WeatherServiceOpenWeatherMap implements WeatherService { @Override public @Nullable WeatherConditions getWeatherConditions(String location) { WeatherConditions.Builder cond = WeatherConditions.newBuilder(); try (InputStream response = getWeatherApiResponse(location)) { JsonParser parser = jsonFactory.createJsonParser(response); String rootKey; do { String fieldKey; switch (Strings.nullToEmpty(rootKey = parser.skipToKey(FIELDS_ROOT))) { case "main": do { switch (Strings.nullToEmpty(fieldKey = parser.skipToKey(FIELDS_MAIN))) { case "temp": cond.setTempFahrenheit((int) parser.getFloatValue()); break; case "humidity": cond.setHumidityPercent(parser.getIntValue() / 100.0); break; } } while (fieldKey != null && parser.nextToken() != null); break; case "wind": do { switch (Strings.nullToEmpty(fieldKey = parser.skipToKey(FIELDS_WIND))) { case "speed": cond.setWindMph((int) parser.getFloatValue()); break; } } while (fieldKey != null && parser.nextToken() != null); break; } } while (rootKey != null && parser.nextToken() != null); } catch (IOException e) { logger.warn("{}: {}", location, e.toString()); return null; } if (logger.isDebugEnabled() && cond.isInitialized()) { logger.debug("{}: {}F, {}mph, {}%", location, cond.getTempFahrenheit(), cond.getWindMph(), cond.getHumidityPercent()); } return cond.isInitialized() ? cond.build() : null; } WeatherServiceOpenWeatherMap(JsonFactory jsonFactory, HttpTransport httpTransport); @Override @Nullable WeatherConditions getWeatherConditions(String location);  }
@Test public void testConditions() { if (!ENABLED) { return; } WeatherConditions cond = service.getWeatherConditions(LOCATION); assertNotNull(cond); assertNotNull(cond.getTempFahrenheit()); assertNotNull(cond.getHumidityPercent()); assertNotNull(cond.getWindMph()); }
@Test public void testCache() { if (!ENABLED) { return; } WeatherService cache = new WeatherServiceCache( TIMEOUT, service, MoreExecutors.newDirectExecutorService()); Stopwatch stopwatch1 = Stopwatch.createStarted(); assertNotNull(cache.getWeatherConditions(LOCATION)); logger.info("Weather lookup time (cache miss): {}ms", stopwatch1.elapsed(TimeUnit.MILLISECONDS)); Stopwatch stopwatch2 = Stopwatch.createStarted(); assertNotNull(cache.getWeatherConditions(LOCATION)); long time2 = stopwatch2.elapsed(TimeUnit.MILLISECONDS); logger.info("Weather lookup time (cache hit): {}ms", time2); if (time2 >= 1000) { logger.warn("That was slow!"); } }
@Test public void testCacheTimeout() throws InterruptedException { if (!ENABLED) { return; } WeatherService cache = new WeatherServiceCache( 0, service, Executors.newFixedThreadPool(1, new ThreadFactory() { @Override public Thread newThread(final Runnable r) { return new Thread() { @Override public void run() { try { sleep(20L); } catch (InterruptedException e) {} r.run(); }}; }})); assertNull(cache.getWeatherConditions(LOCATION)); Thread.sleep(TIMEOUT); assertNotNull(cache.getWeatherConditions(LOCATION)); }