Better exception handling for import of keys

This commit is contained in:
Dominik Schürmann 2014-07-31 17:11:06 +02:00
parent 1d2c93ca8a
commit 9475285013
9 changed files with 27 additions and 47 deletions

View File

@ -134,9 +134,7 @@ public class UncachedKeyRing {
}
public static List<UncachedKeyRing> fromStream(InputStream stream)
throws PgpGeneralException, IOException {
public static List<UncachedKeyRing> fromStream(InputStream stream) throws IOException {
List<UncachedKeyRing> result = new Vector<UncachedKeyRing>();
while(stream.available() > 0) {
@ -147,8 +145,10 @@ public class UncachedKeyRing {
while ((obj = objectFactory.nextObject()) != null) {
Log.d(Constants.TAG, "Found class: " + obj.getClass());
if (!(obj instanceof PGPKeyRing)) {
throw new PgpGeneralException(
"Bad object of type " + obj.getClass().getName() + " in stream!");
Log.d(Constants.TAG,
"Bad object of type " + obj.getClass().getName() + " in stream, proceed with next object...");
// skip object
continue;
}
result.add(new UncachedKeyRing((PGPKeyRing) obj));
}

View File

@ -287,8 +287,8 @@ public class ImportKeysListFragment extends ListFragment implements
if (error == null) {
// No error
mCachedKeyData = ((ImportKeysListLoader) loader).getParcelableRings();
} else if (error instanceof ImportKeysListLoader.FileHasNoContentException) {
Notify.showNotify(getActivity(), R.string.error_import_file_no_content, Notify.Style.ERROR);
} else if (error instanceof ImportKeysListLoader.NoValidKeysException) {
Notify.showNotify(getActivity(), R.string.error_import_no_valid_keys, Notify.Style.ERROR);
} else if (error instanceof ImportKeysListLoader.NonPgpPartException) {
Notify.showNotify(getActivity(),
((ImportKeysListLoader.NonPgpPartException) error).getCount() + " " + getResources().

View File

@ -37,7 +37,7 @@ import java.util.List;
public class ImportKeysListLoader
extends AsyncTaskLoader<AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>> {
public static class FileHasNoContentException extends Exception {
public static class NoValidKeysException extends Exception {
}
public static class NonPgpPartException extends Exception {
@ -118,8 +118,6 @@ public class ImportKeysListLoader
* @return
*/
private void generateListOfKeyrings(InputData inputData) {
boolean isEmpty = true;
PositionAwareInputStream progressIn = new PositionAwareInputStream(
inputData.getInputStream());
@ -127,42 +125,24 @@ public class ImportKeysListLoader
// PGPObject chunks after the first one, e.g. files with several consecutive ASCII
// armor blocks
BufferedInputStream bufferedInput = new BufferedInputStream(progressIn);
bufferedInput.mark(1024);
try {
// read all available blocks... (asc files can contain many blocks with BEGIN END)
while (bufferedInput.available() > 0) {
// TODO: deal with non-keyring objects?
List<UncachedKeyRing> rings = UncachedKeyRing.fromStream(bufferedInput);
for (UncachedKeyRing key : rings) {
ImportKeysListEntry item = new ImportKeysListEntry(getContext(), key);
mData.add(item);
mParcelableRings.put(item.hashCode(), new ParcelableKeyRing(key.getEncoded()));
isEmpty = false;
}
// parse all keyrings
List<UncachedKeyRing> rings = UncachedKeyRing.fromStream(bufferedInput);
for (UncachedKeyRing key : rings) {
ImportKeysListEntry item = new ImportKeysListEntry(getContext(), key);
mData.add(item);
mParcelableRings.put(item.hashCode(), new ParcelableKeyRing(key.getEncoded()));
}
} catch (IOException e) {
Log.e(Constants.TAG, "IOException on parsing key file! Return NoValidKeysException!", e);
NoValidKeysException e1 = new NoValidKeysException();
mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>
(mData, e1);
} catch (Exception e) {
Log.e(Constants.TAG, "Exception on parsing key file!", e);
try {
bufferedInput.reset();
} catch (IOException e1) {
}
Log.d(Constants.TAG, "Last 1024 byte input data: " + convertStreamToString(bufferedInput));
Log.e(Constants.TAG, "Other Exception on parsing key file!", e);
mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData, e);
}
if (isEmpty) {
FileHasNoContentException e = new FileHasNoContentException();
Log.e(Constants.TAG, "File has no content!", e);
mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>
(mData, e);
}
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}

View File

@ -253,7 +253,7 @@
<string name="error_keyserver_insufficient_query">Petición de búsqueda de clave demasiado corta</string>
<string name="error_searching_keys">Error irrecuperable buscando claves en el servidor</string>
<string name="error_keyserver_too_many_responses">La petición de búsqueda de clave devolvió demasiados candidatos; por favor refine su petición</string>
<string name="error_import_file_no_content">El Fichero/Portapapeles está vacío</string>
<string name="error_import_no_valid_keys">El Fichero/Portapapeles está vacío</string>
<string name="error_generic_report_bug">Ha ocurrido un error genérico, por favor, informa de este bug a OpenKeychain</string>
<plurals name="error_import_non_pgp_part">
<item quantity="one">parte del archivo cargado es un objeto OpenPGP válido pero no una clave OpenPGP</item>

View File

@ -253,7 +253,7 @@
<string name="error_keyserver_insufficient_query">La requête de recherche de clef est trop courte</string>
<string name="error_searching_keys">Erreur irrécupérable lors de la recherche de clef sur le serveur</string>
<string name="error_keyserver_too_many_responses">La requête de recherche de clef a retourné trop de candidats. Veuillez raffiner la requête</string>
<string name="error_import_file_no_content">Le fichier/le presse-papiers est vide</string>
<string name="error_import_no_valid_keys">Le fichier/le presse-papiers est vide</string>
<string name="error_generic_report_bug">Une erreur générique est survenue, veuillez créer un nouveau rapport de bogue pour OpenKeychain.</string>
<plurals name="error_import_non_pgp_part">
<item quantity="one">une partie du fichier chargé est un objet OpenPGP valide mais pas une clef OpenPGP</item>

View File

@ -253,7 +253,7 @@
<string name="error_keyserver_insufficient_query">Chiave della query di ricerca troppo corta</string>
<string name="error_searching_keys">Errore irreversibile nella ricerca di chiavi sul server</string>
<string name="error_keyserver_too_many_responses">Chiave della query di ricerca ha generato troppi candidati; Si prega di perfezionare la ricerca</string>
<string name="error_import_file_no_content">File/Appunti vuoti</string>
<string name="error_import_no_valid_keys">File/Appunti vuoti</string>
<string name="error_generic_report_bug">Si è verificato un errore generico, si prega di creare una nuova segnalazione di errore per OpenKeychain.</string>
<plurals name="error_import_non_pgp_part">
<item quantity="one">parte del file caricato e\' un oggetto OpenPGP valido, ma non una chave OpenPGP</item>

View File

@ -249,7 +249,7 @@
<string name="error_keyserver_insufficient_query">鍵検索のクエリが短かすぎます</string>
<string name="error_searching_keys">サーバでの鍵の検索が回復不可能なエラーになりました</string>
<string name="error_keyserver_too_many_responses">鍵検索のクエリが沢山の候補を返しました; クエリを精密化してください</string>
<string name="error_import_file_no_content">ファイル/クリップボードが空です</string>
<string name="error_import_no_valid_keys">ファイル/クリップボードが空です</string>
<string name="error_generic_report_bug">一般エラーが発生しました、この新しいバグの情報をOpenKeychainプロジェクトに送ってください</string>
<plurals name="error_import_non_pgp_part">
<item quantity="other">読み込んだファイルのOpenPGPオブジェクト部分は正しいですが、OpenPGPの鍵ではありません</item>

View File

@ -257,7 +257,7 @@
<string name="error_keyserver_insufficient_query">Запрос слишком короткий</string>
<string name="error_searching_keys">Ошибка поиска ключей на сервере</string>
<string name="error_keyserver_too_many_responses">Поиск ключа вернул слишком много вариантов; Пожалуйста, уточните запрос</string>
<string name="error_import_file_no_content">Файл/Буфер пуст</string>
<string name="error_import_no_valid_keys">Файл/Буфер пуст</string>
<string name="error_generic_report_bug">Выявлена ошибка. Пожалуйста, сообщите о ней разработчику.</string>
<plurals name="error_import_non_pgp_part">
<item quantity="one">часть загруженного файла содержит данные OpenPGP, но это не ключ</item>

View File

@ -273,7 +273,7 @@
<string name="error_keyserver_insufficient_query">Key search query too short</string>
<string name="error_searching_keys">Unrecoverable error searching for keys at server</string>
<string name="error_keyserver_too_many_responses">Key search query returned too many candidates; Please refine query</string>
<string name="error_import_file_no_content">File/Clipboard is empty</string>
<string name="error_import_no_valid_keys">No valid keys found in File/Clipboard!</string>
<string name="error_generic_report_bug">A generic error occurred, please create a new bug report for OpenKeychain.</string>
<plurals name="error_import_non_pgp_part">
<item quantity="one">part of the loaded file is a valid OpenPGP object but not a OpenPGP key</item>