|
| 1 | +package com.github.dockerjava.api.model; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonFactory; |
| 4 | +import com.fasterxml.jackson.core.JsonParser; |
| 5 | +import com.fasterxml.jackson.core.JsonToken; |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import com.github.dockerjava.api.command.EventCallback; |
| 8 | +import com.google.common.base.Preconditions; |
| 9 | + |
| 10 | +import javax.ws.rs.client.WebTarget; |
| 11 | +import javax.ws.rs.core.Response; |
| 12 | +import java.io.InputStream; |
| 13 | +import java.util.concurrent.Callable; |
| 14 | + |
| 15 | +/** |
| 16 | + * EventNotifier API |
| 17 | + */ |
| 18 | +public class EventNotifier implements Callable<Void> { |
| 19 | + private static final JsonFactory JSON_FACTORY = new JsonFactory(); |
| 20 | + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); |
| 21 | + |
| 22 | + private final EventCallback eventCallback; |
| 23 | + private final WebTarget webTarget; |
| 24 | + |
| 25 | + private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { |
| 26 | + this.eventCallback = eventCallback; |
| 27 | + this.webTarget = webTarget; |
| 28 | + } |
| 29 | + |
| 30 | + public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { |
| 31 | + Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); |
| 32 | + Preconditions.checkNotNull(webTarget, "An WebTarget must be provided"); |
| 33 | + return new EventNotifier(eventCallback, webTarget); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public Void call() throws Exception { |
| 38 | + Response response = webTarget.request().get(Response.class); |
| 39 | + InputStream inputStream = response.readEntity(InputStream.class); |
| 40 | + try { |
| 41 | + JsonParser jp = JSON_FACTORY.createParser(inputStream); |
| 42 | + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { |
| 43 | + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); |
| 44 | + } |
| 45 | + } finally { |
| 46 | + if (response != null) { |
| 47 | + response.close(); |
| 48 | + } |
| 49 | + } |
| 50 | + return null; |
| 51 | + } |
| 52 | +} |
0 commit comments