Created
May 26, 2017 15:27
-
-
Save OleksandrKucherenko/b626877f56ec0dd39f3c7ee536940453 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package /* YOUR PROJECT PACKAGE */.utils; | |
import android.support.annotation.*; | |
import java.net.InetAddress; | |
import java.net.UnknownHostException; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.TimeoutException; | |
import okhttp3.Dns; | |
import rx.Observable; | |
import rx.schedulers.Schedulers; | |
/** implements DNS lookup/resolve client with timeout feature. */ | |
public class DnsEx implements Dns { | |
/** Empty instance used as indicator of TIMEOUT exception. */ | |
private static final List<InetAddress> TIMEOUT = Collections.emptyList(); | |
/** timeout in millis. */ | |
private final long mTimeoutDns; | |
/** Hidden constructor. */ | |
private DnsEx(final long dnsTimeoutMillis) { | |
mTimeoutDns = dnsTimeoutMillis; | |
} | |
/** Create a new instance with specific timeout. */ | |
@NonNull | |
public static DnsEx timeout(final int time, @NonNull final TimeUnit units) { | |
final long millis = units.toMillis(time); | |
return new DnsEx(millis); | |
} | |
/** {@inheritDoc} */ | |
@Override | |
public List<InetAddress> lookup(@NonNull final String address) throws UnknownHostException { | |
final List<InetAddress> results = Observable.fromCallable( | |
new Callable<List<InetAddress>>() { | |
@Override | |
public List<InetAddress> call() throws Exception { | |
return Dns.SYSTEM.lookup(address); | |
} | |
}) | |
.subscribeOn(Schedulers.computation()) | |
.timeout(mTimeoutDns, TimeUnit.MILLISECONDS, Observable.just(TIMEOUT)) | |
.toBlocking() | |
.firstOrDefault(TIMEOUT); | |
if (TIMEOUT == results) { | |
final String message = "Cannot resolve '" + address + "' in " + mTimeoutDns + " ms."; | |
// wrap Timeout exception into UnknownHostException | |
final UnknownHostException unknown = new UnknownHostException(address); | |
unknown.initCause(new TimeoutException(message)); | |
throw unknown; | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: