Author: kmorin Date: 2014-03-03 18:36:04 +0100 (Mon, 03 Mar 2014) New Revision: 63 Url: http://forge.codelutin.com/projects/wlo/repository/revisions/63 Log: setup application sign fixes #4630 [TECH] Mise ?\195?\160 jour automatique de l'application Added: trunk/src/fr/ifremer/wlo/utils/ImportUtil.java Removed: trunk/proguard.cfg trunk/src/fr/ifremer/wlo/imports/ImportUtil.java Modified: trunk/AndroidManifest.xml trunk/pom.xml trunk/res/values-fr/strings.xml trunk/res/values/strings.xml trunk/src/fr/ifremer/wlo/MainActivity.java trunk/src/fr/ifremer/wlo/WloApplication.java trunk/src/fr/ifremer/wlo/WloBaseActivity.java trunk/src/fr/ifremer/wlo/preferences/CategoryCreationAcivity.java trunk/src/fr/ifremer/wlo/preferences/SettingsActivity.java trunk/src/fr/ifremer/wlo/utils/UpdateCheckTask.java Modified: trunk/AndroidManifest.xml =================================================================== --- trunk/AndroidManifest.xml 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/AndroidManifest.xml 2014-03-03 17:36:04 UTC (rev 63) @@ -16,7 +16,7 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fr.ifremer.wlo" android:versionCode="1" - android:versionName="1.0"> + android:versionName="0.2"> <uses-sdk minSdkVersion="15" android:targetSdkVersion="15"/> Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/pom.xml 2014-03-03 17:36:04 UTC (rev 63) @@ -269,9 +269,6 @@ <excludeJarResources> <excludeJarResource>.*nuiton.*</excludeJarResource> </excludeJarResources> - <!--<sign>--> - <!--<debug>false</debug>--> - <!--</sign>--> <!--<device>emulator</device>--> <device>usb</device> <zipalign> @@ -284,9 +281,6 @@ ${project.build.directory}/${project.artifactId}-${project.version}-aligned.apk </outputApk> </zipalign> - <proguard> - <skip>true</skip> <!-- android.proguard.skip --> - </proguard> </configuration> <extensions>true</extensions> </plugin> @@ -324,6 +318,70 @@ <profiles> <profile> + <id>sign</id> + <activation> + <property> + <name>performRelease</name> + <value>true</value> + </property> + </activation> + <build> + <plugins> + <plugin> + <groupId>org.nuiton</groupId> + <artifactId>helper-maven-plugin</artifactId> + <executions> + <execution> + <id>get-keystore</id> + <goals> + <goal>share-server-secret</goal> + </goals> + <phase>package</phase> + <configuration> + <serverId>codelutin-keystore</serverId> + <privateKeyOut>jarsigner.keystore</privateKeyOut> + <passwordOut>jarsigner.storepass</passwordOut> + <usernameOut>jarsigner.alias</usernameOut> + <passphraseOut>jarsigner.keypass</passphraseOut> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jarsigner-plugin</artifactId> + <executions> + <execution> + <id>signing</id> + <goals> + <goal>sign</goal> + </goals> + <phase>package</phase> + <inherited>true</inherited> + <configuration> + <includes> + <include>target/*.apk</include> + </includes> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.jayway.maven.plugins.android.generation2</groupId> + <artifactId>android-maven-plugin</artifactId> + <inherited>true</inherited> + <configuration> + <sign> + <debug>false</debug> + </sign> + </configuration> + </plugin> + </plugins> + </build> + </profile> + + <profile> <id>check-release-profile</id> <activation> <property> Deleted: trunk/proguard.cfg =================================================================== --- trunk/proguard.cfg 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/proguard.cfg 2014-03-03 17:36:04 UTC (rev 63) @@ -1,10 +0,0 @@ --dontoptimize --dontobfuscate --dontwarn javax.annotation.** --dontwarn javax.inject.** --dontwarn sun.misc.Unsafe --dontwarn com.google.common.collect.MinMaxPriorityQueue - --keepclasseswithmembers public class * { - public static void main(java.lang.String[]); -} \ No newline at end of file Modified: trunk/res/values/strings.xml =================================================================== --- trunk/res/values/strings.xml 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/res/values/strings.xml 2014-03-03 17:36:04 UTC (rev 63) @@ -216,4 +216,9 @@ <string name="crash_dialog_comment_prompt">You might add your comments about the problem below:</string> <string name="crash_dialog_ok_toast">Thank you !</string> + <!-- Update --> + <string name="update_dowload_error">Error while downloading the new version of WLO</string> + <string name="update_available_title">New version available</string> + <string name="update_available_message">A new version of WLO is available. Would you like to install it?</string> + </resources> Modified: trunk/res/values-fr/strings.xml =================================================================== --- trunk/res/values-fr/strings.xml 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/res/values-fr/strings.xml 2014-03-03 17:36:04 UTC (rev 63) @@ -208,4 +208,9 @@ <string name="crash_dialog_comment_prompt">Vous pouvez ajouter un commentaire ci-dessous:</string> <string name="crash_dialog_ok_toast">Merci !</string> + <!-- Update --> + <string name="update_dowload_error">Erreur lors du téléchargement de la dernière version de WLO</string> + <string name="update_available_title">Nouvelle version disponible</string> + <string name="update_available_message">Une nouvelle version de WLO est disponible. Voulez-vous la télécharger et l\'installer ?</string> + </resources> Modified: trunk/src/fr/ifremer/wlo/MainActivity.java =================================================================== --- trunk/src/fr/ifremer/wlo/MainActivity.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/MainActivity.java 2014-03-03 17:36:04 UTC (rev 63) @@ -28,8 +28,10 @@ import android.app.AlertDialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; +import android.content.Context; import android.content.Intent; import android.content.res.Configuration; +import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; @@ -40,13 +42,14 @@ import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; -import fr.ifremer.wlo.imports.ImportUtil; +import fr.ifremer.wlo.utils.ImportUtil; import fr.ifremer.wlo.models.categorization.CategoryModel; import fr.ifremer.wlo.preferences.SettingsActivity; import fr.ifremer.wlo.storage.DataCache; import fr.ifremer.wlo.storage.Exporter; import fr.ifremer.wlo.storage.WloSqlOpenHelper; import fr.ifremer.wlo.utils.UIUtils; +import fr.ifremer.wlo.utils.UpdateCheckTask; import fr.ifremer.wlo.utils.filechooser.FileDialog; import fr.ifremer.wlo.utils.filechooser.SelectionMode; import org.apache.commons.io.FileUtils; @@ -109,6 +112,9 @@ super.onCreate(savedInstanceState); + new InitializationTask().execute(); + new UpdateCheckTask(this).execute(); + mainPanel = (LinearLayout) findViewById(R.id.main_panel); logoPanel = (LinearLayout) findViewById(R.id.logo_panel); buttonPanel = (LinearLayout) findViewById(R.id.button_panel); @@ -277,4 +283,108 @@ startActivityForResult(serverIntent, REQUEST_CONNECT_ICHTYOMETER); } + protected class InitializationTask extends AsyncTask<Void, Integer, Void> { + + protected ProgressDialog dialog; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + + dialog = new ProgressDialog(MainActivity.this); + dialog.setIndeterminate(false); + dialog.setCancelable(false); + dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + dialog.setMax(9); + dialog.setMessage(getString(R.string.main_loading_referential)); + dialog.show(); + } + + @Override + protected Void doInBackground(Void... params) { + Context context = MainActivity.this; + try { + int i = 1; + if (DataCache.getAllCommercialSpecies(context).isEmpty()) { + ImportUtil.importCommercialSpecies(context, getAssets().open("ref_import_commercial_species.csv")); + } + publishProgress(i++); + + if (DataCache.getAllLocations(context).isEmpty()) { + ImportUtil.importLocations(context, getAssets().open("ref_import_locations.csv")); + } + publishProgress(i++); + + if (DataCache.getAllMensurations(context).isEmpty()) { + ImportUtil.importMensurations(context, getAssets().open("ref_import_mensurations.csv")); + } + publishProgress(i++); + + if (DataCache.getAllMetiers(context).isEmpty()) { + ImportUtil.importMetiers(context, getAssets().open("ref_import_metiers.csv")); + } + publishProgress(i++); + + if (DataCache.getAllPresentations(context).isEmpty()) { + ImportUtil.importPresentations(context, getAssets().open("ref_import_presentations.csv")); + } + publishProgress(i++); + + if (DataCache.getAllScientificSpecies(context).isEmpty()) { + ImportUtil.importScientificSpecies(context, getAssets().open("ref_import_scientific_species.csv")); + } + publishProgress(i++); + + if (DataCache.getAllStates(context).isEmpty()) { + ImportUtil.importStates(context, getAssets().open("ref_import_states.csv")); + } + publishProgress(i++); + + if (DataCache.getAllVessels(context).isEmpty()) { + ImportUtil.importVessels(context, getAssets().open("ref_import_vessels.csv")); + } + publishProgress(i++); + + if (DataCache.getAllCategories(context).isEmpty()) { + WloSqlOpenHelper soh = new WloSqlOpenHelper(context); + + CategoryModel ageCategory = new CategoryModel(); + ageCategory.setLabel(getString(R.string.age)); + soh.saveData(ageCategory); + + CategoryModel genderCategory = new CategoryModel(); + genderCategory.setLabel(getString(R.string.gender)); + soh.saveData(genderCategory); + + CategoryModel maturityCategory = new CategoryModel(); + maturityCategory.setLabel(getString(R.string.maturity)); + soh.saveData(maturityCategory); + + soh.saveData(ImportUtil.importQualitativeValues(ageCategory, getAssets().open("ref_import_ages.csv"))); + soh.saveData(ImportUtil.importQualitativeValues(genderCategory, getAssets().open("ref_import_genders.csv"))); + soh.saveData(ImportUtil.importQualitativeValues(maturityCategory, getAssets().open("ref_import_maturities.csv"))); + + soh.close(); + } + publishProgress(i++); + + } catch (IOException | RuntimeException e) { + Log.e(TAG, "error on initial import", e); + } + return null; + } + + @Override + protected void onProgressUpdate(Integer... progress) { + dialog.setProgress(progress[0]); + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.dismiss(); + } + + } + } \ No newline at end of file Modified: trunk/src/fr/ifremer/wlo/WloApplication.java =================================================================== --- trunk/src/fr/ifremer/wlo/WloApplication.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/WloApplication.java 2014-03-03 17:36:04 UTC (rev 63) @@ -1,16 +1,23 @@ package fr.ifremer.wlo; import android.app.Application; +import android.app.DownloadManager; import android.app.ProgressDialog; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; import android.util.Log; -import fr.ifremer.wlo.imports.ImportUtil; +import fr.ifremer.wlo.utils.ImportUtil; import fr.ifremer.wlo.models.categorization.CategoryModel; import fr.ifremer.wlo.storage.DataCache; import fr.ifremer.wlo.storage.WloSqlOpenHelper; +import fr.ifremer.wlo.utils.UpdateCheckTask; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; +import java.io.FileNotFoundException; import java.io.IOException; /** @@ -34,68 +41,6 @@ public void onCreate() { ACRA.init(this); super.onCreate(); - - new Thread(new Runnable() { - @Override - public void run() { - initData(); - } - }).start(); - } - protected void initData() { - try { - if (DataCache.getAllCommercialSpecies(this).isEmpty()) { - ImportUtil.importCommercialSpecies(this, getAssets().open("ref_import_commercial_species.csv")); - } - if (DataCache.getAllLocations(this).isEmpty()) { - ImportUtil.importLocations(this, getAssets().open("ref_import_locations.csv")); - } - if (DataCache.getAllMensurations(this).isEmpty()) { - ImportUtil.importMensurations(this, getAssets().open("ref_import_mensurations.csv")); - } - if (DataCache.getAllMetiers(this).isEmpty()) { - ImportUtil.importMetiers(this, getAssets().open("ref_import_metiers.csv")); - } - if (DataCache.getAllPresentations(this).isEmpty()) { - ImportUtil.importPresentations(this, getAssets().open("ref_import_presentations.csv")); - } - if (DataCache.getAllScientificSpecies(this).isEmpty()) { - ImportUtil.importScientificSpecies(this, getAssets().open("ref_import_scientific_species.csv")); - } - if (DataCache.getAllStates(this).isEmpty()) { - ImportUtil.importStates(this, getAssets().open("ref_import_states.csv")); - } - if (DataCache.getAllVessels(this).isEmpty()) { - ImportUtil.importVessels(this, getAssets().open("ref_import_vessels.csv")); - } - if (DataCache.getAllCategories(this).isEmpty()) { - WloSqlOpenHelper soh = new WloSqlOpenHelper(this); - - CategoryModel ageCategory = new CategoryModel(); - ageCategory.setLabel(getString(R.string.age)); - soh.saveData(ageCategory); - - CategoryModel genderCategory = new CategoryModel(); - genderCategory.setLabel(getString(R.string.gender)); - soh.saveData(genderCategory); - - CategoryModel maturityCategory = new CategoryModel(); - maturityCategory.setLabel(getString(R.string.maturity)); - soh.saveData(maturityCategory); - - soh.saveData(ImportUtil.importQualitativeValues(ageCategory, getAssets().open("ref_import_ages.csv"))); - soh.saveData(ImportUtil.importQualitativeValues(genderCategory, getAssets().open("ref_import_genders.csv"))); - soh.saveData(ImportUtil.importQualitativeValues(maturityCategory, getAssets().open("ref_import_maturities.csv"))); - - soh.close(); - } - - } catch (IOException | RuntimeException e) { - //TODO kmorin 20140130 show error to the user - Log.e(TAG, "error on initial import", e); - } - } - } Modified: trunk/src/fr/ifremer/wlo/WloBaseActivity.java =================================================================== --- trunk/src/fr/ifremer/wlo/WloBaseActivity.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/WloBaseActivity.java 2014-03-03 17:36:04 UTC (rev 63) @@ -24,20 +24,30 @@ * #L% */ +import android.app.DownloadManager; +import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.IntentFilter; import android.content.ServiceConnection; +import android.database.Cursor; +import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import android.os.Messenger; +import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; +import android.widget.Toast; +import java.io.File; +import java.io.FileNotFoundException; + /** * @author kmorin <kmorin@codelutin.com> * @since 0.1 @@ -49,10 +59,47 @@ protected Messenger mServiceMessenger = null; protected Messenger mMessenger = null; + protected DownloadManager downloadManager; + protected static Long downloadingApkId = null; + protected final BroadcastReceiver downloadReceiver = new BroadcastReceiver() { + + @Override + public void onReceive(Context arg0, Intent arg1) { + DownloadManager.Query query = new DownloadManager.Query(); + query.setFilterById(downloadingApkId); + Cursor cursor = downloadManager.query(query); + + if(cursor.moveToFirst()){ + int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); + int status = cursor.getInt(columnIndex); + int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON); + int reason = cursor.getInt(columnReason); + + if(status == DownloadManager.STATUS_SUCCESSFUL){ + //Retrieve the saved download id + Uri uri = downloadManager.getUriForDownloadedFile(downloadingApkId); + + Intent promptInstall = new Intent(Intent.ACTION_VIEW) + .setDataAndType(uri, "application/vnd.android.package-archive"); + startActivity(promptInstall); + + } else if (status == DownloadManager.STATUS_FAILED){ + Toast.makeText(WloBaseActivity.this, + R.string.update_dowload_error, + Toast.LENGTH_LONG).show(); + } + downloadingApkId = null; + } + } + + }; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); + Integer viewId = getContentView(); if (viewId != null) { setContentView(viewId); @@ -65,6 +112,19 @@ } @Override + protected void onResume() { + super.onResume(); + IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); + registerReceiver(downloadReceiver, intentFilter); + } + + @Override + protected void onPause() { + super.onPause(); + unregisterReceiver(downloadReceiver); + } + + @Override protected void onDestroy() { Log.d(TAG, "destroy"); super.onDestroy(); @@ -128,4 +188,12 @@ Intent intent = new Intent(this, upClass); return intent; } + + public static Long getDownloadingApkId() { + return downloadingApkId; + } + + public static void setDownloadingApkId(Long downloadingApkId) { + WloBaseActivity.downloadingApkId = downloadingApkId; + } } Deleted: trunk/src/fr/ifremer/wlo/imports/ImportUtil.java =================================================================== --- trunk/src/fr/ifremer/wlo/imports/ImportUtil.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/imports/ImportUtil.java 2014-03-03 17:36:04 UTC (rev 63) @@ -1,284 +0,0 @@ -package fr.ifremer.wlo.imports; - -/* - * #%L - * WLO - * $Id:$ - * $HeadURL:$ - * %% - * Copyright (C) 2013 - 2014 Ifremer - * %% - * 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/gpl-3.0.html>. - * #L% - */ - -import android.content.Context; -import android.util.Log; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; -import fr.ifremer.wlo.models.BaseModel; -import fr.ifremer.wlo.models.categorization.CategoryModel; -import fr.ifremer.wlo.models.categorization.QualitativeValueModel; -import fr.ifremer.wlo.models.referentials.CalcifiedPartTaking; -import fr.ifremer.wlo.models.referentials.HasCode; -import fr.ifremer.wlo.storage.DataCache; -import fr.ifremer.wlo.storage.WloSqlOpenHelper; -import org.apache.commons.collections.CollectionUtils; -import org.nuiton.csv.Import; -import org.nuiton.csv.ImportModel; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 0.1 - */ -public class ImportUtil { - - private static final String TAG = "ImportUtil"; - - public static final char CSV_SEPARATOR = ';'; - - public static int importCommercialSpecies(Context context, String path) { - try { - return importCommercialSpecies(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importCommercialSpecies(Context context, InputStream inputStream) { - CommercialSpeciesRowModel commercialSpeciesRowModel = new CommercialSpeciesRowModel(CSV_SEPARATOR); - int result = importData(context, commercialSpeciesRowModel, inputStream, DataCache.getAllCommercialSpecies(context)); - DataCache.invalidateCommercialSpecies(); - return result; - } - - public static int importLocations(Context context, String path) { - try { - return importLocations(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importLocations(Context context, InputStream inputStream) { - LocationRowModel locationRowModel = new LocationRowModel(CSV_SEPARATOR); - int result = importData(context, locationRowModel, inputStream, DataCache.getAllLocations(context)); - DataCache.invalidateLocations(); - return result; - } - - public static int importMensurations(Context context, String path) { - try { - return importMensurations(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importMensurations(Context context, InputStream inputStream) { - MensurationRowModel mensurationRowModel = new MensurationRowModel(CSV_SEPARATOR); - int result = importData(context, mensurationRowModel, inputStream, DataCache.getAllMensurations(context)); - DataCache.invalidateMensurations(); - return result; - } - - public static int importMetiers(Context context, String path) { - try { - return importMetiers(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importMetiers(Context context, InputStream inputStream) { - MetierRowModel metierRowModel = new MetierRowModel(CSV_SEPARATOR); - int result = importData(context, metierRowModel, inputStream, DataCache.getAllMetiers(context)); - DataCache.invalidateMetiers(); - return result; - } - - public static int importPresentations(Context context, String path) { - try { - return importPresentations(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importPresentations(Context context, InputStream inputStream) { - PresentationRowModel presentationRowModel = new PresentationRowModel(CSV_SEPARATOR); - int result = importData(context, presentationRowModel, inputStream, DataCache.getAllPresentations(context)); - DataCache.invalidatePresentations(); - return result; - } - - public static int importScientificSpecies(Context context, String path) { - try { - return importScientificSpecies(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importScientificSpecies(Context context, InputStream inputStream) { - ScientificSpeciesRowModel scientificSpeciesRowModel = new ScientificSpeciesRowModel(CSV_SEPARATOR); - int result = importData(context, scientificSpeciesRowModel, inputStream, DataCache.getAllScientificSpecies(context)); - DataCache.invalidateScientificSpecies(); - return result; - } - - public static int importStates(Context context, String path) { - try { - return importStates(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importStates(Context context, InputStream inputStream) { - StateRowModel stateRowModel = new StateRowModel(CSV_SEPARATOR); - int result = importData(context, stateRowModel, inputStream, DataCache.getAllStates(context)); - DataCache.invalidateStates(); - return result; - } - - public static int importVessels(Context context, String path) { - try { - return importVessels(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importVessels(Context context, InputStream inputStream) { - VesselRowModel vesselRowModel = new VesselRowModel(CSV_SEPARATOR); - int result = importData(context, vesselRowModel, inputStream, DataCache.getAllVessels(context)); - DataCache.invalidateVessels(); - return result; - } - - public static int importCalcifiedPartTakings(Context context, String path) { - try { - return importCalcifiedPartTakings(context, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return 0; - } - - public static int importCalcifiedPartTakings(Context context, InputStream inputStream) { - CalcifiedPartTakingRowModel calcifiedPartTakingRowModel = new CalcifiedPartTakingRowModel(CSV_SEPARATOR, DataCache.getAllScientificSpecies(context)); - int result = importData(context, calcifiedPartTakingRowModel, inputStream, new ArrayList<CalcifiedPartTaking>()); - return result; - } - - public static Collection<QualitativeValueModel> importQualitativeValues(CategoryModel categoryModel, String path) { - try { - return importQualitativeValues(categoryModel, new FileInputStream(path)); - } catch (FileNotFoundException e) { - Log.e(TAG, "File " + path + " not found", e); - } - return null; - } - - public static Collection<QualitativeValueModel> importQualitativeValues(CategoryModel categoryModel, InputStream inputStream) { - QualitativeValueRowModel qualitativeValueRowModel = new QualitativeValueRowModel(CSV_SEPARATOR, categoryModel); - Collection<QualitativeValueModel> result = importData(qualitativeValueRowModel, inputStream, new ArrayList<QualitativeValueModel>()); - return result; - } - - protected static <M extends BaseModel> int importData(Context context, ImportModel<M> importModel, - InputStream inputStream, final Collection<M> actualReferential) { - - Collection<M> models = importData(importModel, inputStream, actualReferential); - - if (CollectionUtils.isNotEmpty(models)) { - Predicate<M> filter; - //if the models have a code attribute, check - M first = models.iterator().next(); - if (HasCode.class.isAssignableFrom(first.getClass())) { - Collection<HasCode> hasCodes = Collections2.transform(actualReferential, new Function<M, HasCode>() { - @Override - public HasCode apply(M m) { - return (HasCode) m; - } - }); - final Collection<String> codes = Collections2.transform(hasCodes, HasCode.GET_CODE_FUNCTION); - filter = new Predicate<M>() { - @Override - public boolean apply(M model) { - HasCode hasCode = (HasCode) model; - return !codes.contains(hasCode.getCode()); - } - }; - } else { - filter = new Predicate<M>() { - @Override - public boolean apply(M m) { - return !actualReferential.contains(m); - } - }; - } - - models = Collections2.filter(models, filter); - WloSqlOpenHelper soh = new WloSqlOpenHelper(context); - soh.saveData(models); - soh.close(); - } - - return models.size(); - } - - protected static <M extends BaseModel> Collection<M> importData(ImportModel<M> importModel, InputStream inputStream, - Collection<M> actualReferential) { - Preconditions.checkNotNull(actualReferential); - Import<M> importer = null; - Collection<M> models = null; - - try { - importer = Import.newImport(importModel, inputStream); - models = Lists.newArrayList(importer.iterator()); - - } catch (ClassCastException e) { - // cf issue #4205 - // nuiton-i18n provocks an error when trying to get the error message - Log.e(TAG, "error during import", e); - throw e; - - } finally { - if (importer != null) { - importer.close(); - } - } - return models; - } -} Modified: trunk/src/fr/ifremer/wlo/preferences/CategoryCreationAcivity.java =================================================================== --- trunk/src/fr/ifremer/wlo/preferences/CategoryCreationAcivity.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/preferences/CategoryCreationAcivity.java 2014-03-03 17:36:04 UTC (rev 63) @@ -10,7 +10,7 @@ import android.widget.TextView; import fr.ifremer.wlo.R; import fr.ifremer.wlo.WloBaseActivity; -import fr.ifremer.wlo.imports.ImportUtil; +import fr.ifremer.wlo.utils.ImportUtil; import fr.ifremer.wlo.models.categorization.CategoryModel; import fr.ifremer.wlo.models.categorization.QualitativeValueModel; import fr.ifremer.wlo.storage.DataCache; @@ -100,16 +100,10 @@ // cf issue #4205 // nuiton-i18n provocks an error when trying to get the error message Log.e(TAG, "error during import", e); - runOnUiThread(new Runnable() { - @Override - public void run() { - new AlertDialog.Builder(CategoryCreationAcivity.this) - .setMessage(R.string.import_error) - .setNeutralButton(android.R.string.ok, UIUtils.getCancelClickListener()) - .create().show(); - } - }); - + new AlertDialog.Builder(CategoryCreationAcivity.this) + .setMessage(R.string.import_error) + .setNeutralButton(android.R.string.ok, UIUtils.getCancelClickListener()) + .create().show(); } } else { Modified: trunk/src/fr/ifremer/wlo/preferences/SettingsActivity.java =================================================================== --- trunk/src/fr/ifremer/wlo/preferences/SettingsActivity.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/preferences/SettingsActivity.java 2014-03-03 17:36:04 UTC (rev 63) @@ -30,6 +30,7 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; +import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.MultiSelectListPreference; @@ -38,6 +39,7 @@ import android.util.Log; import android.widget.Toast; import com.google.common.base.Functions; +import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.Collections2; import com.google.common.collect.HashBiMap; @@ -51,7 +53,7 @@ import fr.ifremer.wlo.storage.DataCache; import fr.ifremer.wlo.storage.StorageUtils; import fr.ifremer.wlo.storage.WloSqlOpenHelper; -import fr.ifremer.wlo.imports.ImportUtil; +import fr.ifremer.wlo.utils.ImportUtil; import fr.ifremer.wlo.utils.UIUtils; import fr.ifremer.wlo.utils.filechooser.FileDialog; import fr.ifremer.wlo.utils.filechooser.SelectionMode; @@ -291,112 +293,8 @@ protected void importData(final int requestCode, final Intent data, final boolean backupFile) { final Context context = getActivity(); - - final ProgressDialog dialog = new ProgressDialog(context); - dialog.setCancelable(false); - dialog.setMessage(getString(R.string.preferences_importing_referential)); - dialog.show(); - - new Thread(new Runnable() { - @Override - public void run() { - String path = data.getStringExtra(FileDialog.RESULT_PATH); - Log.d(TAG, path); - final Integer updatedNb; - final Integer newNb; - - try { - switch (requestCode) { - case REQUEST_IMPORT_COMMERCIAL_SPECIES: - newNb = ImportUtil.importCommercialSpecies(context, path); - updatedNb = DataCache.getAllCommercialSpecies(context).size(); - break; - case REQUEST_IMPORT_LOCATIONS: - newNb = ImportUtil.importLocations(context, path); - updatedNb = DataCache.getAllLocations(context).size(); - break; - case REQUEST_IMPORT_MENSURATIONS: - newNb = ImportUtil.importMensurations(context, path); - updatedNb = DataCache.getAllMensurations(context).size(); - break; - case REQUEST_IMPORT_METIERS: - newNb = ImportUtil.importMetiers(context, path); - updatedNb = DataCache.getAllMetiers(context).size(); - break; - case REQUEST_IMPORT_PRESENTATIONS: - newNb = ImportUtil.importPresentations(context, path); - updatedNb = DataCache.getAllPresentations(context).size(); - break; - case REQUEST_IMPORT_SCIENTIFIC_SPECIES: - newNb = ImportUtil.importScientificSpecies(context, path); - updatedNb = DataCache.getAllScientificSpecies(context).size(); - break; - case REQUEST_IMPORT_STATES: - newNb = ImportUtil.importStates(context, path); - updatedNb = DataCache.getAllStates(context).size(); - break; - case REQUEST_IMPORT_VESSELS: - newNb = ImportUtil.importVessels(context, path); - updatedNb = DataCache.getAllVessels(context).size(); - break; - case REQUEST_IMPORT_CALCIFIED_PARTS_TAKINGS: - WloSqlOpenHelper soh = new WloSqlOpenHelper(context); - soh.clearCalcifiedPartTakings(); - soh.close(); - newNb = ImportUtil.importCalcifiedPartTakings(context, path); - updatedNb = null; - break; - default: - newNb = null; - updatedNb = null; - } - - if (backupFile) { - File importedFile = new File(path); - String copyFileName = String.format("%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS-", new Date()) + importedFile.getName(); - File dir = Environment.getExternalStoragePublicDirectory(".wlo"); - File file = new File(dir, copyFileName); - try { - FileUtils.copyInputStreamToFile(new FileInputStream(path), file); - } catch (IOException e) { - Log.e(TAG, "Error while copying the file", e); - } - } - - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - dialog.dismiss(); - - if (updatedNb != null) { - String key = requestCodeByPrefKey.inverse().get(requestCode); - Preference filePicker = findPreference(key); - filePicker.setSummary(getString(R.string.preferences_import_summary, updatedNb)); - } - - Toast.makeText(context, context.getString(R.string.import_new_element_number, newNb), Toast.LENGTH_SHORT).show(); - } - }); - - } catch (Exception e) { - // cf issue #4205 - // nuiton-i18n provocks an error when trying to get the error message - Log.e(TAG, "error during import", e); - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - dialog.dismiss(); - new AlertDialog.Builder(context) - .setMessage(R.string.import_error) - .setNeutralButton(android.R.string.ok, UIUtils.getCancelClickListener()) - .create().show(); - } - }); - - } - - } - }).start(); + String path = data.getStringExtra(FileDialog.RESULT_PATH); + new ImportAsyncTask().execute(path, requestCode, backupFile); } protected <M extends BaseModel> void initMultiSelectListPreference(String prefKey, @@ -439,7 +337,145 @@ } pref.setSummary(getString(R.string.favorite_nb, favoriteIds.size())); } + + protected class ImportAsyncTask extends AsyncTask<Object, Integer, Integer[]> { + + protected ProgressDialog dialog; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + + dialog = new ProgressDialog(getActivity()); + dialog.setCancelable(false); + dialog.setMessage(getString(R.string.preferences_importing_referential)); + dialog.show(); + } + + @Override + protected Integer[] doInBackground(Object... params) { + if (params.length != 3) { + return null; + } + Context context = getActivity(); + String path = (String) params[0]; + Integer requestCode = (Integer) params[1]; + Boolean backupFile = (Boolean) params[2]; + Log.d(TAG, path); + + Integer[] result = new Integer[3]; + result[2] = requestCode; + + try { + switch (requestCode) { + case REQUEST_IMPORT_COMMERCIAL_SPECIES: + result[0] = ImportUtil.importCommercialSpecies(context, path); + result[1] = DataCache.getAllCommercialSpecies(context).size(); + break; + case REQUEST_IMPORT_LOCATIONS: + result[0] = ImportUtil.importLocations(context, path); + result[1] = DataCache.getAllLocations(context).size(); + break; + case REQUEST_IMPORT_MENSURATIONS: + result[0] = ImportUtil.importMensurations(context, path); + result[1] = DataCache.getAllMensurations(context).size(); + break; + case REQUEST_IMPORT_METIERS: + result[0] = ImportUtil.importMetiers(context, path); + result[1] = DataCache.getAllMetiers(context).size(); + break; + case REQUEST_IMPORT_PRESENTATIONS: + result[0] = ImportUtil.importPresentations(context, path); + result[1] = DataCache.getAllPresentations(context).size(); + break; + case REQUEST_IMPORT_SCIENTIFIC_SPECIES: + result[0] = ImportUtil.importScientificSpecies(context, path); + result[1] = DataCache.getAllScientificSpecies(context).size(); + break; + case REQUEST_IMPORT_STATES: + result[0] = ImportUtil.importStates(context, path); + result[1] = DataCache.getAllStates(context).size(); + break; + case REQUEST_IMPORT_VESSELS: + result[0] = ImportUtil.importVessels(context, path); + result[1] = DataCache.getAllVessels(context).size(); + break; + case REQUEST_IMPORT_CALCIFIED_PARTS_TAKINGS: + WloSqlOpenHelper soh = new WloSqlOpenHelper(context); + soh.clearCalcifiedPartTakings(); + soh.close(); + result[0] = ImportUtil.importCalcifiedPartTakings(context, path); + result[1] = null; + break; + default: + result[0] = null; + result[1] = null; + } + + if (backupFile) { + File importedFile = new File(path); + String copyFileName = String.format("%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS-", new Date()) + importedFile.getName(); + File dir = Environment.getExternalStoragePublicDirectory(".wlo"); + File file = new File(dir, copyFileName); + try { + FileUtils.copyInputStreamToFile(new FileInputStream(path), file); + } catch (IOException e) { + Log.e(TAG, "Error while copying the file", e); + } + } + + } catch (Exception e) { + // cf issue #4205 + // nuiton-i18n provocks an error when trying to get the error message + Log.e(TAG, "error during import", e); + result = null; + cancel(true); + + } + return result; + } + + @Override + protected void onPostExecute(Integer[] result) { + super.onPostExecute(result); + + dialog.dismiss(); + + if (result != null) { + if (result[1] != null) { + String key = requestCodeByPrefKey.inverse().get(result[2]); + Preference filePicker = findPreference(key); + filePicker.setSummary(getString(R.string.preferences_import_summary, result[1])); + } + + Toast.makeText(getActivity(), getString(R.string.import_new_element_number, result[0]), Toast.LENGTH_LONG).show(); + +// } else { +// //error +// new AlertDialog.Builder(getActivity()) +// .setMessage(R.string.import_error) +// .setNeutralButton(android.R.string.ok, UIUtils.getCancelClickListener()) +// .create().show(); + } + } + + @Override + protected void onCancelled(Integer[] integer) { + super.onCancelled(integer); + dialog.dismiss(); + + new AlertDialog.Builder(getActivity()) + .setMessage(R.string.import_error) + .setNeutralButton(android.R.string.ok, UIUtils.getCancelClickListener()) + .create().show(); + } + + @Override + protected void onCancelled() { + super.onCancelled(); + onCancelled(null); + } + } } - } \ No newline at end of file Copied: trunk/src/fr/ifremer/wlo/utils/ImportUtil.java (from rev 57, trunk/src/fr/ifremer/wlo/imports/ImportUtil.java) =================================================================== --- trunk/src/fr/ifremer/wlo/utils/ImportUtil.java (rev 0) +++ trunk/src/fr/ifremer/wlo/utils/ImportUtil.java 2014-03-03 17:36:04 UTC (rev 63) @@ -0,0 +1,295 @@ +package fr.ifremer.wlo.utils; + +/* + * #%L + * WLO + * $Id:$ + * $HeadURL:$ + * %% + * Copyright (C) 2013 - 2014 Ifremer + * %% + * 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/gpl-3.0.html>. + * #L% + */ + +import android.content.Context; +import android.os.AsyncTask; +import android.util.Log; +import com.google.common.base.Function; +import com.google.common.base.Preconditions; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.Lists; +import fr.ifremer.wlo.imports.CalcifiedPartTakingRowModel; +import fr.ifremer.wlo.imports.CommercialSpeciesRowModel; +import fr.ifremer.wlo.imports.LocationRowModel; +import fr.ifremer.wlo.imports.MensurationRowModel; +import fr.ifremer.wlo.imports.MetierRowModel; +import fr.ifremer.wlo.imports.PresentationRowModel; +import fr.ifremer.wlo.imports.QualitativeValueRowModel; +import fr.ifremer.wlo.imports.ScientificSpeciesRowModel; +import fr.ifremer.wlo.imports.StateRowModel; +import fr.ifremer.wlo.imports.VesselRowModel; +import fr.ifremer.wlo.models.BaseModel; +import fr.ifremer.wlo.models.categorization.CategoryModel; +import fr.ifremer.wlo.models.categorization.QualitativeValueModel; +import fr.ifremer.wlo.models.referentials.CalcifiedPartTaking; +import fr.ifremer.wlo.models.referentials.HasCode; +import fr.ifremer.wlo.storage.DataCache; +import fr.ifremer.wlo.storage.WloSqlOpenHelper; +import org.apache.commons.collections.CollectionUtils; +import org.nuiton.csv.Import; +import org.nuiton.csv.ImportModel; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 0.1 + */ +public class ImportUtil { + + private static final String TAG = "ImportUtil"; + + public static final char CSV_SEPARATOR = ';'; + + public static int importCommercialSpecies(Context context, String path) { + try { + return importCommercialSpecies(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importCommercialSpecies(Context context, InputStream inputStream) { + CommercialSpeciesRowModel commercialSpeciesRowModel = new CommercialSpeciesRowModel(CSV_SEPARATOR); + int result = importData(context, commercialSpeciesRowModel, inputStream, DataCache.getAllCommercialSpecies(context)); + DataCache.invalidateCommercialSpecies(); + return result; + } + + public static int importLocations(Context context, String path) { + try { + return importLocations(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importLocations(Context context, InputStream inputStream) { + LocationRowModel locationRowModel = new LocationRowModel(CSV_SEPARATOR); + int result = importData(context, locationRowModel, inputStream, DataCache.getAllLocations(context)); + DataCache.invalidateLocations(); + return result; + } + + public static int importMensurations(Context context, String path) { + try { + return importMensurations(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importMensurations(Context context, InputStream inputStream) { + MensurationRowModel mensurationRowModel = new MensurationRowModel(CSV_SEPARATOR); + int result = importData(context, mensurationRowModel, inputStream, DataCache.getAllMensurations(context)); + DataCache.invalidateMensurations(); + return result; + } + + public static int importMetiers(Context context, String path) { + try { + return importMetiers(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importMetiers(Context context, InputStream inputStream) { + MetierRowModel metierRowModel = new MetierRowModel(CSV_SEPARATOR); + int result = importData(context, metierRowModel, inputStream, DataCache.getAllMetiers(context)); + DataCache.invalidateMetiers(); + return result; + } + + public static int importPresentations(Context context, String path) { + try { + return importPresentations(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importPresentations(Context context, InputStream inputStream) { + PresentationRowModel presentationRowModel = new PresentationRowModel(CSV_SEPARATOR); + int result = importData(context, presentationRowModel, inputStream, DataCache.getAllPresentations(context)); + DataCache.invalidatePresentations(); + return result; + } + + public static int importScientificSpecies(Context context, String path) { + try { + return importScientificSpecies(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importScientificSpecies(Context context, InputStream inputStream) { + ScientificSpeciesRowModel scientificSpeciesRowModel = new ScientificSpeciesRowModel(CSV_SEPARATOR); + int result = importData(context, scientificSpeciesRowModel, inputStream, DataCache.getAllScientificSpecies(context)); + DataCache.invalidateScientificSpecies(); + return result; + } + + public static int importStates(Context context, String path) { + try { + return importStates(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importStates(Context context, InputStream inputStream) { + StateRowModel stateRowModel = new StateRowModel(CSV_SEPARATOR); + int result = importData(context, stateRowModel, inputStream, DataCache.getAllStates(context)); + DataCache.invalidateStates(); + return result; + } + + public static int importVessels(Context context, String path) { + try { + return importVessels(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importVessels(Context context, InputStream inputStream) { + VesselRowModel vesselRowModel = new VesselRowModel(CSV_SEPARATOR); + int result = importData(context, vesselRowModel, inputStream, DataCache.getAllVessels(context)); + DataCache.invalidateVessels(); + return result; + } + + public static int importCalcifiedPartTakings(Context context, String path) { + try { + return importCalcifiedPartTakings(context, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return 0; + } + + public static int importCalcifiedPartTakings(Context context, InputStream inputStream) { + CalcifiedPartTakingRowModel calcifiedPartTakingRowModel = new CalcifiedPartTakingRowModel(CSV_SEPARATOR, DataCache.getAllScientificSpecies(context)); + int result = importData(context, calcifiedPartTakingRowModel, inputStream, new ArrayList<CalcifiedPartTaking>()); + return result; + } + + public static Collection<QualitativeValueModel> importQualitativeValues(CategoryModel categoryModel, String path) { + try { + return importQualitativeValues(categoryModel, new FileInputStream(path)); + } catch (FileNotFoundException e) { + Log.e(TAG, "File " + path + " not found", e); + } + return null; + } + + public static Collection<QualitativeValueModel> importQualitativeValues(CategoryModel categoryModel, InputStream inputStream) { + QualitativeValueRowModel qualitativeValueRowModel = new QualitativeValueRowModel(CSV_SEPARATOR, categoryModel); + Collection<QualitativeValueModel> result = importData(qualitativeValueRowModel, inputStream, new ArrayList<QualitativeValueModel>()); + return result; + } + + protected static <M extends BaseModel> int importData(Context context, ImportModel<M> importModel, + InputStream inputStream, final Collection<M> actualReferential) { + + Collection<M> models = importData(importModel, inputStream, actualReferential); + + if (CollectionUtils.isNotEmpty(models)) { + Predicate<M> filter; + //if the models have a code attribute, check + M first = models.iterator().next(); + if (HasCode.class.isAssignableFrom(first.getClass())) { + Collection<HasCode> hasCodes = Collections2.transform(actualReferential, new Function<M, HasCode>() { + @Override + public HasCode apply(M m) { + return (HasCode) m; + } + }); + final Collection<String> codes = Collections2.transform(hasCodes, HasCode.GET_CODE_FUNCTION); + filter = new Predicate<M>() { + @Override + public boolean apply(M model) { + HasCode hasCode = (HasCode) model; + return !codes.contains(hasCode.getCode()); + } + }; + } else { + filter = new Predicate<M>() { + @Override + public boolean apply(M m) { + return !actualReferential.contains(m); + } + }; + } + + models = Collections2.filter(models, filter); + WloSqlOpenHelper soh = new WloSqlOpenHelper(context); + soh.saveData(models); + soh.close(); + } + + return models.size(); + } + + protected static <M extends BaseModel> Collection<M> importData(ImportModel<M> importModel, InputStream inputStream, + Collection<M> actualReferential) { + Preconditions.checkNotNull(actualReferential); + Import<M> importer = null; + Collection<M> models = null; + + try { + importer = Import.newImport(importModel, inputStream); + models = Lists.newArrayList(importer.iterator()); + + } catch (ClassCastException e) { + // cf issue #4205 + // nuiton-i18n provocks an error when trying to get the error message + Log.e(TAG, "error during import", e); + throw e; + + } finally { + if (importer != null) { + importer.close(); + } + } + return models; + } +} Modified: trunk/src/fr/ifremer/wlo/utils/UpdateCheckTask.java =================================================================== --- trunk/src/fr/ifremer/wlo/utils/UpdateCheckTask.java 2014-03-03 15:24:16 UTC (rev 62) +++ trunk/src/fr/ifremer/wlo/utils/UpdateCheckTask.java 2014-03-03 17:36:04 UTC (rev 63) @@ -1,18 +1,111 @@ package fr.ifremer.wlo.utils; +import android.app.AlertDialog; +import android.app.DownloadManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.net.Uri; import android.os.AsyncTask; +import android.os.Environment; +import android.util.Log; +import android.widget.Toast; +import fr.ifremer.wlo.R; +import fr.ifremer.wlo.WloBaseActivity; +import org.nuiton.util.Version; +import org.nuiton.util.VersionUtil; +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; import java.net.URL; +import java.util.Date; +import java.util.Properties; /** * @author Kevin Morin (Code Lutin) * @since x.x */ -public class UpdateCheckTask extends AsyncTask<URL, Integer, Long> { +public class UpdateCheckTask extends AsyncTask<String, Integer, String> { + private static final String TAG = "UpdateCheckTask"; + + public static final String UPDATE_URL = "http://appup.nuiton.org/wlo/wlo-update.properties"; + public static final String VERSION_PROP = "application.version"; + public static final String URL_PROP = "application.url"; + + protected Context context; + + public UpdateCheckTask(Context context) { + this.context = context; + } + @Override - protected Long doInBackground(URL... params) { + protected String doInBackground(String... params) { + String result; - return null; + if (WloBaseActivity.getDownloadingApkId() != null) { + result = null; + } else { + try { + // Create a URL for the desired page + URL url = new URL(UPDATE_URL); + + Properties props = new Properties(); + props.load(url.openStream()); + String version = props.getProperty(VERSION_PROP); + + String currentVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; + + Version newVersion = new Version(version); + if (!newVersion.isSnapshot() && VersionUtil.greaterThan(version, currentVersion)) { + result = props.getProperty(URL_PROP); + + } else { + Log.d(TAG, "The application is up to date"); + result = null; + } + + } catch (IOException | PackageManager.NameNotFoundException e) { + Log.e(TAG, "error while getting the version"); + cancel(true); + result = null; + } + } + + return result; } + + @Override + protected void onPostExecute(final String result) { + super.onPostExecute(result); + if (result != null && WloBaseActivity.getDownloadingApkId() == null) { + + new AlertDialog.Builder(context) + .setTitle(R.string.update_available_title) + .setMessage(R.string.update_available_message) + .setNegativeButton(R.string.no, UIUtils.getCancelClickListener()) + .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); + Uri toDownload = Uri.parse(result); + DownloadManager.Request request = new DownloadManager.Request(toDownload); + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toDownload.getLastPathSegment()); + long enqueue = downloadManager.enqueue(request); + WloBaseActivity.setDownloadingApkId(enqueue); + } + }) + .create() + .show(); + + } + } + }