|
| 1 | +package osgi.enroute.trains.rest.client; |
| 2 | + |
| 3 | +import java.io.InputStream; |
| 4 | +import java.io.UnsupportedEncodingException; |
| 5 | +import java.net.URI; |
| 6 | +import java.net.URL; |
| 7 | +import java.net.URLEncoder; |
| 8 | +import java.util.List; |
| 9 | + |
| 10 | +import org.osgi.service.component.annotations.Reference; |
| 11 | + |
| 12 | +import aQute.lib.converter.TypeReference; |
| 13 | +import aQute.lib.json.Decoder; |
| 14 | +import aQute.lib.json.JSONCodec; |
| 15 | +import osgi.enroute.dto.api.DTOs; |
| 16 | +import osgi.enroute.trains.cloud.api.Observation; |
| 17 | + |
| 18 | +public class TrackClient { |
| 19 | + static JSONCodec codec = new JSONCodec(); |
| 20 | + static TypeReference<List<Observation>> LISTOBSERVATIONS = new TypeReference<List<Observation>>() {}; |
| 21 | + final URI base; |
| 22 | + |
| 23 | + @Reference |
| 24 | + DTOs dtos; |
| 25 | + |
| 26 | + public TrackClient(URI base) { |
| 27 | + this.base = base; |
| 28 | + } |
| 29 | + |
| 30 | + public boolean blocked(String segment, String reason, boolean blocked) throws Exception { |
| 31 | + return (Boolean) send( "blocked", segment, reason, blocked).get(); |
| 32 | + } |
| 33 | + |
| 34 | + Decoder send( Object ... params ) throws Exception { |
| 35 | + StringBuilder sb = new StringBuilder(); |
| 36 | + String del = base.toString(); |
| 37 | + if ( !del.endsWith("/")) |
| 38 | + sb.append("/"); |
| 39 | + |
| 40 | + for ( Object p : params ) { |
| 41 | + sb.append(del).append( encode(p)); |
| 42 | + del = "/"; |
| 43 | + } |
| 44 | + InputStream inputStream = new URL(sb.toString()).openConnection().getInputStream(); |
| 45 | + return codec.dec().from(inputStream); |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + private String encode(Object blocked) throws UnsupportedEncodingException { |
| 50 | + return URLEncoder.encode( ""+blocked, "UTF-8"); |
| 51 | + } |
| 52 | + |
| 53 | + public List<Observation> getRecentObservations(long time) throws Exception { |
| 54 | + return send("observations", time).get(LISTOBSERVATIONS); |
| 55 | + } |
| 56 | +} |
0 commit comments