4
4
import java .io .InputStream ;
5
5
import java .io .InputStreamReader ;
6
6
import java .io .FileInputStream ;
7
+ import java .net .HttpURLConnection ;
7
8
import java .net .URL ;
9
+ import java .net .URLConnection ;
8
10
import java .net .InetAddress ;
9
11
import java .util .Arrays ;
10
12
import java .util .ArrayList ;
22
24
import com .google .transit .realtime .GtfsRealtime .Position ;
23
25
24
26
public class MonitorPositionUpdates {
27
+ private static final String API_KEY_ARG = "-api-key" ;
28
+ private static final String API_KEY_NAME_ARG = "-api-key-name" ;
25
29
private static final String RAW_ARG = "-raw" ;
26
30
private static final String CSV_ARG = "-csvoutput" ;
27
31
private static final String ID_ARG = "-id" ;
@@ -196,6 +200,8 @@ private static String getIP(URL url) throws Exception {
196
200
public static void main (String [] arg ) throws Exception {
197
201
String id = null ;
198
202
String lookupFile = null ;
203
+ String apiKeyName = "x-api-key" ;
204
+ String apiKey = null ;
199
205
boolean raw = false ;
200
206
boolean csvoutput = false ;
201
207
boolean help = false ;
@@ -208,6 +214,14 @@ public void run() {
208
214
});
209
215
210
216
for (int i =0 ; i <arg .length ; i ++) {
217
+ if (arg [i ].equals (API_KEY_ARG ) && i + 1 < arg .length ) {
218
+ apiKey = arg [++i ];
219
+ }
220
+
221
+ if (arg [i ].equals (API_KEY_NAME_ARG ) && i + 1 < arg .length ) {
222
+ apiKeyName = arg [++i ];
223
+ }
224
+
211
225
if (arg [i ].equals (RAW_ARG )) {
212
226
raw = true ;
213
227
}
@@ -268,19 +282,35 @@ public void run() {
268
282
Util .disableSSLChecking ();
269
283
}
270
284
271
- try (InputStream is = url .openStream ()) {
272
- FeedMessage msg = FeedMessage .parseFrom (is );
285
+ URLConnection conn = url .openConnection ();
273
286
274
- if (!csvoutput ) {
275
- dumpRawFeed (msg , id != null ? id : url .toString ());
276
- } else {
277
- dumpCSV (msg );
287
+ try (AutoCloseable ac = () -> ((HttpURLConnection )conn ).disconnect ()) {
288
+ if (apiKey != null ) {
289
+ conn .setRequestProperty (apiKeyName , apiKey );
290
+ }
291
+
292
+ try (InputStream is = conn .getInputStream ()) {
293
+ FeedMessage msg = FeedMessage .parseFrom (is );
294
+
295
+ if (!csvoutput ) {
296
+ dumpRawFeed (msg , id != null ? id : url .toString ());
297
+ } else {
298
+ dumpCSV (msg );
299
+ }
278
300
}
279
301
}
280
302
} else {
281
303
for (;;) {
282
- try (InputStream is = url .openStream ()) {
283
- dumpFeed (FeedMessage .parseFrom (is ), id );
304
+ URLConnection conn = url .openConnection ();
305
+
306
+ try (AutoCloseable ac = () -> ((HttpURLConnection )conn ).disconnect ()) {
307
+ if (apiKey != null ) {
308
+ conn .setRequestProperty (apiKeyName , apiKey );
309
+ }
310
+
311
+ try (InputStream is = conn .getInputStream ()) {
312
+ dumpFeed (FeedMessage .parseFrom (is ), id );
313
+ }
284
314
}
285
315
286
316
Util .sleep (sleepMillis );
0 commit comments