com.jigarmjoshi.service.task.UploaderTask.java Source code

Java tutorial

Introduction

Here is the source code for com.jigarmjoshi.service.task.UploaderTask.java

Source

package com.jigarmjoshi.service.task;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

import com.jigarmjoshi.database.EntryDao;
import com.jigarmjoshi.database.LastLocationDao;
import com.jigarmjoshi.model.LastLocation;
import com.jigarmjoshi.model.Report;
import com.jigarmjoshi.service.ConfigService;
import com.jigarmjoshi.utils.FlagState;
import com.jigarmjoshi.utils.Utility;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * @author jigar.joshi
 * 
 */
public class UploaderTask extends TimerTask {
    private final String serverUrl;
    private final Context context;

    public UploaderTask(Context context) {
        serverUrl = ConfigService.get(ConfigService.SERVER_URL_KEY, "http://192.168.0.104:4567");
        if (serverUrl == null) {
            throw new RuntimeException("could not get server");
        }

        this.context = context;
    }

    @Override
    public void run() {
        EntryDao entryDao = EntryDao.getInstance(context);
        List<Report> entries = null;
        try {
            entries = entryDao.listEntries();
        } catch (Exception ex) {

        }
        if (entries == null) {
            return;
        }
        for (Report entry : entries) {
            boolean uploaded = uploadEntryReport(entry);
            if (uploaded) {
                EntryDao.getInstance(context).deleteEntry(entry);
            } else {
                entry.setUploaded(false);
                EntryDao.getInstance(context).updateEntry(entry);
            }
        }
        Location location = FlagState.getLastDetectedLocation();
        if (location != null) {
            LastLocationDao lastLocationDao = LastLocationDao.getInstance(context);
            LastLocation lastLocation = new LastLocation();
            lastLocationDao.deleteAll();
            lastLocation.setLat(String.valueOf(location.getLatitude()));
            lastLocation.setLon(String.valueOf(location.getLongitude()));
            lastLocationDao.saveLastLocation(lastLocation);
        }
    }

    private final boolean uploadEntryReport(Report entry) {
        if (entry == null || entry.getUploaded()) {
            return true;
        }
        boolean resultFlag = false;
        try {
            Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName());
            Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 60, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord");
            ByteArrayBody bab = new ByteArrayBody(data, "report.jpg");
            // File file= new File("/mnt/sdcard/forest.png");
            // FileBody bin = new FileBody(file);
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat())));
            reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon())));
            reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority())));
            reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName())));
            reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId())));
            reqEntity.addPart("uploaded", bab);
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder responseString = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                responseString = responseString.append(sResponse);
            }
            Log.i(UploaderTask.class.getSimpleName(), responseString.toString());
            if ("SUCCESS".equalsIgnoreCase(responseString.toString())) {
                resultFlag = true;
                if (entry.getImageFileName() != null) {
                    File imageFileToDelete = new File(entry.getImageFileName());
                    boolean deleted = imageFileToDelete.delete();

                    if (deleted) {
                        Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted);
                        MediaScannerConnection.scanFile(context, new String[] {

                                imageFileToDelete.getAbsolutePath() },

                                null, new MediaScannerConnection.OnScanCompletedListener() {

                                    public void onScanCompleted(String path, Uri uri)

                                {

                                    }

                                });

                    }
                }
            }

        } catch (Exception ex) {
            Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex);
            resultFlag = false;
        }
        return resultFlag;
    }
}