blob: 34b92ac7c043308bdd942be11b97478c929d7cc8 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import java.io.FileNotFoundException
import java.net.{ConnectException, URL}
import scala.concurrent.TimeoutException
import scala.concurrent.duration._
object PollingUtils {
def waitUntilServerAvailable(url: URL): Unit = {
val connected = poll(5.seconds, 250.milliseconds)({
urlConnectionAvailable(url)
})
if (!connected) {
throw new TimeoutException(s"Failed to connect to $url")
}
}
def poll(timeout: FiniteDuration, interval: FiniteDuration)(poll: => Boolean): Boolean = {
val start = System.nanoTime()
def go(): Boolean = {
if (poll) {
true
} else if ((System.nanoTime() - start) > timeout.toNanos) {
false
} else {
Thread.sleep(interval.toMillis)
go()
}
}
go()
}
def urlConnectionAvailable(url: URL): Boolean = {
try {
url.openConnection()
.getInputStream
.close()
true
} catch {
case _: ConnectException => false
case _: FileNotFoundException => true // on 404
}
}
}
|