1/*
2 * Copyright (C) 2014 Square, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.squareup.okhttp.benchmarks;
17
18import com.squareup.okhttp.HttpUrl;
19import com.squareup.okhttp.internal.SslContextBuilder;
20import java.io.IOException;
21import java.io.InputStream;
22import java.net.HttpURLConnection;
23import java.util.concurrent.TimeUnit;
24import java.util.zip.GZIPInputStream;
25import javax.net.ssl.HostnameVerifier;
26import javax.net.ssl.HttpsURLConnection;
27import javax.net.ssl.SSLContext;
28import javax.net.ssl.SSLSession;
29import javax.net.ssl.SSLSocketFactory;
30
31class UrlConnection extends SynchronousHttpClient {
32  private static final boolean VERBOSE = false;
33
34  @Override public void prepare(Benchmark benchmark) {
35    super.prepare(benchmark);
36    if (benchmark.tls) {
37      SSLContext sslContext = SslContextBuilder.localhost();
38      SSLSocketFactory socketFactory = sslContext.getSocketFactory();
39      HostnameVerifier hostnameVerifier = new HostnameVerifier() {
40        @Override public boolean verify(String s, SSLSession session) {
41          return true;
42        }
43      };
44      HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
45      HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
46    }
47  }
48
49  @Override public Runnable request(HttpUrl url) {
50    return new UrlConnectionRequest(url);
51  }
52
53  static class UrlConnectionRequest implements Runnable {
54    private final HttpUrl url;
55
56    public UrlConnectionRequest(HttpUrl url) {
57      this.url = url;
58    }
59
60    public void run() {
61      long start = System.nanoTime();
62      try {
63        HttpURLConnection urlConnection = (HttpURLConnection) url.url().openConnection();
64        InputStream in = urlConnection.getInputStream();
65        if ("gzip".equals(urlConnection.getHeaderField("Content-Encoding"))) {
66          in = new GZIPInputStream(in);
67        }
68
69        long total = readAllAndClose(in);
70        long finish = System.nanoTime();
71
72        if (VERBOSE) {
73          System.out.println(String.format("Transferred % 8d bytes in %4d ms",
74              total, TimeUnit.NANOSECONDS.toMillis(finish - start)));
75        }
76      } catch (IOException e) {
77        System.out.println("Failed: " + e);
78      }
79    }
80  }
81}
82