klawisch.jimdo.statistics.statisticsdemo.DownloaderThread.java Source code

Java tutorial

Introduction

Here is the source code for klawisch.jimdo.statistics.statisticsdemo.DownloaderThread.java

Source

/*
The MIT License (MIT)
    
Copyright (c) 2015 Justus Klawisch
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */

package klawisch.jimdo.statistics.statisticsdemo;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import klawisch.jimdo.statistics.statisticsdemo.model.DayStatistics;

/**
 * Created by Klawisch on 05.07.15.
 */
public class DownloaderThread extends Thread {
    private static final String TAG = DownloaderThread.class.getSimpleName();

    private final Random random = new Random();
    private static final int MAX_RANDOM = 300;
    private List<String> dates;
    private Context context;
    private Callback callback;

    public interface Callback {

        // Is called whend the download progress has started
        void downloadStarted();

        // Is called whend the download progress is finished
        void downloadFinished(ArrayList<DayStatistics> statistics);

        // Passes the actual downloading progress
        void updateProgress(int downloaded, int total);
    }

    public static void startDownload(Context context, String baseURL) {
        new DownloaderThread(context, baseURL);
    }

    /**
     * Downloads all available statistic files.
     * First step is to download the file where all available dates are listed. Next step is to
     * iterate the array and download the detailed statistics
     * @param context Context of the calling activity
     * @param baseURL URL of the dates containing file
     */
    public DownloaderThread(Context context, String baseURL) {

        if (context != null && baseURL != null) {
            this.context = context;
            this.callback = (Callback) context;

            JSONObject baseStatistics = getURLContent(baseURL);

            if (baseStatistics != null) {
                try {
                    if (baseStatistics.has("available_dates") && !baseStatistics.isNull("available_dates")) {
                        JSONArray availableDates = baseStatistics.getJSONArray("available_dates");

                        if (availableDates.length() > 0) {
                            int length = availableDates.length();

                            dates = new ArrayList<>();

                            for (int i = 0; i < length; i++) {
                                String date = availableDates.optString(i, null) + ".json";
                                if (date.length() > 0)
                                    dates.add(date);
                            }

                            if (dates.size() > 0)
                                start();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void run() {
        super.run();

        callback.downloadStarted();

        ArrayList<DayStatistics> statistics = new ArrayList<>();
        Iterator<String> iterator = dates.iterator();
        int downloaded = 0;
        int total = dates.size();

        callback.updateProgress(downloaded, total);

        while (iterator.hasNext()) {
            JSONObject jsonObject = getURLContent(iterator.next());
            callback.updateProgress(++downloaded, total);

            if (jsonObject != null)
                statistics.add(StatisticsFactory.createDayStatistics(jsonObject));

            try {
                Thread.sleep(random.nextInt(MAX_RANDOM));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        callback.downloadFinished(statistics);
    }

    /**
     * Downloads the content of a specific url and parses this to a JSONObject
     *
     * @param url The url to download the content
     * @return Returns the parsed JSONObject for further processing
     */
    private JSONObject getURLContent(String url) {
        if (url != null) {
            try {
                InputStream in = context.getAssets().open(url);

                int size = in.available();
                byte[] buffer = new byte[size];
                in.read(buffer);
                in.close();
                return new JSONObject(new String(buffer, "UTF-8"));

            } catch (Exception e) {
                Log.e(TAG, "WARNING: File \"" + url + "\" not found!");

            }
        }
        return null;
    }
}