OffrzLoader extends AsyncTaskLoader<JSONObject> { @Override public JSONObject loadInBackground() { final File cachedOffrzFile = getCacheFile(); final JSONObject cachedOffrz = getCachedOffrz(cachedOffrzFile); if(cachedOffrz != null){ return cachedOffrz; } JSONObject firstOffrz; try { final URL url = new URL(getEndpoint()); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); final String response = StreamUtils.readTextStream(connection.getInputStream()); connection.disconnect(); final JSONArray offrz = new JSONArray(response); firstOffrz = offrz.getJSONObject(0); final long now = System.currentTimeMillis() / 1000L; firstOffrz.put(DOWNLOAD_DATE, now); if (expired(firstOffrz)) { return null; } } catch (MalformedURLException e) { Timber.e("Malformed hardcoded url%s", getEndpoint()); return null; } catch (IOException e) { Timber.e(e,"Can't open connection to %s", getEndpoint()); return null; } catch (JSONException e) { Timber.e("Can't parse json response"); return null; } catch (Exception e) { Timber.e(e,"Generic failure"); return null; } try { FileUtils.writeTextToFile(cachedOffrzFile, firstOffrz.toString()); } catch (IOException e) { Timber.e("Can't cache data to %s", MYOFFRZ_CACHE_FILE); } return firstOffrz; } OffrzLoader(@NonNull Context context); JSONObject getCachedOffrz(File cachedOffrzFile); @Override JSONObject loadInBackground(); @Override void deliverResult(JSONObject data); static final long SIX_HOURS_IN_S; static final String VALIDITY_KEY; }
@Test public void checkFileNotExistDownloadNewFile(){ assertFalse(cacheFile.exists()); assertNotNull(loader.loadInBackground()); }