|
| 1 | +/**************************************************************************** |
| 2 | + * Copyright 2016-2017,2021, Optimizely, Inc. and contributors * |
| 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 | + ***************************************************************************/ |
| 16 | + |
| 17 | +package com.optimizely.ab.android.shared; |
| 18 | + |
| 19 | +import android.os.Build; |
| 20 | + |
| 21 | +import androidx.annotation.NonNull; |
| 22 | +import androidx.annotation.Nullable; |
| 23 | + |
| 24 | +import org.slf4j.Logger; |
| 25 | + |
| 26 | +import java.io.BufferedInputStream; |
| 27 | +import java.io.InputStream; |
| 28 | +import java.net.HttpURLConnection; |
| 29 | +import java.net.URL; |
| 30 | +import java.net.URLConnection; |
| 31 | +import java.util.Scanner; |
| 32 | +import java.util.concurrent.TimeUnit; |
| 33 | + |
| 34 | +import javax.net.ssl.HttpsURLConnection; |
| 35 | +import javax.net.ssl.SSLContext; |
| 36 | +import javax.net.ssl.SSLSocketFactory; |
| 37 | + |
| 38 | +/** |
| 39 | + * Functionality common to all clients using http connections |
| 40 | + */ |
| 41 | +public class ClientForODPOnly { |
| 42 | + |
| 43 | + static final int MAX_BACKOFF_TIMEOUT = (int) Math.pow(2, 5); |
| 44 | + |
| 45 | + @NonNull private final OptlyStorage optlyStorage; |
| 46 | + @NonNull private final Logger logger; |
| 47 | + |
| 48 | + /** |
| 49 | + * Constructs a new Client instance |
| 50 | + * |
| 51 | + * @param optlyStorage an instance of {@link OptlyStorage} |
| 52 | + * @param logger an instance of {@link Logger} |
| 53 | + */ |
| 54 | + public ClientForODPOnly(@NonNull OptlyStorage optlyStorage, @NonNull Logger logger) { |
| 55 | + this.optlyStorage = optlyStorage; |
| 56 | + this.logger = logger; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Opens {@link HttpURLConnection} from a {@link URL} |
| 61 | + * |
| 62 | + * @param url a {@link URL} instance |
| 63 | + * @return an open {@link HttpURLConnection} |
| 64 | + */ |
| 65 | + @Nullable |
| 66 | + public HttpURLConnection openConnection(URL url) { |
| 67 | + try { |
| 68 | + // API 21 (LOLLIPOP)+ supposed to use TLS1.2 as default, but some API-21 devices still fail, so include it here. |
| 69 | + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) { |
| 70 | + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); |
| 71 | + sslContext.init(null, null, null); |
| 72 | + SSLSocketFactory sslSocketFactory = new TLSSocketFactory(); |
| 73 | + HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); |
| 74 | + } |
| 75 | + |
| 76 | + return (HttpURLConnection) url.openConnection(); |
| 77 | + } catch (Exception e) { |
| 78 | + logger.warn("Error making request to {}.", url); |
| 79 | + } |
| 80 | + return null; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Adds a if-modified-since header to the open {@link URLConnection} if this value is |
| 85 | + * stored in {@link OptlyStorage}. |
| 86 | + * @param urlConnection an open {@link URLConnection} |
| 87 | + */ |
| 88 | + public void setIfModifiedSince(@NonNull URLConnection urlConnection) { |
| 89 | + if (urlConnection == null || urlConnection.getURL() == null) { |
| 90 | + logger.error("Invalid connection"); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + long lastModified = optlyStorage.getLong(urlConnection.getURL().toString(), 0); |
| 95 | + if (lastModified > 0) { |
| 96 | + urlConnection.setIfModifiedSince(lastModified); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Retrieves the last-modified head from a {@link URLConnection} and saves it |
| 102 | + * in {@link OptlyStorage}. |
| 103 | + * @param urlConnection a {@link URLConnection} instance |
| 104 | + */ |
| 105 | + public void saveLastModified(@NonNull URLConnection urlConnection) { |
| 106 | + if (urlConnection == null || urlConnection.getURL() == null) { |
| 107 | + logger.error("Invalid connection"); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + long lastModified = urlConnection.getLastModified(); |
| 112 | + if (lastModified > 0) { |
| 113 | + optlyStorage.saveLong(urlConnection.getURL().toString(), urlConnection.getLastModified()); |
| 114 | + } else { |
| 115 | + logger.warn("CDN response didn't have a last modified header"); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + @Nullable |
| 120 | + public String readStream(@NonNull URLConnection urlConnection) { |
| 121 | + Scanner scanner = null; |
| 122 | + try { |
| 123 | + InputStream in = new BufferedInputStream(urlConnection.getInputStream()); |
| 124 | + scanner = new Scanner(in).useDelimiter("\\A"); |
| 125 | + return scanner.hasNext() ? scanner.next() : ""; |
| 126 | + } catch (Exception e) { |
| 127 | + logger.warn("Error reading urlConnection stream.", e); |
| 128 | + return null; |
| 129 | + } |
| 130 | + finally { |
| 131 | + if (scanner != null) { |
| 132 | + // We assume that closing the scanner will close the associated input stream. |
| 133 | + try { |
| 134 | + scanner.close(); |
| 135 | + } |
| 136 | + catch (Exception e) { |
| 137 | + logger.error("Problem with closing the scanner on a input stream" , e); |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Executes a request with exponential backoff |
| 145 | + * @param request the request executable, would be a lambda on Java 8 |
| 146 | + * @param timeout the numerical base for the exponential backoff |
| 147 | + * @param power the number of retries |
| 148 | + * @param <T> the response type of the request |
| 149 | + * @return the response |
| 150 | + */ |
| 151 | + public <T> T execute(Request<T> request, int timeout, int power) { |
| 152 | + int baseTimeout = timeout; |
| 153 | + int maxTimeout = (int) Math.pow(baseTimeout, power); |
| 154 | + T response = null; |
| 155 | + while(timeout <= maxTimeout) { |
| 156 | + try { |
| 157 | + response = request.execute(); |
| 158 | + } catch (Exception e) { |
| 159 | + logger.error("(ClientForODPOnly) Request failed with error: ", e); |
| 160 | + throw e; |
| 161 | + } |
| 162 | + |
| 163 | + if (response == null || response == Boolean.FALSE) { |
| 164 | + // retry is disabled when timeout set to 0 |
| 165 | + if (timeout == 0) break; |
| 166 | + |
| 167 | + try { |
| 168 | + logger.info("Request failed, waiting {} seconds to try again", timeout); |
| 169 | + Thread.sleep(TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS)); |
| 170 | + } catch (InterruptedException e) { |
| 171 | + logger.warn("Exponential backoff failed", e); |
| 172 | + break; |
| 173 | + } |
| 174 | + timeout = timeout * baseTimeout; |
| 175 | + } else { |
| 176 | + break; |
| 177 | + } |
| 178 | + } |
| 179 | + return response; |
| 180 | + } |
| 181 | + |
| 182 | + /** |
| 183 | + * Bundles up a request allowing it's execution to be deferred |
| 184 | + * @param <T> The response type of the request |
| 185 | + */ |
| 186 | + public interface Request<T> { |
| 187 | + T execute(); |
| 188 | + } |
| 189 | +} |
0 commit comments