Example usage for org.apache.http.protocol RequestConnControl RequestConnControl

List of usage examples for org.apache.http.protocol RequestConnControl RequestConnControl

Introduction

In this page you can find the example usage for org.apache.http.protocol RequestConnControl RequestConnControl.

Prototype

RequestConnControl

Source Link

Usage

From source file:us.pserver.revok.channel.HttpRequestChannel.java

/**
 * Init some objects for http communication.
 *//*from  ww w .j ava 2s. co m*/
private void init() {
    algo = CryptAlgorithm.AES_CBC_PKCS5;
    context = HttpCoreContext.create();
    context.setTargetHost(
            new HttpHost((netc.getAddress() == null ? "localhost" : netc.getAddress()), netc.getPort()));
    processor = HttpProcessorBuilder.create().add(new RequestContent()).add(new RequestTargetHost())
            .add(new RequestUserAgent(HttpConsts.HD_VAL_USER_AGENT)).add(new RequestConnControl()).build();
}

From source file:NioHttpClient.java

public NioHttpClient(String user_agent, HttpRequestExecutionHandler request_handler,
        EventListener connection_listener) throws Exception {

    // Construct the long-lived HTTP parameters.
    HttpParams parameters = new BasicHttpParams();
    parameters/*w w w  .  j  a  v  a  2s.c  o  m*/
            // Socket data timeout is 5,000 milliseconds (5 seconds).
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            // Maximum time allowed for connection establishment is 10,00 milliseconds (10 seconds).
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            // Socket buffer size is 8 kB.
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            // Don't bother to check for stale TCP connections.
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            // Don't use Nagle's algorithm (in other words minimize latency).
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            // Set the user agent string that the client sends to the server.
            .setParameter(CoreProtocolPNames.USER_AGENT, user_agent);

    // Construct the core HTTP request processor.
    BasicHttpProcessor http_processor = new BasicHttpProcessor();
    // Add Content-Length header to request where appropriate.
    http_processor.addInterceptor(new RequestContent());
    // Always include Host header in requests.
    http_processor.addInterceptor(new RequestTargetHost());
    // Maintain connection keep-alive by default.
    http_processor.addInterceptor(new RequestConnControl());
    // Include user agent information in each request.
    http_processor.addInterceptor(new RequestUserAgent());

    // Allocate an HTTP client handler.
    BufferingHttpClientHandler client_handler = new BufferingHttpClientHandler(http_processor, // Basic HTTP Processor.
            request_handler, new DefaultConnectionReuseStrategy(), parameters);
    client_handler.setEventListener(connection_listener);

    // Use two worker threads for the IO reactor.
    io_reactor = new DefaultConnectingIOReactor(2, parameters);
    io_event_dispatch = new DefaultClientIOEventDispatch(client_handler, parameters);
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {//from  w  ww  .  j  a va  2s .c  o  m
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//from w w  w.  j  a v a  2s . com

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.droids.protocol.http.DroidsHttpClient.java

@Override
protected BasicHttpProcessor createHttpProcessor() {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}

From source file:com.couchbase.client.ViewNodeTest.java

private AsyncConnectionManager createConMgr(String host, int port) throws IOReactorException {
    HttpHost target = new HttpHost(host, port);
    int maxConnections = 1;

    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "Couchbase Java Client 1.1");

    HttpProcessor httpproc = new ImmutableHttpProcessor(
            new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(),
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(), });

    AsyncNHttpClientHandler protocolHandler = new AsyncNHttpClientHandler(httpproc,
            new ViewNode.MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(),
            new DirectByteBufferAllocator(), params);

    protocolHandler.setEventListener(new ViewNode.EventLogger());
    RequeueOpCallback callback = mock(RequeueOpCallback.class);
    AsyncConnectionManager manager = new AsyncConnectionManager(target, maxConnections, protocolHandler, params,
            callback);/*  w  ww. ja  va  2  s .  c om*/

    return manager;
}

From source file:com.couchbase.client.ViewConnection.java

/**
 * Create ViewNode connections and queue them up for connect.
 *
 * This method also defines the connection params for each connection,
 * including the default settings like timeouts and the user agent string.
 *
 * @param addrs addresses of all the nodes it should connect to.
 * @return Returns a list of the ViewNodes.
 * @throws IOException/*from ww  w  . j  a va 2  s. co  m*/
 */
private List<ViewNode> createConnections(List<InetSocketAddress> addrs) throws IOException {

    List<ViewNode> nodeList = new LinkedList<ViewNode>();

    for (InetSocketAddress a : addrs) {
        HttpParams params = new SyncBasicHttpParams();
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
                .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                .setParameter(CoreProtocolPNames.USER_AGENT, "Couchbase Java Client 1.0.2");

        HttpProcessor httpproc = new ImmutableHttpProcessor(
                new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(),
                        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(), });

        AsyncNHttpClientHandler protocolHandler = new AsyncNHttpClientHandler(httpproc,
                new MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(),
                new DirectByteBufferAllocator(), params);
        protocolHandler.setEventListener(new EventLogger());

        AsyncConnectionManager connMgr = new AsyncConnectionManager(new HttpHost(a.getHostName(), a.getPort()),
                NUM_CONNS, protocolHandler, params, new RequeueOpCallback(this));
        getLogger().info("Added %s to connect queue", a.getHostName());

        ViewNode node = connFactory.createViewNode(a, connMgr);
        node.init();
        nodeList.add(node);
    }

    return nodeList;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {//  ww  w . j a v a  2s  . com
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();

        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");

        Log.v("talon_images", media.toString());

        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");

                // want to check to make sure it doesn't have it already
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return images;
}

From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java

public void ensureRunning() {
    if (original != null) {
        return;//from   w ww . ja v a2  s .c o m
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size()
                + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version)
                            .accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter"))
            .add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json",
            (HttpRequest request, HttpResponse response, HttpContext context) -> {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
        response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);
         */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));

    });
    server = ServerBootstrap.bootstrap().
    // could setLocalAddress if using a JenkinsController that requires it
            setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler())
            .create();

    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;

    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort()
            + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript(
            "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])",
            override);
}