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

Java tutorial

Introduction

Here is the source code for eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.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.support.v4.app.Fragment;
import android.util.Base64;

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

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import eu.codeplumbers.cosi.db.models.Device;
import eu.codeplumbers.cosi.fragments.AboutFragment;
import eu.codeplumbers.cosi.fragments.FileManagerFragment;
import eu.codeplumbers.cosi.wizards.firstrun.ApplicationFragment;
import eu.codeplumbers.cosi.wizards.firstrun.ConnectFragment;

public class CheckDesignDocumentsTask extends AsyncTask<String, String, String> {

    private final String authHeader;
    private final String url;
    private Fragment connectFragment;
    private String errorMessage;
    private ProgressDialog dialog;

    public CheckDesignDocumentsTask(Fragment connectFragment) {
        this.connectFragment = connectFragment;

        Device device = Device.registeredDevice();

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

        // 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(connectFragment.getActivity());
        dialog.setCancelable(false);
        dialog.setMessage("Please wait");
        dialog.setIndeterminate(true);
        dialog.show();

    }

    @Override
    protected String doInBackground(String... docTypes) {
        errorMessage = "";
        for (int i = 0; i < docTypes.length; i++) {
            String docType = docTypes[i].toLowerCase();
            publishProgress("Checking design: " + docType);

            URL urlO = null;
            try {

                // using all view can break notes, files app in cozy
                urlO = getCosiUrl(docType);

                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();

                if (result != "") {
                    errorMessage = createDesignDocument(docType);
                    if (errorMessage != "") {
                        return errorMessage;
                    } else {
                        errorMessage = "";
                    }
                } else {
                    errorMessage = "Failed to parse API response";
                    return errorMessage;
                }

                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();
            }
        }

        return errorMessage;
    }

    private URL getCosiUrl(String docType) throws MalformedURLException {
        URL urlO = null;
        if (docType.equalsIgnoreCase("Note") || (docType.equalsIgnoreCase("File"))
                || (docType.equalsIgnoreCase("Folder"))) {
            urlO = new URL(url.replace("???", docType) + "cosiall/");
        } else {
            urlO = new URL(url.replace("???", docType) + "all/");
        }

        return urlO;
    }

    private String createDesignDocument(String docType) {
        String returnResult = "";
        JSONObject docTypeMap = new JSONObject();
        try {
            docTypeMap.put("map", "function (doc) { if (doc.docType.toLowerCase() === '" + docType
                    + "') { filter = function (doc) { return emit(doc._id, doc); }; filter(doc); }}");

            URL urlO = getCosiUrl(docType);

            String requestMethod = "PUT";

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            OutputStream os = conn.getOutputStream();
            os.write(docTypeMap.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

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

            if (result.contains("success")) {
                returnResult = "";
            } else {
                returnResult = result;
            }

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

        } catch (UnsupportedEncodingException e) {
            returnResult = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (ProtocolException e) {
            returnResult = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            returnResult = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            returnResult = e.getLocalizedMessage();
            e.printStackTrace();
        }

        return returnResult;
    }

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

        dialog.setMessage(values[0]);
    }

    @Override
    protected void onPostExecute(String errorMessage) {
        super.onPostExecute(errorMessage);

        dialog.cancel();

        if (errorMessage == "") {
            if (connectFragment instanceof ConnectFragment)
                ((ConnectFragment) connectFragment).onDesignsOK();
            if (connectFragment instanceof AboutFragment)
                ((AboutFragment) connectFragment).onDesignsOK();

        } else {

            if (connectFragment instanceof ConnectFragment)
                ((ConnectFragment) connectFragment).onDesignFailure(errorMessage);
            if (connectFragment instanceof AboutFragment)
                ((AboutFragment) connectFragment).onDesignFailure(errorMessage);
        }
    }
}