44import java .io .InputStream ;
55import java .io .InputStreamReader ;
66import java .io .FileInputStream ;
7+ import java .net .HttpURLConnection ;
78import java .net .URL ;
9+ import java .net .URLConnection ;
810import java .net .InetAddress ;
911import java .util .Arrays ;
1012import java .util .ArrayList ;
2224import com .google .transit .realtime .GtfsRealtime .Position ;
2325
2426public class MonitorPositionUpdates {
27+ private static final String API_KEY_ARG = "-api-key" ;
28+ private static final String API_KEY_NAME_ARG = "-api-key-name" ;
2529 private static final String RAW_ARG = "-raw" ;
2630 private static final String CSV_ARG = "-csvoutput" ;
2731 private static final String ID_ARG = "-id" ;
@@ -196,6 +200,8 @@ private static String getIP(URL url) throws Exception {
196200 public static void main (String [] arg ) throws Exception {
197201 String id = null ;
198202 String lookupFile = null ;
203+ String apiKeyName = "x-api-key" ;
204+ String apiKey = null ;
199205 boolean raw = false ;
200206 boolean csvoutput = false ;
201207 boolean help = false ;
@@ -208,6 +214,14 @@ public void run() {
208214 });
209215
210216 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+
211225 if (arg [i ].equals (RAW_ARG )) {
212226 raw = true ;
213227 }
@@ -268,19 +282,35 @@ public void run() {
268282 Util .disableSSLChecking ();
269283 }
270284
271- try (InputStream is = url .openStream ()) {
272- FeedMessage msg = FeedMessage .parseFrom (is );
285+ URLConnection conn = url .openConnection ();
273286
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+ }
278300 }
279301 }
280302 } else {
281303 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+ }
284314 }
285315
286316 Util .sleep (sleepMillis );
0 commit comments