eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java Source code

Java tutorial

Introduction

Here is the source code for eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

Source

/*
 *     Cos android client for Cozy Cloud
 *
 *     Copyright (C)  2016 Hamza Abdelkebir
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package eu.codeplumbers.cosi.api.tasks;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Base64;

import com.activeandroid.query.Delete;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import eu.codeplumbers.cosi.db.models.Device;
import eu.codeplumbers.cosi.db.models.Note;
import eu.codeplumbers.cosi.db.models.Place;
import eu.codeplumbers.cosi.fragments.NoteListFragment;
import eu.codeplumbers.cosi.fragments.PlacesFragment;
import eu.codeplumbers.cosi.utils.DateUtils;

public class GetPlacesTask extends AsyncTask<Void, String, List<Place>> {

    private final String url;
    private final String authHeader;
    private PlacesFragment placesFragment;
    private List<Place> allPlaces;
    private String errorMessage;
    private ProgressDialog dialog;

    public GetPlacesTask(PlacesFragment placesFragment) {
        this.placesFragment = placesFragment;
        allPlaces = new ArrayList<>();

        Device device = Device.registeredDevice();

        // delete all local places
        new Delete().from(Place.class).execute();

        // cozy register device url
        this.url = device.getUrl() + "/ds-api/request/place/all/";

        // concatenate username and password with colon for authentication
        final String credentials = device.getLogin() + ":" + device.getPassword();
        authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

        dialog = new ProgressDialog(placesFragment.getActivity());
        dialog.setCancelable(false);
        dialog.setMessage("Please wait");
        dialog.setIndeterminate(true);
        dialog.show();

    }

    @Override
    protected List<Place> doInBackground(Void... voids) {
        URL urlO = null;
        try {
            urlO = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONArray jsonArray = new JSONArray(result);

            if (jsonArray != null) {
                if (jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        String version = "0";
                        if (jsonArray.getJSONObject(i).has("version")) {
                            version = jsonArray.getJSONObject(i).getString("version");
                        }
                        JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Place place = Place.getByLocation(placeJson.get("description").toString(),
                                placeJson.get("latitude").toString(), placeJson.get("longitude").toString());

                        if (place == null) {
                            place = new Place(placeJson);
                        } else {
                            place.setDeviceId(placeJson.getString("deviceId"));
                            place.setAddress(placeJson.getString("address"));
                            place.setDateAndTime(placeJson.getString("dateAndTime"));
                            place.setLongitude(placeJson.getDouble("longitude"));
                            place.setLatitude(placeJson.getDouble("latitude"));
                            place.setRemoteId(placeJson.getString("_id"));
                        }

                        publishProgress("Saving place : " + place.getAddress());
                        place.save();

                        allPlaces.add(place);
                    }
                } else {
                    publishProgress("Your Cozy has no places stored.");
                    return allPlaces;
                }
            } else {
                errorMessage = "Failed to parse API response";
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }

        return allPlaces;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        dialog.setMessage(values[0]);
    }

    @Override
    protected void onPostExecute(List<Place> places) {
        super.onPostExecute(places);

        dialog.cancel();

        if (errorMessage != "") {
            placesFragment.refreshLocationsOnMap();
        } else {
            placesFragment.onSyncFailure(errorMessage);
        }
    }
}