From f452c63dc4576d277b8e658afce2b4a7ae0676e5 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 24 Feb 2017 13:15:17 -0300 Subject: [PATCH 01/41] Removing deprecated class --- .../utils/pokemon/PokemonCpUtils.java | 285 ------------------ 1 file changed, 285 deletions(-) delete mode 100644 src/me/corriekay/pokegoutil/utils/pokemon/PokemonCpUtils.java diff --git a/src/me/corriekay/pokegoutil/utils/pokemon/PokemonCpUtils.java b/src/me/corriekay/pokegoutil/utils/pokemon/PokemonCpUtils.java deleted file mode 100644 index 3069ff95..00000000 --- a/src/me/corriekay/pokegoutil/utils/pokemon/PokemonCpUtils.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Most of the code in this file is taken from PokeGoAPI by Grover-c13 - * Kudos for his work. - * https://github.com/Grover-c13/PokeGOAPI-Java/blob/master/src/main/java/com/pokegoapi/api/pokemon/PokemonCpUtils.java - */ - -package me.corriekay.pokegoutil.utils.pokemon; - -import java.util.HashMap; -import java.util.Map; - -/** - * Utility class to provide functions calculating CP. - * - * @deprecated We don't need this class anymore, cause the Pogo-API can do all that his class does as well. - */ -@Deprecated -public class PokemonCpUtils { - private static final Map LEVEL_CPMULTIPLIER = new HashMap<>(); - - static { - LEVEL_CPMULTIPLIER.put(1f, 0.094f); - LEVEL_CPMULTIPLIER.put(1.5f, 0.135137432f); - LEVEL_CPMULTIPLIER.put(2f, 0.16639787f); - LEVEL_CPMULTIPLIER.put(2.5f, 0.192650919f); - LEVEL_CPMULTIPLIER.put(3f, 0.21573247f); - LEVEL_CPMULTIPLIER.put(3.5f, 0.236572661f); - LEVEL_CPMULTIPLIER.put(4f, 0.25572005f); - LEVEL_CPMULTIPLIER.put(4.5f, 0.273530381f); - LEVEL_CPMULTIPLIER.put(5f, 0.29024988f); - LEVEL_CPMULTIPLIER.put(5.5f, 0.306057377f); - LEVEL_CPMULTIPLIER.put(6f, 0.3210876f); - LEVEL_CPMULTIPLIER.put(6.5f, 0.335445036f); - LEVEL_CPMULTIPLIER.put(7f, 0.34921268f); - LEVEL_CPMULTIPLIER.put(7.5f, 0.362457751f); - LEVEL_CPMULTIPLIER.put(8f, 0.37523559f); - LEVEL_CPMULTIPLIER.put(8.5f, 0.387592406f); - LEVEL_CPMULTIPLIER.put(9f, 0.39956728f); - LEVEL_CPMULTIPLIER.put(9.5f, 0.411193551f); - LEVEL_CPMULTIPLIER.put(10f, 0.42250001f); - LEVEL_CPMULTIPLIER.put(10.5f, 0.432926419f); - LEVEL_CPMULTIPLIER.put(11f, 0.44310755f); - LEVEL_CPMULTIPLIER.put(11.5f, 0.453059958f); - LEVEL_CPMULTIPLIER.put(12f, 0.46279839f); - LEVEL_CPMULTIPLIER.put(12.5f, 0.472336083f); - LEVEL_CPMULTIPLIER.put(13f, 0.48168495f); - LEVEL_CPMULTIPLIER.put(13.5f, 0.4908558f); - LEVEL_CPMULTIPLIER.put(14f, 0.49985844f); - LEVEL_CPMULTIPLIER.put(14.5f, 0.508701765f); - LEVEL_CPMULTIPLIER.put(15f, 0.51739395f); - LEVEL_CPMULTIPLIER.put(15.5f, 0.525942511f); - LEVEL_CPMULTIPLIER.put(16f, 0.53435433f); - LEVEL_CPMULTIPLIER.put(16.5f, 0.542635767f); - LEVEL_CPMULTIPLIER.put(17f, 0.55079269f); - LEVEL_CPMULTIPLIER.put(17.5f, 0.558830576f); - LEVEL_CPMULTIPLIER.put(18f, 0.56675452f); - LEVEL_CPMULTIPLIER.put(18.5f, 0.574569153f); - LEVEL_CPMULTIPLIER.put(19f, 0.58227891f); - LEVEL_CPMULTIPLIER.put(19.5f, 0.589887917f); - LEVEL_CPMULTIPLIER.put(20f, 0.59740001f); - LEVEL_CPMULTIPLIER.put(20.5f, 0.604818814f); - LEVEL_CPMULTIPLIER.put(21f, 0.61215729f); - LEVEL_CPMULTIPLIER.put(21.5f, 0.619399365f); - LEVEL_CPMULTIPLIER.put(22f, 0.62656713f); - LEVEL_CPMULTIPLIER.put(22.5f, 0.633644533f); - LEVEL_CPMULTIPLIER.put(23f, 0.64065295f); - LEVEL_CPMULTIPLIER.put(23.5f, 0.647576426f); - LEVEL_CPMULTIPLIER.put(24f, 0.65443563f); - LEVEL_CPMULTIPLIER.put(24.5f, 0.661214806f); - LEVEL_CPMULTIPLIER.put(25f, 0.667934f); - LEVEL_CPMULTIPLIER.put(25.5f, 0.674577537f); - LEVEL_CPMULTIPLIER.put(26f, 0.68116492f); - LEVEL_CPMULTIPLIER.put(26.5f, 0.687680648f); - LEVEL_CPMULTIPLIER.put(27f, 0.69414365f); - LEVEL_CPMULTIPLIER.put(27.5f, 0.700538673f); - LEVEL_CPMULTIPLIER.put(28f, 0.70688421f); - LEVEL_CPMULTIPLIER.put(28.5f, 0.713164996f); - LEVEL_CPMULTIPLIER.put(29f, 0.71939909f); - LEVEL_CPMULTIPLIER.put(29.5f, 0.725571552f); - LEVEL_CPMULTIPLIER.put(30f, 0.7317f); - LEVEL_CPMULTIPLIER.put(30.5f, 0.734741009f); - LEVEL_CPMULTIPLIER.put(31f, 0.73776948f); - LEVEL_CPMULTIPLIER.put(31.5f, 0.740785574f); - LEVEL_CPMULTIPLIER.put(32f, 0.74378943f); - LEVEL_CPMULTIPLIER.put(32.5f, 0.746781211f); - LEVEL_CPMULTIPLIER.put(33f, 0.74976104f); - LEVEL_CPMULTIPLIER.put(33.5f, 0.752729087f); - LEVEL_CPMULTIPLIER.put(34f, 0.75568551f); - LEVEL_CPMULTIPLIER.put(34.5f, 0.758630378f); - LEVEL_CPMULTIPLIER.put(35f, 0.76156384f); - LEVEL_CPMULTIPLIER.put(35.5f, 0.764486065f); - LEVEL_CPMULTIPLIER.put(36f, 0.76739717f); - LEVEL_CPMULTIPLIER.put(36.5f, 0.770297266f); - LEVEL_CPMULTIPLIER.put(37f, 0.7731865f); - LEVEL_CPMULTIPLIER.put(37.5f, 0.776064962f); - LEVEL_CPMULTIPLIER.put(38f, 0.77893275f); - LEVEL_CPMULTIPLIER.put(38.5f, 0.781790055f); - LEVEL_CPMULTIPLIER.put(39f, 0.78463697f); - LEVEL_CPMULTIPLIER.put(39.5f, 0.787473578f); - LEVEL_CPMULTIPLIER.put(40f, 0.79030001f); - LEVEL_CPMULTIPLIER.put(40.5F, 0.7931164F); - } - - /** Prevent initializing this class. */ - private PokemonCpUtils() { - } - - private static float getLevel(float cpMuliplier) { - float level; - if (cpMuliplier < 0.734f) { - // compute polynomial approximation obtained by regression - level = 58.35178527f * cpMuliplier * cpMuliplier - 2.838007664f * cpMuliplier + 0.8539209906f; - } else { - // compute linear approximation obtained by regression - level = 171.0112688f * cpMuliplier - 95.20425243f; - } - // round to nearest .5 value and return - return Math.round((level) * 2) / 2.0f; - } - - /** - * Get the level from the cp multiplier - * - * @param cpMultiplier All CP multiplier values combined - * @return Level - */ - public static float getLevelFromCpMultiplier(float cpMultiplier) { - return getLevel(cpMultiplier); - } - - /** - * Get the maximum CP from the values - * - * @param attack All attack values combined - * @param defense All defense values combined - * @param stamina All stamina values combined - * @return Maximum CP for these levels - */ - public static int getMaxCp(int attack, int defense, int stamina) { - return getMaxCpForTrainerLevel(attack, defense, stamina, 40); - } - - /** - * Get the maximum CP for the given values - * - * @param attack All attack values combined - * @param defense All defense values combined - * @param stamina All stamina values combined - * @param trainerLevel the trainer level for which the CP should be calculated - * @return Maximum CP for these levels - */ - public static int getMaxCpForTrainerLevel(int attack, int defense, int stamina, int trainerLevel) { - float maxPokemonLevel = Math.min(40.5f, trainerLevel + 1.5F); - return getCpForPokemonLevel(attack, defense, stamina, maxPokemonLevel); - } - - /** - * Get the CP for the given values - * - * @param attack All attack values combined - * @param defense All defense values combined - * @param stamina All stamina values combined - * @param level the Pokémon level for which the CP should be calculated - * @return Maximum CP for these levels - */ - public static int getCpForPokemonLevel(int attack, int defense, int stamina, float level) { - float pokemonLevel = Math.min(40.5f, level); - float cpMultiplier = LEVEL_CPMULTIPLIER.get(pokemonLevel); - return (int) Math.round((double) attack * Math.pow((double) defense, 0.5D) * Math.pow((double) stamina, 0.5D) * Math.pow((double) cpMultiplier, 2.0D) / 10.0D); - } - - /** - * Get the CP after powerup - * - * @param cp Current CP level - * @param cpMultiplier All CP multiplier values combined - * @return New CP level - */ - public static int getCpAfterPowerup(float cp, float cpMultiplier) { - // Based on http://pokemongo.gamepress.gg/power-up-costs - float level = getLevelFromCpMultiplier(cpMultiplier); - if (level <= 10) { - return (int) ((cp * 0.009426125469) / Math.pow(cpMultiplier, 2)); - } - if (level <= 20) { - return (int) ((cp * 0.008919025675) / Math.pow(cpMultiplier, 2)); - } - if (level <= 30) { - return (int) ((cp * 0.008924905903) / Math.pow(cpMultiplier, 2)); - } - return (int) ((cp * 0.00445946079) / Math.pow(cpMultiplier, 2)); - } - - /** - * Get the amount of stardust required to do a powerup - * - * @param cpMultiplier All CP multiplier values combined - * @param powerups Number of previous powerups - * @return Amount of stardust - */ - public static int getStartdustCostsForPowerup(float cpMultiplier, int powerups) { - // Based on http://pokemongo.gamepress.gg/power-up-costs - float level = getLevelFromCpMultiplier(cpMultiplier); - if (level <= 3 && powerups <= 4) { - return 200; - } - if (level <= 4 && powerups <= 8) { - return 400; - } - if (level <= 7 && powerups <= 12) { - return 600; - } - if (level <= 8 && powerups <= 16) { - return 800; - } - if (level <= 11 && powerups <= 20) { - return 1000; - } - if (level <= 13 && powerups <= 24) { - return 1300; - } - if (level <= 15 && powerups <= 28) { - return 1600; - } - if (level <= 17 && powerups <= 32) { - return 1900; - } - if (level <= 19 && powerups <= 36) { - return 2200; - } - if (level <= 21 && powerups <= 40) { - return 2500; - } - if (level <= 23 && powerups <= 44) { - return 3000; - } - if (level <= 25 && powerups <= 48) { - return 3500; - } - if (level <= 27 && powerups <= 52) { - return 4000; - } - if (level <= 29 && powerups <= 56) { - return 4500; - } - if (level <= 31 && powerups <= 60) { - return 5000; - } - if (level <= 33 && powerups <= 64) { - return 6000; - } - if (level <= 35 && powerups <= 68) { - return 7000; - } - if (level <= 37 && powerups <= 72) { - return 8000; - } - if (level <= 39 && powerups <= 76) { - return 9000; - } - return 10000; - } - - /** - * Get the amount of candy required to do a powerup - * - * @param cpMultiplier All CP multiplier values combined - * @param powerups Number of previous powerups - * @return Amount of candy - */ - public static int getCandyCostsForPowerup(float cpMultiplier, int powerups) { - // Based on http://pokemongo.gamepress.gg/power-up-costs - float level = getLevelFromCpMultiplier(cpMultiplier); - if (level <= 13 && powerups <= 20) { - return 1; - } - if (level <= 21 && powerups <= 36) { - return 2; - } - if (level <= 31 && powerups <= 60) { - return 3; - } - return 4; - } -} From 54d1b97593e1ed842b9c7e48f95284f0f141efc7 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 24 Feb 2017 13:16:56 -0300 Subject: [PATCH 02/41] Fixing problem with getStardustCostForPowerup when users has pokemon lvl 40 Fix #3 --- pom.xml | 6 +++--- src/me/corriekay/pokegoutil/data/enums/PokeColumn.java | 9 +++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 9fa95bd6..e0ce37e1 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 BPGM BPGM - 0.1.7-beta572-3 + 0.1.7-hotfix1 src test @@ -102,9 +102,9 @@ - com.github.gegy1000 + com.github.FernandoTBarros PokeGOAPI-Java - fb759f0b51461d0e047ecf04bb33b12829b3e8fe + 253e052002ea60905b0c872dfa0e133e28710fbd org.json diff --git a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java index 3f11ae40..5b6b1f2b 100644 --- a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java +++ b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java @@ -198,10 +198,15 @@ public Object get(final Pokemon p) { } } }, - STARDUST_TO_POWERUP("Stardust", ColumnType.INT) { + STARDUST_TO_POWERUP("Stardust", ColumnType.NULLABLE_INT) { @Override public Object get(final Pokemon p) { - return p.getStardustCostsForPowerup(); + int startdust = p.getStardustCostsForPowerup(); + if (startdust != 0) { + return String.valueOf(startdust); + } else { + return StringLiterals.NO_VALUE_SIGN; + } } }, MAX_CP_CUR("Max CP (Cur)", ColumnType.INT) { From 10d39269d464116d19d23ae06f5f4574064e18cd Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 24 Feb 2017 13:18:42 -0300 Subject: [PATCH 03/41] Try catch NPE when trying to get data from column Fix #554 --- .../pokegoutil/utils/windows/PokemonTableModel.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java index c1912529..8ae4c498 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java @@ -12,7 +12,7 @@ import me.corriekay.pokegoutil.data.enums.PokeColumn; -@SuppressWarnings( {"serial", "rawtypes"}) +@SuppressWarnings( {"serial"}) public class PokemonTableModel extends AbstractTableModel { @@ -44,8 +44,12 @@ public void updateTableData(final List pokes) { pokeCol.add(i.getValue(), p); for (final PokeColumn column : PokeColumn.values()) { - // Now lets add the value for that column - column.data.add(i.getValue(), column.get(p)); + try { + column.data.add(i.getValue(), column.get(p)); + } catch (NullPointerException e) { + System.out.println("Error getting data for column: " + column.heading); + e.printStackTrace(); + } } i.increment(); From b593464dfb0ea8017539387c95775f26cab3e8c1 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 24 Feb 2017 13:20:04 -0300 Subject: [PATCH 04/41] Updating eclipse preferences regarding checkstyle --- .settings/org.eclipse.core.resources.prefs | 2 + .settings/org.eclipse.jdt.core.prefs | 12 ++--- .settings/org.eclipse.jdt.ui.prefs | 61 +++++++++++++++++++++- 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 9806319b..6f0997bb 100644 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -1,4 +1,6 @@ eclipse.preferences.version=1 +encoding//src/main/resources=UTF-8 encoding//src/me/corriekay/pokegoutil/windows/PokemonTab.java=UTF-8 encoding/=UTF-8 encoding/src=UTF-8 +encoding/test=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 821070f0..1e8df216 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -75,7 +75,7 @@ org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false org.eclipse.jdt.core.formatter.comment.indent_root_tags=true org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=200 +org.eclipse.jdt.core.formatter.comment.line_length=170 org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=false org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false @@ -107,7 +107,7 @@ org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert @@ -158,7 +158,7 @@ org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert @@ -189,7 +189,7 @@ org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert @@ -238,7 +238,7 @@ org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert @@ -287,7 +287,7 @@ org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=200 +org.eclipse.jdt.core.formatter.lineSplit=170 org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs index b8197b5a..49285802 100644 --- a/.settings/org.eclipse.jdt.ui.prefs +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -1,3 +1,62 @@ +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=false +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=true +cleanup.always_use_this_for_non_static_method_access=true +cleanup.convert_functional_interfaces=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=false +cleanup.format_source_code=false +cleanup.format_source_code_changes_only=false +cleanup.insert_inferred_type_arguments=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=true +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_redundant_type_arguments=true +cleanup.remove_trailing_whitespaces=false +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_anonymous_class_creation=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_lambda=true +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=false +cleanup.use_this_for_non_static_method_access=true +cleanup.use_this_for_non_static_method_access_only_if_necessary=false +cleanup.use_type_arguments=false +cleanup_profile=_eclipse-cs BlossomsPokemonGoManager +cleanup_settings_version=2 eclipse.preferences.version=1 -formatter_profile=_GitHub Codacy [built-in] +formatter_profile=_eclipse-cs BlossomsPokemonGoManager formatter_settings_version=12 From 5d959da0bc96ead92bbffc36d9e85ba6586cac40 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Sat, 25 Feb 2017 18:07:15 -0300 Subject: [PATCH 05/41] Including a column to show item required to evolve --- pom.xml | 6 +++--- .../pokegoutil/data/enums/PokeColumn.java | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 9fa95bd6..37cb327b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 BPGM BPGM - 0.1.7-beta572-3 + 0.1.8 src test @@ -102,9 +102,9 @@ - com.github.gegy1000 + com.github.FernandoTBarros PokeGOAPI-Java - fb759f0b51461d0e047ecf04bb33b12829b3e8fe + 024b471c2e319f9886e5da95dd30f1513d8bd85d org.json diff --git a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java index 3f11ae40..096acb07 100644 --- a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java +++ b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java @@ -16,7 +16,8 @@ import POGOProtos.Enums.PokemonIdOuterClass; import POGOProtos.Enums.PokemonMoveOuterClass.PokemonMove; import POGOProtos.Enums.PokemonTypeOuterClass.PokemonType; -import POGOProtos.Settings.Master.MoveSettingsOuterClass.MoveSettings; +import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId; +import POGOProtos.Settings.Master.Pokemon.EvolutionBranchOuterClass.EvolutionBranch; import me.corriekay.pokegoutil.utils.AutoIncrementer; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; @@ -198,6 +199,22 @@ public Object get(final Pokemon p) { } } }, + ITEM_TO_EVOLVE("Item To Evolve", ColumnType.STRING) { + @Override + public Object get(final Pokemon p) { + List evolutionBranch = p.getEvolutionBranch(); + if (evolutionBranch != null && evolutionBranch.size()>0) { + for (EvolutionBranch evoBranch : evolutionBranch) { + if(evoBranch.getEvolutionItemRequirement()!=null && + evoBranch.getEvolutionItemRequirement()!=ItemId.UNRECOGNIZED && + evoBranch.getEvolutionItemRequirement()!=ItemId.ITEM_UNKNOWN) { + return PokemonUtils.formatItem(evoBranch.getEvolutionItemRequirement()) + " (" + PokemonUtils.getLocalPokeName(evoBranch.getEvolution().getNumber()) + ")"; + } + } + } + return ""; + } + }, STARDUST_TO_POWERUP("Stardust", ColumnType.INT) { @Override public Object get(final Pokemon p) { From 23eb5298a858924157b81a54ee0a3af22a840654 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Mon, 27 Feb 2017 12:17:54 -0300 Subject: [PATCH 06/41] Creating new column with new renderer and editor for item required for evolution Refactoring search bar using proper rowFilter by Java Maintaining selection after search or after operations like refresh, transfer and evolve --- pom.xml | 4 +- .../pokegoutil/data/enums/ColumnType.java | 26 ++++ .../pokegoutil/data/enums/PokeColumn.java | 31 +++- .../utils/helpers/EvolveHelper.java | 55 ++++++++ .../utils/windows/PokemonTable.java | 74 ++++++++-- .../utils/windows/PokemonTableModel.java | 30 +++- .../windows/renderer/CellRendererHelper.java | 2 + .../windows/renderer/CheckBoxCellEditor.java | 51 +++++++ .../renderer/CheckBoxCellRenderer.java | 97 +++++++++++++ .../pokegoutil/windows/PokemonTab.java | 132 +++++++++--------- 10 files changed, 414 insertions(+), 88 deletions(-) create mode 100644 src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java create mode 100644 src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java create mode 100644 src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java diff --git a/pom.xml b/pom.xml index 37cb327b..3b2a84aa 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 BPGM BPGM - 0.1.8 + 0.1.7-hotfix2 src test @@ -104,7 +104,7 @@ com.github.FernandoTBarros PokeGOAPI-Java - 024b471c2e319f9886e5da95dd30f1513d8bd85d + 84df3ebb045807f7645623268937bf3b9c9b27ff org.json diff --git a/src/me/corriekay/pokegoutil/data/enums/ColumnType.java b/src/me/corriekay/pokegoutil/data/enums/ColumnType.java index b1fe78ad..1a164623 100644 --- a/src/me/corriekay/pokegoutil/data/enums/ColumnType.java +++ b/src/me/corriekay/pokegoutil/data/enums/ColumnType.java @@ -3,10 +3,13 @@ import java.util.Comparator; import java.util.concurrent.CompletableFuture; +import javax.swing.DefaultCellEditor; +import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import me.corriekay.pokegoutil.utils.StringLiterals; import me.corriekay.pokegoutil.utils.helpers.DateHelper; +import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; import me.corriekay.pokegoutil.utils.windows.renderer.CellRendererHelper; /** @@ -65,11 +68,18 @@ public enum ColumnType { String.class, Comparators.FUTURE_STRING, CellRendererHelper.FUTURE + ), + EVOLVE_CHECK_BOX( + EvolveHelper.class, + Comparators.EVOLVE, + CellRendererHelper.CHECK_BOX, + CellRendererHelper.CHECK_BOX_EDITOR ); public final Class clazz; public final Comparator comparator; public final TableCellRenderer tableCellRenderer; + public final TableCellEditor tableCellEditor; /** * This private class is needed to create the comparators that are used in this enum. @@ -82,6 +92,7 @@ private static final class Comparators { public static final Comparator INT = Integer::compareTo; public static final Comparator LONG = Long::compareTo; public static final Comparator STRING = String::compareTo; + public static final Comparator EVOLVE = EvolveHelper::compareTo; public static final Comparator> FUTURE_STRING = (left, right) -> left.getNow("").compareTo(right.getNow("")); public static final Comparator NULLABLE_INT = (left, right) -> { if (StringLiterals.NO_VALUE_SIGN.equals(left)) { @@ -115,5 +126,20 @@ private static final class Comparators { this.clazz = clazz; this.comparator = comparator; this.tableCellRenderer = tableCellRenderer; + this.tableCellEditor = null; + } + + /** + * Constructor to create a column type enum field. + * + * @param clazz The class type of the column, what the data is. + * @param comparator The comparator for that column. + * @param tableCellRenderer The table cell renderer. + */ + ColumnType(final Class clazz, final Comparator comparator, final TableCellRenderer tableCellRenderer, final TableCellEditor tableCellEditor) { + this.clazz = clazz; + this.comparator = comparator; + this.tableCellRenderer = tableCellRenderer; + this.tableCellEditor = tableCellEditor; } } diff --git a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java index 90175da4..161efa1f 100644 --- a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java +++ b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.NoSuchElementException; +import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import com.pokegoapi.api.pokemon.Evolutions; @@ -23,13 +24,14 @@ import me.corriekay.pokegoutil.utils.ConfigNew; import me.corriekay.pokegoutil.utils.StringLiterals; import me.corriekay.pokegoutil.utils.Utilities; -import me.corriekay.pokegoutil.utils.helpers.CollectionHelper; import me.corriekay.pokegoutil.utils.helpers.DateHelper; +import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; import me.corriekay.pokegoutil.utils.helpers.LocationHelper; import me.corriekay.pokegoutil.utils.pokemon.PokemonCalculationUtils; import me.corriekay.pokegoutil.utils.pokemon.PokemonPerformanceCache; import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; import me.corriekay.pokegoutil.utils.windows.renderer.CellRendererHelper; +import me.corriekay.pokegoutil.windows.PokemonTab; /** * A class that holds data relevant for each column. @@ -199,20 +201,25 @@ public Object get(final Pokemon p) { } } }, - ITEM_TO_EVOLVE("Item To Evolve", ColumnType.STRING) { + ITEM_TO_EVOLVE("Item To Evolve", ColumnType.EVOLVE_CHECK_BOX) { @Override public Object get(final Pokemon p) { + if (PokemonTab.mapPokemonItem.containsKey(p.getId())) { + return PokemonTab.mapPokemonItem.get(p.getId()); + } List evolutionBranch = p.getEvolutionBranch(); if (evolutionBranch != null && evolutionBranch.size()>0) { for (EvolutionBranch evoBranch : evolutionBranch) { if(evoBranch.getEvolutionItemRequirement()!=null && evoBranch.getEvolutionItemRequirement()!=ItemId.UNRECOGNIZED && evoBranch.getEvolutionItemRequirement()!=ItemId.ITEM_UNKNOWN) { - return PokemonUtils.formatItem(evoBranch.getEvolutionItemRequirement()) + " (" + PokemonUtils.getLocalPokeName(evoBranch.getEvolution().getNumber()) + ")"; + EvolveHelper evolve = new EvolveHelper(evoBranch.getEvolution(), evoBranch.getEvolutionItemRequirement()); + PokemonTab.mapPokemonItem.put(p.getId(), evolve); + return evolve; } } } - return ""; + return null; } }, STARDUST_TO_POWERUP("Stardust", ColumnType.NULLABLE_INT) { @@ -405,9 +412,10 @@ public Object get(final Pokemon p) { public final int id; public final String heading; public final ColumnType columnType; - public final ArrayList data; + public final ArrayList data; private TableCellRenderer customCellRenderer; + private TableCellEditor customCellEditor; /** * Constructor to create the enum entries. @@ -419,7 +427,7 @@ public Object get(final Pokemon p) { this.id = Internal.AUTO_INCREMENTER.get(); this.heading = heading; this.columnType = columnType; - this.data = CollectionHelper.provideArrayList(columnType.clazz); + this.data = new ArrayList<>(); } /** @@ -471,7 +479,7 @@ public static PokeColumn getForHeading(final String heading) { * * @return The comparator. */ - public Comparator getComparator() { + public Comparator getComparator() { return columnType.comparator; } @@ -483,6 +491,15 @@ public Comparator getComparator() { public TableCellRenderer getCellRenderer() { return customCellRenderer != null ? customCellRenderer : columnType.tableCellRenderer; } + + /** + * Returns the table cell editor for the given column, based on the column type. + * + * @return The cell editor. + */ + public TableCellEditor getCellEditor() { + return customCellEditor != null ? customCellEditor : columnType.tableCellEditor; + } /** * This method must be overwritten and should return what should be the diff --git a/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java b/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java new file mode 100644 index 00000000..3db248f5 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java @@ -0,0 +1,55 @@ +package me.corriekay.pokegoutil.utils.helpers; + +import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; +import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId; +import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; + +/** + * Helper class for evolving with itens + */ +public final class EvolveHelper implements Comparable { + + private PokemonId pokemonToEvolve; + private ItemId itemToEvolve; + private boolean evolveWithItem; + + public EvolveHelper(PokemonId pokemon, ItemId item) { + this.pokemonToEvolve = pokemon; + this.itemToEvolve = item; + this.evolveWithItem = false; + } + + @Override + public String toString() { + return getItemToEvolve() + " (" + getPokemonToEvolve() + ")"; + } + + public String getPokemonToEvolve() { + return PokemonUtils.getLocalPokeName(this.pokemonToEvolve.getNumber()); + } + + public String getItemToEvolve() { + return PokemonUtils.formatItem(this.itemToEvolve); + } + + public ItemId getItemToEvolveId() { + return this.itemToEvolve; + } + + public void setItemToEvolve(ItemId itemToEvolve) { + this.itemToEvolve = itemToEvolve; + } + + public boolean isEvolveWithItem() { + return evolveWithItem; + } + + public void setEvolveWithItem(boolean evolveWithItem) { + this.evolveWithItem = evolveWithItem; + } + + @Override + public int compareTo(EvolveHelper o) { + return this.toString().compareTo(o.toString()); + } +} diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java index 5bac2fca..6b329905 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java @@ -10,19 +10,22 @@ import javax.swing.JTable; import javax.swing.ListSelectionModel; +import javax.swing.RowFilter; import javax.swing.RowSorter.SortKey; import javax.swing.SortOrder; import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; -import com.pokegoapi.api.PokemonGo; import com.pokegoapi.api.pokemon.Pokemon; +import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; +import me.corriekay.pokegoutil.utils.StringLiterals; +import me.corriekay.pokegoutil.utils.Utilities; import me.corriekay.pokegoutil.utils.helpers.JTableColumnPacker; +import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; /** * The Pokémon Table. Extended JTable which displays all Pokémon and does the needed @@ -30,6 +33,7 @@ *

* Added things are row sorter, column comparators, listener and the cell renderers. */ +@SuppressWarnings("serial") public class PokemonTable extends JTable { // Global statics @@ -40,19 +44,18 @@ public class PokemonTable extends JTable { private PokemonTableModel ptm; - private List columnErrors = new LinkedList(); + private List columnErrors = new LinkedList(); + private TableRowSorter trs; /** * Constructs the PokemonTable, sets the model and defines all preset stuff. - * - * @param go The go instance of the Pogo API */ - public PokemonTable(final PokemonGo go) { + public PokemonTable() { setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); setAutoResizeMode(AUTO_RESIZE_OFF); setRowHeight(getRowHeight() + ROW_HEIGHT_PADDING * 2); - ptm = new PokemonTableModel(go, new ArrayList<>(), this); + ptm = new PokemonTableModel(new ArrayList<>(), this); setModel(ptm); // Load sort configs @@ -69,7 +72,7 @@ public PokemonTable(final PokemonGo go) { sortOrder2 = SortOrder.ASCENDING; } - final TableRowSorter trs = new TableRowSorter<>(ptm); + trs = new TableRowSorter<>(ptm); // Set the comparator for each column that is defined. for (final PokeColumn column : PokeColumn.values()) { @@ -103,6 +106,9 @@ public PokemonTable(final PokemonGo go) { // Add cell renderers for (final PokeColumn column : PokeColumn.values()) { columnModel.getColumn(column.id).setCellRenderer(column.getCellRenderer()); + if (column.getCellEditor() != null) { + columnModel.getColumn(column.id).setCellEditor(column.getCellEditor()); + } } try { rearrangeColumnOrder(); @@ -189,4 +195,56 @@ private void pack() { JTableColumnPacker.packColumn(this, i, COLUMN_MARGIN); } } + + /** + * Function for filtering the table using the proper RowFilter of Java + * @param filterText the text to be filtered + */ + public void filterTable(String filterText) { + RowFilter rowFilter = null; + if (filterText != null && filterText != "") { + rowFilter = new RowFilter() { + @Override + public boolean include(javax.swing.RowFilter.Entry entry) { + Pokemon poke = entry.getModel().getPokemonByIndexNotConverting(entry.getIdentifier()); + if(poke != null) { + final boolean useFamilyName = config.getBool(ConfigKey.INCLUDE_FAMILY); + String familyName = ""; + if (useFamilyName) { + // Try translating family name + try { + final PokemonId familyPokemonId = PokemonId.valueOf(poke.getPokemonFamily().toString().replaceAll(StringLiterals.FAMILY_PREFIX, "")); + familyName = PokemonUtils.getLocalPokeName(familyPokemonId.getNumber()); + } catch (final IllegalArgumentException e) { + familyName = poke.getPokemonFamily().toString(); + } + } + + String searchme = Utilities.concatString(',', + PokemonUtils.getLocalPokeName(poke), + ((useFamilyName) ? familyName : ""), + poke.getNickname(), + poke.getSettings().getType().toString(), + poke.getSettings().getType2().toString(), + poke.getMove1().toString(), + poke.getMove2().toString(), + poke.getPokeball().toString()); + searchme = searchme.replaceAll("_FAST", "").replaceAll(StringLiterals.FAMILY_PREFIX, "").replaceAll("NONE", "") + .replaceAll("ITEM_", "").replaceAll(StringLiterals.POKEMON_TYPE_PREFIX, "").replaceAll(StringLiterals.UNDERSCORE, "") + .replaceAll(StringLiterals.SPACE, "").toLowerCase(); + + final String[] terms = filterText.split(";"); + for (final String s : terms) { + if (searchme.contains(s)) { + return true; + } + } + return false; + } + return true; + } + }; + } + trs.setRowFilter(rowFilter); + } } diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java index 8ae4c498..707c4248 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java @@ -7,7 +7,6 @@ import org.apache.commons.lang3.mutable.MutableInt; -import com.pokegoapi.api.PokemonGo; import com.pokegoapi.api.pokemon.Pokemon; import me.corriekay.pokegoutil.data.enums.PokeColumn; @@ -19,12 +18,9 @@ public class PokemonTableModel extends AbstractTableModel { PokemonTable pt; private final ArrayList pokeCol = new ArrayList<>(); - private final PokemonGo go; - @Deprecated - PokemonTableModel(final PokemonGo go, final List pokes, final PokemonTable pt) { + PokemonTableModel(final List pokes, final PokemonTable pt) { this.pt = pt; - this.go = go; updateTableData(pokes); } @@ -34,7 +30,6 @@ public class PokemonTableModel extends AbstractTableModel { * * @param pokes The list of pokemon that should be displayed */ - @SuppressWarnings("unchecked") public void updateTableData(final List pokes) { ClearTable(); @@ -65,6 +60,15 @@ private void ClearTable() { } } + public int getIndexByPokemon(final Pokemon p) { + try { + return pokeCol.indexOf(p); + } catch (final Exception e) { + e.printStackTrace(); + return -1; + } + } + public Pokemon getPokemonByIndex(final int i) { try { return pokeCol.get(pt.convertRowIndexToModel(i)); @@ -73,6 +77,15 @@ public Pokemon getPokemonByIndex(final int i) { return null; } } + + public Pokemon getPokemonByIndexNotConverting(final int i) { + try { + return pokeCol.get(i); + } catch (final Exception e) { + e.printStackTrace(); + return null; + } + } @Override public String getColumnName(final int columnIndex) { @@ -93,4 +106,9 @@ public int getRowCount() { public Object getValueAt(final int rowIndex, final int columnIndex) { return PokeColumn.getForId(columnIndex).data.get(rowIndex); } + + @Override + public boolean isCellEditable(final int rowIndex, final int columnIndex) { + return PokeColumn.getForId(columnIndex).columnType.tableCellEditor != null; + } } diff --git a/src/me/corriekay/pokegoutil/utils/windows/renderer/CellRendererHelper.java b/src/me/corriekay/pokegoutil/utils/windows/renderer/CellRendererHelper.java index 3c0e7dfa..d6c67089 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/renderer/CellRendererHelper.java +++ b/src/me/corriekay/pokegoutil/utils/windows/renderer/CellRendererHelper.java @@ -14,6 +14,8 @@ public final class CellRendererHelper { public static final DpsCellRenderer DPS2VALUE = new DpsCellRenderer().withRatingColors(0, 45); public static final FutureCellRenderer FUTURE = new FutureCellRenderer(); public static final AutoIncrementCellRenderer AUTO_INCREMENT = new AutoIncrementCellRenderer(); + public static final CheckBoxCellRenderer CHECK_BOX = new CheckBoxCellRenderer(); + public static final CheckBoxCellEditor CHECK_BOX_EDITOR = new CheckBoxCellEditor(); // Special renderer public static final NumberCellRenderer IV = new NumberCellRenderer().withRatingColors(0, PokemonUtils.MAX_IV); diff --git a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java new file mode 100644 index 00000000..87206fc9 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java @@ -0,0 +1,51 @@ +package me.corriekay.pokegoutil.utils.windows.renderer; + +import java.awt.Component; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.AbstractCellEditor; +import javax.swing.JTable; +import javax.swing.table.TableCellEditor; + +import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; + +/** + * Provide custom formatting for the moveset ranking columns while allowing sorting on original values. + */ +@SuppressWarnings("serial") +class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor, ItemListener { + + private CheckBoxCellRenderer vr = new CheckBoxCellRenderer(); + private EvolveHelper evolve; + + public CheckBoxCellEditor() { + vr.getCheckBox().addItemListener(this); + } + + @Override + public Object getCellEditorValue() { + return vr.getCheckBox().isSelected(); + } + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) { + if (value != null) { + CheckBoxCellRenderer chcr = (CheckBoxCellRenderer) vr.getTableCellRendererComponent(table, value, isSelected, true, row, col); + if(chcr.getCheckBox().isEnabled()) { + evolve = (EvolveHelper) value; + return chcr; + } + } + return null; + } + + @Override + public void itemStateChanged(ItemEvent e) { + if (evolve != null) { + evolve.setEvolveWithItem(e.getStateChange() == ItemEvent.SELECTED); + evolve = null; + } + this.fireEditingStopped(); + } +} diff --git a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java new file mode 100644 index 00000000..911326ee --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java @@ -0,0 +1,97 @@ +package me.corriekay.pokegoutil.utils.windows.renderer; + +import java.awt.Component; +import java.awt.FlowLayout; + +import javax.swing.BorderFactory; +import javax.swing.JCheckBox; +import javax.swing.JPanel; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.table.TableCellRenderer; + +import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; +import me.corriekay.pokegoutil.utils.windows.PokemonTable; +import me.corriekay.pokegoutil.windows.PokemonTab; + +/** + * Provide custom formatting for the moveset ranking columns while allowing sorting on original values. + */ +@SuppressWarnings("serial") +public class CheckBoxCellRenderer extends JPanel implements TableCellRenderer { + // Padding left and right can be overwritten by custom renderer. + protected static final int PADDING_LEFT = 3; + protected static final int PADDING_RIGHT = 3; + + private JCheckBox checkBox; + + public CheckBoxCellRenderer() { + super(new FlowLayout(FlowLayout.LEADING, 0, 0)); + checkBox = new JCheckBox(); + checkBox.setOpaque(false); + checkBox.setVerticalAlignment(SwingUtilities.TOP); + add(checkBox); + } + + + @Override + public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, + final boolean hasFocus, final int rowIndex, final int columnIndex) { + if (value != null) { + EvolveHelper evolve = (EvolveHelper) value; + checkBox.setVisible(true); + checkBox.setSelected(evolve.isEvolveWithItem()); + int itemCount = PokemonTab.getPlayerItems().getItem(evolve.getItemToEvolveId()).getCount(); + checkBox.setText(evolve.toString() + " [" + itemCount + "]"); + checkBox.setEnabled(true); + if (itemCount <= 0) { + checkBox.setEnabled(false); + checkBox.setOpaque(false); + } + } + else { + checkBox.setEnabled(true); + checkBox.setText(""); + checkBox.setVisible(false); + } + setNativeLookAndFeel(table, value, isSelected); + + return this; + } + + /** + * Sets the native look and feel for the TableCellRenderer. + * This method should be called first in getTableCellRendererComponent() when extending this CellRenderer, + * or should be overwritten and called then. + * + * @param table The table. + * @param value The value. + * @param isSelected If the cell is selected. + */ + protected void setNativeLookAndFeel(final JTable table, final Object value, final boolean isSelected) { + setOpaque(true); + setDefaultSelectionColors(table, isSelected); + setFont(table.getFont()); + setBorder(BorderFactory.createEmptyBorder(0, PADDING_LEFT, PokemonTable.ROW_HEIGHT_PADDING, PADDING_RIGHT)); + } + + /** + * Set the selection colors for the cell. + * + * @param table The table. + * @param isSelected If the cell is selected. + */ + private void setDefaultSelectionColors(final JTable table, final boolean isSelected) { + if (isSelected) { + this.setBackground(table.getSelectionBackground()); + this.setForeground(table.getSelectionForeground()); + } else { + this.setBackground(table.getBackground()); + this.setForeground(table.getForeground()); + } + } + + public JCheckBox getCheckBox() { + return checkBox; + } +} diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index 855082f6..9ff0fcb7 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -14,9 +14,12 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; +import java.util.stream.Collectors; import javax.swing.BoxLayout; import javax.swing.JButton; @@ -36,6 +39,7 @@ import org.apache.commons.lang3.mutable.MutableInt; import com.pokegoapi.api.PokemonGo; +import com.pokegoapi.api.inventory.ItemBag; import com.pokegoapi.api.map.pokemon.EvolutionResult; import com.pokegoapi.api.player.PlayerProfile.Currency; import com.pokegoapi.api.pokemon.Pokemon; @@ -44,12 +48,18 @@ import com.pokegoapi.exceptions.RemoteServerException; import com.pokegoapi.exceptions.hash.HashException; +import POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId; +import POGOProtos.Networking.Responses.NicknamePokemonResponseOuterClass.NicknamePokemonResponse; +import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse; +import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse; +import POGOProtos.Networking.Responses.UpgradePokemonResponseOuterClass.UpgradePokemonResponse; import me.corriekay.pokegoutil.data.enums.BatchOperation; import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; import me.corriekay.pokegoutil.utils.StringLiterals; import me.corriekay.pokegoutil.utils.Utilities; +import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; import me.corriekay.pokegoutil.utils.helpers.LDocumentListener; import me.corriekay.pokegoutil.utils.helpers.LocationHelper; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler; @@ -60,12 +70,6 @@ import me.corriekay.pokegoutil.utils.ui.GhostText; import me.corriekay.pokegoutil.utils.windows.PokemonTable; import me.corriekay.pokegoutil.utils.windows.PokemonTableModel; -import POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId; -import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; -import POGOProtos.Networking.Responses.NicknamePokemonResponseOuterClass.NicknamePokemonResponse; -import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse; -import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse; -import POGOProtos.Networking.Responses.UpgradePokemonResponseOuterClass.UpgradePokemonResponse; /** * The main PokemonTab. @@ -73,11 +77,12 @@ @SuppressWarnings("serial") public class PokemonTab extends JPanel { - private final PokemonGo go; + private static PokemonGo go; private final PokemonTable pt; private static final JTextField searchBar = new JTextField(""); private static final JTextField ivTransfer = new JTextField("", 20); private static final ConfigNew config = ConfigNew.getConfig(); + public static final HashMap mapPokemonItem = new HashMap(); // Used constants private static final int WHEN_TO_SHOW_SELECTION_TITLE = 2; @@ -85,18 +90,19 @@ public class PokemonTab extends JPanel { private static final int POPUP_WIDTH = 500; private static final int POPUP_HEIGHT = 400; private static final int MIN_FONT_SIZE = 2; + private List selectedRows; /** * Creates an instance of the PokemonTab. * * @param go The go api class. */ - public PokemonTab(final PokemonGo go) { + public PokemonTab(final PokemonGo goInstance) { super(); setLayout(new BorderLayout()); - this.go = go; - pt = new PokemonTable(go); + go = goInstance; + pt = new PokemonTable(); final JPanel topPanel = new JPanel(new GridBagLayout()); final JButton refreshPkmn = new JButton("Refresh List"), renameSelected = new JButton(BatchOperation.RENAME.toString()), @@ -111,6 +117,9 @@ public PokemonTab(final PokemonGo go) { return; } if (event.getSource() == pt.getSelectionModel() && pt.getRowSelectionAllowed()) { + if(pt.getSelectionModel().getAnchorSelectionIndex() > -1 && pt.getSelectionModel().getLeadSelectionIndex() > -1) { + selectedRows = Arrays.stream(pt.getSelectedRows()).boxed().collect(Collectors.toList()); + } final int selectedRows = pt.getSelectedRowCount(); if (selectedRows >= WHEN_TO_SHOW_SELECTION_TITLE) { PokemonGoMainWindow.getInstance().setTitle(selectedRows + " Pokémon selected"); @@ -251,15 +260,24 @@ protected Void doInBackground() { }.execute()); topPanel.add(fontSize); - LDocumentListener.addChangeListener(searchBar, e -> refreshList()); + LDocumentListener.addChangeListener(searchBar, e -> { + String search = searchBar.getText().replaceAll(StringLiterals.SPACE, "").replaceAll(StringLiterals.UNDERSCORE, "").replaceAll("snek", "ekans") + .toLowerCase(); + if ("searchpokémon...".equals(search)) { + search = ""; + } + pt.filterTable(search); + }); new GhostText(searchBar, "Search Pokémon..."); add(topPanel, BorderLayout.NORTH); final JScrollPane sp = new JScrollPane(pt); sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sp, BorderLayout.CENTER); + + pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); } - + private void changeLanguage(final String langCode) { config.setString(ConfigKey.LANGUAGE, langCode); @@ -281,7 +299,7 @@ private void changeLanguage(final String langCode) { private void refreshPkmn() { try { - go.getInventories().updateInventories(); + go.getInventories().updateInventories(true); PokemonGoMainWindow.getInstance().refreshTitle(); } catch (final Exception e) { e.printStackTrace(); @@ -372,7 +390,7 @@ private void renameSelected() { handler.bulkRenameWithPattern(renamePattern, perPokeCallback); try { - go.getInventories().updateInventories(); + go.getInventories().updateInventories(true); } catch (final Exception e) { e.printStackTrace(); } @@ -424,6 +442,7 @@ private void transferSelected() { skipped.increment(); return; } + removeSelection(poke); finalSelection.add(poke); }); @@ -508,7 +527,14 @@ private void evolveSelected() { return; } - final EvolutionResult evolutionResultWrapper = poke.evolve(); + final EvolutionResult evolutionResultWrapper; + EvolveHelper evolve = mapPokemonItem.get(poke.getId()); + if (evolve != null && evolve.isEvolveWithItem()) { + evolutionResultWrapper = poke.evolve(evolve.getItemToEvolveId()); + } + else { + evolutionResultWrapper = poke.evolve(); + } if (evolutionResultWrapper.isSuccessful()) { final Pokemon newPoke = evolutionResultWrapper.getEvolvedPokemon(); int newCandies = newPoke.getCandy(); @@ -546,6 +572,7 @@ private void evolveSelected() { newCandies = newPoke.getCandy(); candyRefund++; } + removeSelection(poke); System.out.println(String.format( "Transferring %s, Result: %s", StringUtils.capitalize(newPoke.getPokemonId().toString().toLowerCase()), @@ -567,7 +594,6 @@ private void evolveSelected() { newCp, (newCp - cp), newHp, (newHp - hp))); } - go.getInventories().updateInventories(); success.increment(); } else { err.increment(); @@ -718,7 +744,7 @@ private void powerUpSelected() { } }); try { - go.getInventories().updateInventories(); + go.getInventories().updateInventories(true); PokemonGoMainWindow.getInstance().refreshTitle(); } catch (final RemoteServerException | LoginFailedException | CaptchaActiveException | HashException e) { e.printStackTrace(); @@ -911,6 +937,12 @@ private JPanel buildPanelForOperation(final BatchOperation operation, final Arra case EVOLVE: str += " Cost: " + p.getCandiesToEvolve(); str += p.getCandiesToEvolve() > 1 ? " Candies" : " Candy"; + if (mapPokemonItem.containsKey(p.getId())) { + EvolveHelper evolve = mapPokemonItem.get(p.getId()); + if (evolve.isEvolveWithItem()) { + str += " Evolving to " + evolve.getPokemonToEvolve() + " using " + evolve.getItemToEvolve(); + } + } break; case POWER_UP: str += " Cost: " + p.getCandyCostsForPowerup(); @@ -993,63 +1025,28 @@ public ArrayList getSelectedPokemon() { } return pokes; } + + public void removeSelection(Pokemon p) { + final PokemonTableModel model = (PokemonTableModel) pt.getModel(); + int index = model.getIndexByPokemon(p); + if (index > 0) { + selectedRows.remove(index); + } + } public void refreshList() { - final List pokes = new ArrayList<>(); - final String search = searchBar.getText().replaceAll(StringLiterals.SPACE, "").replaceAll(StringLiterals.UNDERSCORE, "").replaceAll("snek", "ekans") - .toLowerCase(); - final String[] terms = search.split(";"); try { - if ("".equals(search) || "searchpokémon...".equals(search)) { - pokes.addAll(go.getInventories().getPokebank().getPokemons()); - } - else - { - synchronized (go.getInventories().getPokebank().getLock()) { - go.getInventories().getPokebank().getPokemons().forEach(poke -> { - final boolean useFamilyName = config.getBool(ConfigKey.INCLUDE_FAMILY); - String familyName = ""; - if (useFamilyName) { - // Try translating family name - try { - final PokemonId familyPokemonId = PokemonId.valueOf(poke.getPokemonFamily().toString().replaceAll(StringLiterals.FAMILY_PREFIX, "")); - familyName = PokemonUtils.getLocalPokeName(familyPokemonId.getNumber()); - } catch (final IllegalArgumentException e) { - familyName = poke.getPokemonFamily().toString(); - } - } - - String searchme = Utilities.concatString(',', - PokemonUtils.getLocalPokeName(poke), - ((useFamilyName) ? familyName : ""), - poke.getNickname(), - poke.getSettings().getType().toString(), - poke.getSettings().getType2().toString(), - poke.getMove1().toString(), - poke.getMove2().toString(), - poke.getPokeball().toString()); - searchme = searchme.replaceAll("_FAST", "").replaceAll(StringLiterals.FAMILY_PREFIX, "").replaceAll("NONE", "") - .replaceAll("ITEM_", "").replaceAll(StringLiterals.POKEMON_TYPE_PREFIX, "").replaceAll(StringLiterals.UNDERSCORE, "") - .replaceAll(StringLiterals.SPACE, "").toLowerCase(); - - for (final String s : terms) { - if (searchme.contains(s)) { - pokes.add(poke); - // Break, so that a Pokémon isn't added twice even if it - // matches more than one criteria - break; - } - } - }); + pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); + if (selectedRows != null) { + for (Integer index : selectedRows) { + pt.addRowSelectionInterval(index, index); } } - pt.constructNewTableModel(pokes); - } catch (final Exception e) { e.printStackTrace(); } } - + /** * Provide custom formatting for the list of patterns. */ @@ -1089,4 +1086,9 @@ public List getColumnErrors() { public void saveColumnOrder() { pt.saveColumnOrderToConfig(); } + + public static ItemBag getPlayerItems() + { + return go.getInventories().getItemBag(); + } } From 2b25d2a007c4a37fa836d270eb6544502a7be1ff Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Tue, 28 Feb 2017 12:49:42 -0300 Subject: [PATCH 07/41] Fixing codeclimate/codacy issues Work in progress --- .../pokegoutil/data/enums/ColumnType.java | 2 +- .../pokegoutil/data/enums/PokeColumn.java | 20 +++--- .../utils/helpers/EvolveHelper.java | 15 +++-- .../utils/windows/PokemonRowFilter.java | 67 +++++++++++++++++++ .../utils/windows/PokemonTable.java | 48 ++----------- .../utils/windows/PokemonTableModel.java | 59 ++++++++++------ .../windows/renderer/CheckBoxCellEditor.java | 23 ++++--- .../renderer/CheckBoxCellRenderer.java | 18 +++-- 8 files changed, 156 insertions(+), 96 deletions(-) create mode 100644 src/me/corriekay/pokegoutil/utils/windows/PokemonRowFilter.java diff --git a/src/me/corriekay/pokegoutil/data/enums/ColumnType.java b/src/me/corriekay/pokegoutil/data/enums/ColumnType.java index 1a164623..a1a366bd 100644 --- a/src/me/corriekay/pokegoutil/data/enums/ColumnType.java +++ b/src/me/corriekay/pokegoutil/data/enums/ColumnType.java @@ -3,7 +3,6 @@ import java.util.Comparator; import java.util.concurrent.CompletableFuture; -import javax.swing.DefaultCellEditor; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; @@ -135,6 +134,7 @@ private static final class Comparators { * @param clazz The class type of the column, what the data is. * @param comparator The comparator for that column. * @param tableCellRenderer The table cell renderer. + * @param tableCellEditor The table cell editor. */ ColumnType(final Class clazz, final Comparator comparator, final TableCellRenderer tableCellRenderer, final TableCellEditor tableCellEditor) { this.clazz = clazz; diff --git a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java index 161efa1f..8d8eacf8 100644 --- a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java +++ b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java @@ -141,7 +141,7 @@ public Object get(final Pokemon p) { @Override public Object get(final Pokemon p) { final PokemonMove move = p.getMove1(); - PokemonType type = PokemonMeta.getMoveSettings(move).getPokemonType(); + final PokemonType type = PokemonMeta.getMoveSettings(move).getPokemonType(); return PokemonUtils.formatType(type); } }, @@ -149,7 +149,7 @@ public Object get(final Pokemon p) { @Override public Object get(final Pokemon p) { final PokemonMove move = p.getMove2(); - PokemonType type = PokemonMeta.getMoveSettings(move).getPokemonType(); + final PokemonType type = PokemonMeta.getMoveSettings(move).getPokemonType(); return PokemonUtils.formatType(type); } }, @@ -207,13 +207,13 @@ public Object get(final Pokemon p) { if (PokemonTab.mapPokemonItem.containsKey(p.getId())) { return PokemonTab.mapPokemonItem.get(p.getId()); } - List evolutionBranch = p.getEvolutionBranch(); - if (evolutionBranch != null && evolutionBranch.size()>0) { - for (EvolutionBranch evoBranch : evolutionBranch) { - if(evoBranch.getEvolutionItemRequirement()!=null && - evoBranch.getEvolutionItemRequirement()!=ItemId.UNRECOGNIZED && - evoBranch.getEvolutionItemRequirement()!=ItemId.ITEM_UNKNOWN) { - EvolveHelper evolve = new EvolveHelper(evoBranch.getEvolution(), evoBranch.getEvolutionItemRequirement()); + final List evolutionBranch = p.getEvolutionBranch(); + if (evolutionBranch != null && evolutionBranch.size() > 0) { + for (final EvolutionBranch evoBranch : evolutionBranch) { + if (evoBranch.getEvolutionItemRequirement() != null + && evoBranch.getEvolutionItemRequirement() != ItemId.UNRECOGNIZED + && evoBranch.getEvolutionItemRequirement() != ItemId.ITEM_UNKNOWN) { + final EvolveHelper evolve = new EvolveHelper(evoBranch.getEvolution(), evoBranch.getEvolutionItemRequirement()); PokemonTab.mapPokemonItem.put(p.getId(), evolve); return evolve; } @@ -225,7 +225,7 @@ public Object get(final Pokemon p) { STARDUST_TO_POWERUP("Stardust", ColumnType.NULLABLE_INT) { @Override public Object get(final Pokemon p) { - int startdust = p.getStardustCostsForPowerup(); + final int startdust = p.getStardustCostsForPowerup(); if (startdust != 0) { return String.valueOf(startdust); } else { diff --git a/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java b/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java index 3db248f5..60e61f26 100644 --- a/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java +++ b/src/me/corriekay/pokegoutil/utils/helpers/EvolveHelper.java @@ -5,7 +5,7 @@ import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; /** - * Helper class for evolving with itens + * Helper class for evolving with itens. */ public final class EvolveHelper implements Comparable { @@ -13,7 +13,12 @@ public final class EvolveHelper implements Comparable { private ItemId itemToEvolve; private boolean evolveWithItem; - public EvolveHelper(PokemonId pokemon, ItemId item) { + /** + * Default constructor. + * @param pokemon the pokemon that require item to evolve + * @param item required to evolve to pokemon + */ + public EvolveHelper(final PokemonId pokemon, final ItemId item) { this.pokemonToEvolve = pokemon; this.itemToEvolve = item; this.evolveWithItem = false; @@ -36,7 +41,7 @@ public ItemId getItemToEvolveId() { return this.itemToEvolve; } - public void setItemToEvolve(ItemId itemToEvolve) { + public void setItemToEvolve(final ItemId itemToEvolve) { this.itemToEvolve = itemToEvolve; } @@ -44,12 +49,12 @@ public boolean isEvolveWithItem() { return evolveWithItem; } - public void setEvolveWithItem(boolean evolveWithItem) { + public void setEvolveWithItem(final boolean evolveWithItem) { this.evolveWithItem = evolveWithItem; } @Override - public int compareTo(EvolveHelper o) { + public int compareTo(final EvolveHelper o) { return this.toString().compareTo(o.toString()); } } diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonRowFilter.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonRowFilter.java new file mode 100644 index 00000000..c2f088e6 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonRowFilter.java @@ -0,0 +1,67 @@ +package me.corriekay.pokegoutil.utils.windows; + +import javax.swing.RowFilter; + +import com.pokegoapi.api.pokemon.Pokemon; + +import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; +import me.corriekay.pokegoutil.utils.ConfigKey; +import me.corriekay.pokegoutil.utils.ConfigNew; +import me.corriekay.pokegoutil.utils.StringLiterals; +import me.corriekay.pokegoutil.utils.Utilities; +import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; + +/** + * Helper class to filter the contents of the table based on the fields of the Pokemon class. + */ +public class PokemonRowFilter extends RowFilter { + final String filterText; + + /** + * Default constructor to store filterText variable that will be used in the override "include" method. + * @param filterText the text that will be used as filter + */ + PokemonRowFilter(final String filterText) { + this.filterText = filterText; + } + + @Override + public boolean include(final javax.swing.RowFilter.Entry entry) { + final Pokemon poke = entry.getModel().getPokemonByIndexNotConverting(entry.getIdentifier()); + if (poke != null) { + final boolean useFamilyName = ConfigNew.getConfig().getBool(ConfigKey.INCLUDE_FAMILY); + String familyName = ""; + if (useFamilyName) { + // Try translating family name + try { + final PokemonId familyPokemonId = PokemonId.valueOf(poke.getPokemonFamily().toString().replaceAll(StringLiterals.FAMILY_PREFIX, "")); + familyName = PokemonUtils.getLocalPokeName(familyPokemonId.getNumber()); + } catch (final IllegalArgumentException e) { + familyName = poke.getPokemonFamily().toString(); + } + } + + String searchme = Utilities.concatString(',', + PokemonUtils.getLocalPokeName(poke), + useFamilyName ? familyName : "", + poke.getNickname(), + poke.getSettings().getType().toString(), + poke.getSettings().getType2().toString(), + poke.getMove1().toString(), + poke.getMove2().toString(), + poke.getPokeball().toString()); + searchme = searchme.replaceAll("_FAST", "").replaceAll(StringLiterals.FAMILY_PREFIX, "").replaceAll("NONE", "") + .replaceAll("ITEM_", "").replaceAll(StringLiterals.POKEMON_TYPE_PREFIX, "").replaceAll(StringLiterals.UNDERSCORE, "") + .replaceAll(StringLiterals.SPACE, "").toLowerCase(); + + final String[] terms = filterText.split(";"); + for (final String s : terms) { + if (searchme.contains(s)) { + return true; + } + } + return false; + } + return true; + } +} diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java index 6b329905..376e8fe5 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java @@ -197,53 +197,13 @@ private void pack() { } /** - * Function for filtering the table using the proper RowFilter of Java + * Function for filtering the table using the proper RowFilter of Java. * @param filterText the text to be filtered */ - public void filterTable(String filterText) { + public void filterTable(final String filterText) { RowFilter rowFilter = null; - if (filterText != null && filterText != "") { - rowFilter = new RowFilter() { - @Override - public boolean include(javax.swing.RowFilter.Entry entry) { - Pokemon poke = entry.getModel().getPokemonByIndexNotConverting(entry.getIdentifier()); - if(poke != null) { - final boolean useFamilyName = config.getBool(ConfigKey.INCLUDE_FAMILY); - String familyName = ""; - if (useFamilyName) { - // Try translating family name - try { - final PokemonId familyPokemonId = PokemonId.valueOf(poke.getPokemonFamily().toString().replaceAll(StringLiterals.FAMILY_PREFIX, "")); - familyName = PokemonUtils.getLocalPokeName(familyPokemonId.getNumber()); - } catch (final IllegalArgumentException e) { - familyName = poke.getPokemonFamily().toString(); - } - } - - String searchme = Utilities.concatString(',', - PokemonUtils.getLocalPokeName(poke), - ((useFamilyName) ? familyName : ""), - poke.getNickname(), - poke.getSettings().getType().toString(), - poke.getSettings().getType2().toString(), - poke.getMove1().toString(), - poke.getMove2().toString(), - poke.getPokeball().toString()); - searchme = searchme.replaceAll("_FAST", "").replaceAll(StringLiterals.FAMILY_PREFIX, "").replaceAll("NONE", "") - .replaceAll("ITEM_", "").replaceAll(StringLiterals.POKEMON_TYPE_PREFIX, "").replaceAll(StringLiterals.UNDERSCORE, "") - .replaceAll(StringLiterals.SPACE, "").toLowerCase(); - - final String[] terms = filterText.split(";"); - for (final String s : terms) { - if (searchme.contains(s)) { - return true; - } - } - return false; - } - return true; - } - }; + if (filterText != null && !"".equals(filterText)) { + rowFilter = new PokemonRowFilter(filterText); } trs.setRowFilter(rowFilter); } diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java index 707c4248..4d8432ec 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java @@ -10,15 +10,24 @@ import com.pokegoapi.api.pokemon.Pokemon; import me.corriekay.pokegoutil.data.enums.PokeColumn; +import me.corriekay.pokegoutil.utils.logging.ConsolePrintStream; -@SuppressWarnings( {"serial"}) - +/** + * Extended from AbstractTableModel to provide useful methos to PokemonTabel. + */ public class PokemonTableModel extends AbstractTableModel { - PokemonTable pt; + private static final long serialVersionUID = -1942850053142414172L; + + private PokemonTable pt; private final ArrayList pokeCol = new ArrayList<>(); + /** + * Default constructor. + * @param pokes list of pokemons to display + * @param pt the pokemonTabel instance + */ PokemonTableModel(final List pokes, final PokemonTable pt) { this.pt = pt; @@ -39,11 +48,13 @@ public void updateTableData(final List pokes) { pokeCol.add(i.getValue(), p); for (final PokeColumn column : PokeColumn.values()) { + // Reason: To avoid future problems inside whatever columns + // noinspection CheckStyle try { column.data.add(i.getValue(), column.get(p)); } catch (NullPointerException e) { - System.out.println("Error getting data for column: " + column.heading); - e.printStackTrace(); + System.out.println("Error getting data for column: " + column.heading + " and value: " + i.getValue()); + ConsolePrintStream.printException(e); } } @@ -60,29 +71,37 @@ private void ClearTable() { } } + /** + * Return the Index of the pokemon in the list. + * @param p pokemon that should have the index returned + * @return index of the pokemon p + */ public int getIndexByPokemon(final Pokemon p) { - try { - return pokeCol.indexOf(p); - } catch (final Exception e) { - e.printStackTrace(); - return -1; - } + return pokeCol.indexOf(p); } - public Pokemon getPokemonByIndex(final int i) { + /** + * Return the pokemon by the index after converted by "convertRowIndexToModel". + * @param index index of the pokemon that should be returned + * @return the pokemon in the index i + */ + public Pokemon getPokemonByIndex(final int index) { try { - return pokeCol.get(pt.convertRowIndexToModel(i)); - } catch (final Exception e) { - e.printStackTrace(); + return pokeCol.get(pt.convertRowIndexToModel(index)); + } catch (final IndexOutOfBoundsException e) { return null; } } - - public Pokemon getPokemonByIndexNotConverting(final int i) { + + /** + * Return the pokemon by the index without converting by "convertRowIndexToModel". + * @param index index of the pokemon that should be returned + * @return the pokemon in the index i + */ + public Pokemon getPokemonByIndexNotConverting(final int index) { try { - return pokeCol.get(i); - } catch (final Exception e) { - e.printStackTrace(); + return pokeCol.get(index); + } catch (final IndexOutOfBoundsException e) { return null; } } diff --git a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java index 87206fc9..c8b0a783 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java +++ b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellEditor.java @@ -11,28 +11,31 @@ import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; /** - * Provide custom formatting for the moveset ranking columns while allowing sorting on original values. + * Provide a checkbox editor for clicking in the checkBox renderer and editing the content. */ -@SuppressWarnings("serial") class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor, ItemListener { - private CheckBoxCellRenderer vr = new CheckBoxCellRenderer(); + private static final long serialVersionUID = 7138280995796928980L; + private CheckBoxCellRenderer checkBoxCellRenderer = new CheckBoxCellRenderer(); private EvolveHelper evolve; - public CheckBoxCellEditor() { - vr.getCheckBox().addItemListener(this); + /** + * Default constructor to add a listener in the checkBox renderer. + */ + CheckBoxCellEditor() { + checkBoxCellRenderer.getCheckBox().addItemListener(this); } @Override public Object getCellEditorValue() { - return vr.getCheckBox().isSelected(); + return checkBoxCellRenderer.getCheckBox().isSelected(); } @Override - public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) { + public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int col) { if (value != null) { - CheckBoxCellRenderer chcr = (CheckBoxCellRenderer) vr.getTableCellRendererComponent(table, value, isSelected, true, row, col); - if(chcr.getCheckBox().isEnabled()) { + final CheckBoxCellRenderer chcr = (CheckBoxCellRenderer) checkBoxCellRenderer.getTableCellRendererComponent(table, value, isSelected, true, row, col); + if (chcr.getCheckBox().isEnabled()) { evolve = (EvolveHelper) value; return chcr; } @@ -41,7 +44,7 @@ public Component getTableCellEditorComponent(JTable table, Object value, boolean } @Override - public void itemStateChanged(ItemEvent e) { + public void itemStateChanged(final ItemEvent e) { if (evolve != null) { evolve.setEvolveWithItem(e.getStateChange() == ItemEvent.SELECTED); evolve = null; diff --git a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java index 911326ee..fd1547f8 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java +++ b/src/me/corriekay/pokegoutil/utils/windows/renderer/CheckBoxCellRenderer.java @@ -17,14 +17,18 @@ /** * Provide custom formatting for the moveset ranking columns while allowing sorting on original values. */ -@SuppressWarnings("serial") public class CheckBoxCellRenderer extends JPanel implements TableCellRenderer { + // Padding left and right can be overwritten by custom renderer. protected static final int PADDING_LEFT = 3; protected static final int PADDING_RIGHT = 3; + private static final long serialVersionUID = 1340158676852621702L; private JCheckBox checkBox; + /** + * Default constructor for creating the component properly. + */ public CheckBoxCellRenderer() { super(new FlowLayout(FlowLayout.LEADING, 0, 0)); checkBox = new JCheckBox(); @@ -33,23 +37,21 @@ public CheckBoxCellRenderer() { add(checkBox); } - @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int rowIndex, final int columnIndex) { if (value != null) { - EvolveHelper evolve = (EvolveHelper) value; + final EvolveHelper evolve = (EvolveHelper) value; checkBox.setVisible(true); checkBox.setSelected(evolve.isEvolveWithItem()); - int itemCount = PokemonTab.getPlayerItems().getItem(evolve.getItemToEvolveId()).getCount(); + final int itemCount = PokemonTab.getPlayerItems().getItem(evolve.getItemToEvolveId()).getCount(); checkBox.setText(evolve.toString() + " [" + itemCount + "]"); checkBox.setEnabled(true); if (itemCount <= 0) { checkBox.setEnabled(false); checkBox.setOpaque(false); } - } - else { + } else { checkBox.setEnabled(true); checkBox.setText(""); checkBox.setVisible(false); @@ -91,6 +93,10 @@ private void setDefaultSelectionColors(final JTable table, final boolean isSelec } } + /** + * Return the checkBox component. + * @return checkBox component + */ public JCheckBox getCheckBox() { return checkBox; } From f4c7dbd342a8bc4afee7964cd9e6e56638eec56a Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Tue, 28 Feb 2017 14:59:21 -0300 Subject: [PATCH 08/41] Fixing codeclimate/codacy issues Work in progress --- .../pokegoutil/data/enums/PokeColumn.java | 6 +- .../utils/windows/PokemonTable.java | 4 - .../pokegoutil/windows/PokemonTab.java | 75 ++++++++++--------- 3 files changed, 43 insertions(+), 42 deletions(-) diff --git a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java index e5ab9a40..260ae7bb 100644 --- a/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java +++ b/src/me/corriekay/pokegoutil/data/enums/PokeColumn.java @@ -204,8 +204,8 @@ public Object get(final Pokemon p) { ITEM_TO_EVOLVE("Item To Evolve", ColumnType.EVOLVE_CHECK_BOX) { @Override public Object get(final Pokemon p) { - if (PokemonTab.mapPokemonItem.containsKey(p.getId())) { - return PokemonTab.mapPokemonItem.get(p.getId()); + if (PokemonTab.MAP_POKEMON_ITEM.containsKey(p.getId())) { + return PokemonTab.MAP_POKEMON_ITEM.get(p.getId()); } final List evolutionBranch = p.getEvolutionBranch(); if (evolutionBranch != null && evolutionBranch.size() > 0) { @@ -214,7 +214,7 @@ public Object get(final Pokemon p) { && evoBranch.getEvolutionItemRequirement() != ItemId.UNRECOGNIZED && evoBranch.getEvolutionItemRequirement() != ItemId.ITEM_UNKNOWN) { final EvolveHelper evolve = new EvolveHelper(evoBranch.getEvolution(), evoBranch.getEvolutionItemRequirement()); - PokemonTab.mapPokemonItem.put(p.getId(), evolve); + PokemonTab.MAP_POKEMON_ITEM.put(p.getId(), evolve); return evolve; } } diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java index 8c6348a5..f4d41e6b 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java @@ -18,14 +18,10 @@ import com.pokegoapi.api.pokemon.Pokemon; -import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; -import me.corriekay.pokegoutil.utils.StringLiterals; -import me.corriekay.pokegoutil.utils.Utilities; import me.corriekay.pokegoutil.utils.helpers.JTableColumnPacker; -import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; /** * The Pokémon Table. Extended JTable which displays all Pokémon and does the needed diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index 9ff0fcb7..d4d73b4d 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -74,28 +74,28 @@ /** * The main PokemonTab. */ -@SuppressWarnings("serial") public class PokemonTab extends JPanel { + public static final Map MAP_POKEMON_ITEM = new HashMap(); + private static final long serialVersionUID = -3356302801659055820L; private static PokemonGo go; - private final PokemonTable pt; - private static final JTextField searchBar = new JTextField(""); - private static final JTextField ivTransfer = new JTextField("", 20); - private static final ConfigNew config = ConfigNew.getConfig(); - public static final HashMap mapPokemonItem = new HashMap(); - + // Used constants private static final int WHEN_TO_SHOW_SELECTION_TITLE = 2; private static final String GYM_SKIPPED_MESSAGE_UNFORMATTED = "%s with %d CP is in gym, skipping."; private static final int POPUP_WIDTH = 500; private static final int POPUP_HEIGHT = 400; private static final int MIN_FONT_SIZE = 2; - private List selectedRows; + + private final PokemonTable pt; + private List selectedRowsList; + private final JTextField searchBar = new JTextField(""); + private final JTextField ivTransfer = new JTextField("", 20); + private final ConfigNew config = ConfigNew.getConfig(); /** * Creates an instance of the PokemonTab. - * - * @param go The go api class. + * @param goInstance The go api class. */ public PokemonTab(final PokemonGo goInstance) { super(); @@ -117,8 +117,8 @@ public PokemonTab(final PokemonGo goInstance) { return; } if (event.getSource() == pt.getSelectionModel() && pt.getRowSelectionAllowed()) { - if(pt.getSelectionModel().getAnchorSelectionIndex() > -1 && pt.getSelectionModel().getLeadSelectionIndex() > -1) { - selectedRows = Arrays.stream(pt.getSelectedRows()).boxed().collect(Collectors.toList()); + if (pt.getSelectionModel().getAnchorSelectionIndex() > -1 && pt.getSelectionModel().getLeadSelectionIndex() > -1) { + selectedRowsList = Arrays.stream(pt.getSelectedRows()).boxed().collect(Collectors.toList()); } final int selectedRows = pt.getSelectedRowCount(); if (selectedRows >= WHEN_TO_SHOW_SELECTION_TITLE) { @@ -528,11 +528,10 @@ private void evolveSelected() { } final EvolutionResult evolutionResultWrapper; - EvolveHelper evolve = mapPokemonItem.get(poke.getId()); + final EvolveHelper evolve = MAP_POKEMON_ITEM.get(poke.getId()); if (evolve != null && evolve.isEvolveWithItem()) { evolutionResultWrapper = poke.evolve(evolve.getItemToEvolveId()); - } - else { + } else { evolutionResultWrapper = poke.evolve(); } if (evolutionResultWrapper.isSuccessful()) { @@ -937,8 +936,8 @@ private JPanel buildPanelForOperation(final BatchOperation operation, final Arra case EVOLVE: str += " Cost: " + p.getCandiesToEvolve(); str += p.getCandiesToEvolve() > 1 ? " Candies" : " Candy"; - if (mapPokemonItem.containsKey(p.getId())) { - EvolveHelper evolve = mapPokemonItem.get(p.getId()); + if (MAP_POKEMON_ITEM.containsKey(p.getId())) { + final EvolveHelper evolve = MAP_POKEMON_ITEM.get(p.getId()); if (evolve.isEvolveWithItem()) { str += " Evolving to " + evolve.getPokemonToEvolve() + " using " + evolve.getItemToEvolve(); } @@ -1026,19 +1025,23 @@ public ArrayList getSelectedPokemon() { return pokes; } - public void removeSelection(Pokemon p) { + /** + * Helper method to remove the pokemon from the selectedRowsList. + * @param p pokemon that will be removed from the list + */ + public void removeSelection(final Pokemon p) { final PokemonTableModel model = (PokemonTableModel) pt.getModel(); - int index = model.getIndexByPokemon(p); + final int index = model.getIndexByPokemon(p); if (index > 0) { - selectedRows.remove(index); + selectedRowsList.remove(index); } } public void refreshList() { try { pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); - if (selectedRows != null) { - for (Integer index : selectedRows) { + if (selectedRowsList != null) { + for (Integer index : selectedRowsList) { pt.addRowSelectionInterval(index, index); } } @@ -1046,11 +1049,26 @@ public void refreshList() { e.printStackTrace(); } } + + public static ItemBag getPlayerItems() { + return go.getInventories().getItemBag(); + } + + public List getColumnErrors() { + return pt.getColumnErrors(); + } + + public void saveColumnOrder() { + pt.saveColumnOrderToConfig(); + } /** * Provide custom formatting for the list of patterns. */ private class ReplacePatternRenderer extends JLabel implements ListCellRenderer { + + private static final long serialVersionUID = -7057892212235868835L; + /** * Constructor to create a ReplacePatternRenderer. */ @@ -1078,17 +1096,4 @@ public Component getListCellRendererComponent(final JList getColumnErrors() { - return pt.getColumnErrors(); - } - - public void saveColumnOrder() { - pt.saveColumnOrderToConfig(); - } - - public static ItemBag getPlayerItems() - { - return go.getInventories().getItemBag(); - } } From 6a287d68036fa1f9b9199ebe002d6cd83bf3f9a4 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Thu, 2 Mar 2017 02:25:01 -0300 Subject: [PATCH 09/41] Refactoring PokemonTab, PokemonTable and creating auxiliar classes to decrease class complexity and fixing some codeclimate issues. --- .../helpers/InvalidIvValueException.java | 16 + .../utils/ui/IVTransferTextField.java | 47 +++ .../utils/ui/SearchBarTextField.java | 35 ++ .../utils/windows/PokemonTable.java | 99 ++++-- .../corriekay/pokegoutil/windows/MenuBar.java | 2 +- .../pokegoutil/windows/OperationWorker.java | 42 +++ .../windows/PokemonGoMainWindow.java | 29 +- .../pokegoutil/windows/PokemonTab.java | 317 +++++------------- 8 files changed, 315 insertions(+), 272 deletions(-) create mode 100644 src/me/corriekay/pokegoutil/utils/helpers/InvalidIvValueException.java create mode 100644 src/me/corriekay/pokegoutil/utils/ui/IVTransferTextField.java create mode 100644 src/me/corriekay/pokegoutil/utils/ui/SearchBarTextField.java create mode 100644 src/me/corriekay/pokegoutil/windows/OperationWorker.java diff --git a/src/me/corriekay/pokegoutil/utils/helpers/InvalidIvValueException.java b/src/me/corriekay/pokegoutil/utils/helpers/InvalidIvValueException.java new file mode 100644 index 00000000..591ed1d1 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/helpers/InvalidIvValueException.java @@ -0,0 +1,16 @@ +package me.corriekay.pokegoutil.utils.helpers; + +/** + * Exception class to help validate IV value inside method. + */ +public class InvalidIvValueException extends Exception { + + private static final long serialVersionUID = 7145962829371471669L; + + /** + * Default constructor to show a invalid msg on console. + */ + public InvalidIvValueException() { + super("Please select a valid IV value (0-100)"); + } +} diff --git a/src/me/corriekay/pokegoutil/utils/ui/IVTransferTextField.java b/src/me/corriekay/pokegoutil/utils/ui/IVTransferTextField.java new file mode 100644 index 00000000..958cfd35 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/ui/IVTransferTextField.java @@ -0,0 +1,47 @@ +package me.corriekay.pokegoutil.utils.ui; + +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.util.function.Consumer; + +import javax.swing.JTextField; + +import me.corriekay.pokegoutil.windows.OperationWorker; + +/** + * Helper class to encapsulate methods and fields used by IVTransfer JTextField. + */ +public class IVTransferTextField extends JTextField { + + private static final int DEFAULT_SIZE = 20; + private static final long serialVersionUID = -1497271459888003626L; + + /** + * Default constructor that initialize the JTextField with the default properties. + * @param action function that will be called passing the text present in this TextField + */ + public IVTransferTextField(final Consumer action) { + super("", DEFAULT_SIZE); + this.addKeyListener( + new KeyListener() { + @Override + public void keyPressed(final KeyEvent event) { + if (event.getKeyCode() == KeyEvent.VK_ENTER) { + new OperationWorker(action, IVTransferTextField.this.getText()).execute(); + } + } + + @Override + public void keyTyped(final KeyEvent event) { + // nothing here + } + + @Override + public void keyReleased(final KeyEvent event) { + // nothing here + } + }); + + new GhostText(this, "Pokemon IV"); + } +} diff --git a/src/me/corriekay/pokegoutil/utils/ui/SearchBarTextField.java b/src/me/corriekay/pokegoutil/utils/ui/SearchBarTextField.java new file mode 100644 index 00000000..74583aa0 --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/ui/SearchBarTextField.java @@ -0,0 +1,35 @@ +package me.corriekay.pokegoutil.utils.ui; + +import java.util.function.Consumer; + +import javax.swing.JTextField; + +import me.corriekay.pokegoutil.utils.StringLiterals; +import me.corriekay.pokegoutil.utils.helpers.LDocumentListener; + +/** + * SearchBar component to encapsulate contents related to search mechanics. + */ +public class SearchBarTextField extends JTextField { + + private static final long serialVersionUID = -8207087504009285250L; + + /** + * Default constructor for creating the JTextField with empty string. + * @param filterMethod method that will be called whenever this textField changes. + */ + public SearchBarTextField(final Consumer filterMethod) { + super(""); + + LDocumentListener.addChangeListener(this, e -> { + String search = getText().replaceAll(StringLiterals.SPACE, "").replaceAll(StringLiterals.UNDERSCORE, "").replaceAll("snek", "ekans") + .toLowerCase(); + if ("searchpokémon...".equals(search)) { + search = ""; + } + filterMethod.accept(search); + }); + new GhostText(this, "Search Pokémon..."); + } + +} diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java index f4d41e6b..b72d773d 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java @@ -1,5 +1,6 @@ package me.corriekay.pokegoutil.utils.windows; +import java.awt.Font; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; @@ -16,11 +17,14 @@ import javax.swing.table.TableColumn; import javax.swing.table.TableRowSorter; +import org.apache.commons.lang3.math.NumberUtils; + import com.pokegoapi.api.pokemon.Pokemon; import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; +import me.corriekay.pokegoutil.utils.helpers.InvalidIvValueException; import me.corriekay.pokegoutil.utils.helpers.JTableColumnPacker; /** @@ -29,14 +33,15 @@ *

* Added things are row sorter, column comparators, listener and the cell renderers. */ -@SuppressWarnings("serial") public class PokemonTable extends JTable { // Global statics public static final int COLUMN_MARGIN = 3; public static final int ROW_HEIGHT_PADDING = ConfigNew.getConfig().getInt(ConfigKey.ROW_PADDING); + private static final long serialVersionUID = 8205978051944394627L; private static final String COLUMN_SEPARATOR = ","; + private static final int MIN_FONT_SIZE = 2; private final ConfigNew config = ConfigNew.getConfig(); @@ -99,8 +104,7 @@ public PokemonTable() { } try { restoreColumnOrder(); - } - catch(Exception exc) { + } catch (Exception exc) { System.out.println("Oooops, something went wrong with table order rearranging!"); System.out.println(exc.toString()); } @@ -110,7 +114,7 @@ public PokemonTable() { * Loads the column order settings from configuration and applies them to the table. */ private void restoreColumnOrder() { - List myColumnEnumNames = new LinkedList(); + final List myColumnEnumNames = new LinkedList(); final String columnOrder = config.getString(ConfigKey.POKEMONTABLE_COLUMNORDER); if (columnOrder != null && !columnOrder.isEmpty()) { myColumnEnumNames.addAll(Arrays.asList(columnOrder.split(COLUMN_SEPARATOR))); @@ -120,19 +124,18 @@ private void restoreColumnOrder() { } int newIndex = 0; - for (String enumName : myColumnEnumNames) { + for (final String enumName : myColumnEnumNames) { try { - PokeColumn pokeColumn = PokeColumn.valueOf(enumName); - TableColumn c = this.getColumn(pokeColumn.heading); + final PokeColumn pokeColumn = PokeColumn.valueOf(enumName); + final TableColumn c = this.getColumn(pokeColumn.heading); if (c != null) { - int currentIndex = this.convertColumnIndexToView(c.getModelIndex()); + final int currentIndex = this.convertColumnIndexToView(c.getModelIndex()); if (currentIndex != newIndex) { this.getColumnModel().moveColumn(currentIndex, newIndex); } newIndex++; } - } - catch(IllegalArgumentException exc) { + } catch (IllegalArgumentException exc) { columnErrors.add(enumName); } } @@ -143,20 +146,14 @@ private void restoreColumnOrder() { * globbed together separated by COLUMN_SEPARATOR. */ public void saveColumnOrderToConfig() { - List enumNames = new LinkedList(); - Enumeration e = this.getColumnModel().getColumns(); - while(e.hasMoreElements()) { - String columnHeading = e.nextElement().getHeaderValue().toString(); - try { - enumNames.add(PokeColumn.getForHeading(columnHeading).toString()); - } - catch (IllegalArgumentException exc) - { - // can this happen in production use? - } + final List enumNames = new LinkedList(); + final Enumeration e = this.getColumnModel().getColumns(); + while (e.hasMoreElements()) { + final String columnHeading = e.nextElement().getHeaderValue().toString(); + enumNames.add(PokeColumn.getForHeading(columnHeading).toString()); } final String columnOrderEnums = String.join(COLUMN_SEPARATOR, enumNames); - ConfigNew.getConfig().setString(ConfigKey.POKEMONTABLE_COLUMNORDER, columnOrderEnums); + config.setString(ConfigKey.POKEMONTABLE_COLUMNORDER, columnOrderEnums); } /** @@ -245,4 +242,62 @@ public void filterTable(final String filterText) { } trs.setRowFilter(rowFilter); } + + /** + * Set font size if specified in config file. + */ + public void applySpecifiedFontSize() { + final Font font = getFont(); + final int size = Math.max(MIN_FONT_SIZE, config.getInt(ConfigKey.FONT_SIZE, font.getSize())); + if (size != font.getSize()) { + setFont(font.deriveFont((float) size)); + } + } + + /** + * Return the selected pokemons on the list. + * @return ArrayList of the selected pokemons + */ + public ArrayList getSelectedPokemon() { + final ArrayList pokes = new ArrayList<>(); + final PokemonTableModel model = (PokemonTableModel) getModel(); + for (final int i : getSelectedRows()) { + final Pokemon poke = model.getPokemonByIndex(i); + if (poke != null) { + pokes.add(poke); + } + } + return pokes; + } + + /** + * Method for selecting pokemons with IV less than "text". + * @param text iv passed as argument to be selected. + */ + public void selectLessThanIv(final String text) { + try { + if (!NumberUtils.isNumber(text)) { + throw new InvalidIvValueException(); + } + + final double ivLessThan = Double.parseDouble(text); + final int maxIvValue = 100; + if (ivLessThan > maxIvValue || ivLessThan < 0) { + throw new InvalidIvValueException(); + } + + clearSelection(); + System.out.println("Selecting Pokemon with IV less than: " + text); + + for (int i = 0; i < getRowCount(); i++) { + final double pIv = (double) getValueAt(i, getIndexForColumnEnum(PokeColumn.IV_RATING)) * 100; + if (pIv < ivLessThan) { + getSelectionModel().addSelectionInterval(i, i); + } + } + } catch (InvalidIvValueException e) { + System.out.println(e.getMessage()); + } + + } } diff --git a/src/me/corriekay/pokegoutil/windows/MenuBar.java b/src/me/corriekay/pokegoutil/windows/MenuBar.java index 8cde4968..07075b21 100644 --- a/src/me/corriekay/pokegoutil/windows/MenuBar.java +++ b/src/me/corriekay/pokegoutil/windows/MenuBar.java @@ -74,7 +74,7 @@ public MenuBar(PokemonGo go, PokemonTab pokemonTab) { includeFamily.addItemListener( e -> { config.setBool(ConfigKey.INCLUDE_FAMILY, includeFamily.isSelected()); - if (!pokemonTab.getSelectedPokemon().isEmpty()) { + if (!pokemonTab.getPokemonTable().getSelectedPokemon().isEmpty()) { SwingUtilities.invokeLater(pokemonTab::refreshList); } }); diff --git a/src/me/corriekay/pokegoutil/windows/OperationWorker.java b/src/me/corriekay/pokegoutil/windows/OperationWorker.java new file mode 100644 index 00000000..b10378f8 --- /dev/null +++ b/src/me/corriekay/pokegoutil/windows/OperationWorker.java @@ -0,0 +1,42 @@ +package me.corriekay.pokegoutil.windows; + +import java.util.function.Consumer; + +import javax.swing.SwingWorker; + +/** + * Worker class to call the functions of each operation in a generic way. + */ +public final class OperationWorker extends SwingWorker { + private Runnable function; + private Consumer stringConsumer; + private String consumable; + + /** + * Constructor that receives a function that has none arguments and just call it. + * @param function with no arguments that will be called in the "doInBackground" method. + */ + public OperationWorker(final Runnable function) { + this.function = function; + } + + /** + * Constructor that receives a function that expect to receive one String and call it. + * @param action function that will be called passin the consumable string to it. + * @param consumable string that will be passed to action function. + */ + public OperationWorker(final Consumer action, final String consumable) { + this.stringConsumer = action; + this.consumable = consumable; + } + + @Override + protected Void doInBackground() { + if (function != null) { + function.run(); + } else if (stringConsumer != null) { + stringConsumer.accept(consumable); + } + return null; + } +} diff --git a/src/me/corriekay/pokegoutil/windows/PokemonGoMainWindow.java b/src/me/corriekay/pokegoutil/windows/PokemonGoMainWindow.java index 9aa1de6f..fbf90665 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonGoMainWindow.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonGoMainWindow.java @@ -32,18 +32,15 @@ */ public class PokemonGoMainWindow extends JFrame { - private static final long serialVersionUID = -6224748358995357643L; - public JTextArea textArea = new JTextArea(); - public JScrollPane jsp; - - public static PokemonGoMainWindow instance = null; + private static PokemonGoMainWindow instance; + private static final long serialVersionUID = -6224748358995357643L; + private static final int TEXT_AREA_HEIGHT = 150; + private final PokemonGo go; private final PlayerProfile pp; private final JTabbedPane tab = new JTabbedPane(); - private static final int textAreaHeight = 150; - private final GlobalSettingsController globalSettings = GlobalSettingsController.getGlobalSettingsController(); /** @@ -95,12 +92,12 @@ public PokemonGoMainWindow(final PokemonGo pkmngo, final boolean smartscroll) { final Updater updater = Updater.getUpdater(); updater.checkForNewVersion(); - List errors = pokemonTab.getColumnErrors(); + final List errors = pokemonTab.getPokemonTable().getColumnErrors(); if (!errors.isEmpty()) { System.out.println("WARNING: Some column names from config could not be recognized!"); - String configString = ConfigNew.getConfig().getString(ConfigKey.POKEMONTABLE_COLUMNORDER); + final String configString = ConfigNew.getConfig().getString(ConfigKey.POKEMONTABLE_COLUMNORDER); System.out.printf("Config string is: '%s'\n", configString); - for (String wrongColumn : errors) { + for (final String wrongColumn : errors) { System.out.printf(" Name not recognized: '%s'\n", wrongColumn); } System.out.println("Existing columns for which no match in configuation was found will appear at the end of the table."); @@ -117,18 +114,18 @@ public PokemonGoMainWindow(final PokemonGo pkmngo, final boolean smartscroll) { * @param smartscroll use smart scroll */ private void initializeConsole(final boolean smartscroll) { + final JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); - jsp = new JScrollPane(textArea); - jsp.setPreferredSize(new Dimension(Integer.MAX_VALUE, textAreaHeight)); + final JScrollPane jsp = new JScrollPane(textArea); + jsp.setPreferredSize(new Dimension(Integer.MAX_VALUE, TEXT_AREA_HEIGHT)); if (smartscroll) { new SmartScroller(jsp); } add(jsp, BorderLayout.SOUTH); globalSettings.getLogController().setTextArea(textArea); - } /** @@ -144,6 +141,9 @@ public PokemonGo getPoGo() { return go; } + /** + * Method for showing the title updated. + */ public void refreshTitle() { try { final NumberFormat f = NumberFormat.getInstance(); @@ -156,6 +156,9 @@ public void refreshTitle() { } } + /** + * Start main Window by showing it. + */ public void start() { setVisible(true); } diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index d4d73b4d..a2ecd699 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -3,14 +3,11 @@ import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; -import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; @@ -29,13 +26,10 @@ import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; -import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.SwingUtilities; -import javax.swing.SwingWorker; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.mutable.MutableInt; import com.pokegoapi.api.PokemonGo; @@ -54,20 +48,19 @@ import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse; import POGOProtos.Networking.Responses.UpgradePokemonResponseOuterClass.UpgradePokemonResponse; import me.corriekay.pokegoutil.data.enums.BatchOperation; -import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.ConfigKey; import me.corriekay.pokegoutil.utils.ConfigNew; import me.corriekay.pokegoutil.utils.StringLiterals; import me.corriekay.pokegoutil.utils.Utilities; import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; -import me.corriekay.pokegoutil.utils.helpers.LDocumentListener; import me.corriekay.pokegoutil.utils.helpers.LocationHelper; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler.ReplacePattern; import me.corriekay.pokegoutil.utils.pokemon.PokeNick; import me.corriekay.pokegoutil.utils.pokemon.PokemonCalculationUtils; import me.corriekay.pokegoutil.utils.pokemon.PokemonUtils; -import me.corriekay.pokegoutil.utils.ui.GhostText; +import me.corriekay.pokegoutil.utils.ui.IVTransferTextField; +import me.corriekay.pokegoutil.utils.ui.SearchBarTextField; import me.corriekay.pokegoutil.utils.windows.PokemonTable; import me.corriekay.pokegoutil.utils.windows.PokemonTableModel; @@ -81,17 +74,18 @@ public class PokemonTab extends JPanel { private static PokemonGo go; // Used constants - private static final int WHEN_TO_SHOW_SELECTION_TITLE = 2; private static final String GYM_SKIPPED_MESSAGE_UNFORMATTED = "%s with %d CP is in gym, skipping."; + private static final int WHEN_TO_SHOW_SELECTION_TITLE = 2; + private static final int GRID_WIDTH = 3; private static final int POPUP_WIDTH = 500; private static final int POPUP_HEIGHT = 400; - private static final int MIN_FONT_SIZE = 2; + // Pokemon name language drop down + private static final String[] LOCALES = {"en", "de", "fr", "ru", "zh_CN", "zh_HK", "ja"}; + private static final String[] SIZES = new String[] {"8", "10", "11", "12", "14", "16", "18"}; private final PokemonTable pt; - private List selectedRowsList; - private final JTextField searchBar = new JTextField(""); - private final JTextField ivTransfer = new JTextField("", 20); private final ConfigNew config = ConfigNew.getConfig(); + private List selectedRowsList; /** * Creates an instance of the PokemonTab. @@ -103,14 +97,8 @@ public PokemonTab(final PokemonGo goInstance) { setLayout(new BorderLayout()); go = goInstance; pt = new PokemonTable(); - final JPanel topPanel = new JPanel(new GridBagLayout()); - final JButton refreshPkmn = new JButton("Refresh List"), - renameSelected = new JButton(BatchOperation.RENAME.toString()), - transferSelected = new JButton(BatchOperation.TRANSFER.toString()), - evolveSelected = new JButton(BatchOperation.EVOLVE.toString()), - powerUpSelected = new JButton(BatchOperation.POWER_UP.toString()), - toggleFavorite = new JButton(BatchOperation.FAVORITE.toString()); - + addAndInitializeComponents(); + pt.getSelectionModel().addListSelectionListener(event -> { if (event.getValueIsAdjusting()) { // We need a break here. Cause otherwise mouse selection would trigger twice. (Yeah, that's swing) @@ -129,155 +117,73 @@ public PokemonTab(final PokemonGo goInstance) { } }); + //Try to apply the specified font size to table + pt.applySpecifiedFontSize(); + + pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); + } + + /** + * Handle component creation and initialization inside PokemonTab constructor. + */ + private void addAndInitializeComponents() { + final SearchBarTextField searchBar = new SearchBarTextField(pt::filterTable); + final JPanel topPanel = new JPanel(new GridBagLayout()); + final JButton refreshPkmn = new JButton("Refresh List"), + renameSelected = new JButton(BatchOperation.RENAME.toString()), + transferSelected = new JButton(BatchOperation.TRANSFER.toString()), + evolveSelected = new JButton(BatchOperation.EVOLVE.toString()), + powerUpSelected = new JButton(BatchOperation.POWER_UP.toString()), + toggleFavorite = new JButton(BatchOperation.FAVORITE.toString()); + final IVTransferTextField ivTransfer = new IVTransferTextField(pt::selectLessThanIv); + final JButton transferIv = new JButton("Select Pokemon < IV"); + final JComboBox pokelang = new JComboBox(LOCALES); + final JComboBox fontSize = new JComboBox<>(SIZES); + final GridBagConstraints gbc = new GridBagConstraints(); + topPanel.add(refreshPkmn, gbc); - refreshPkmn.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - refreshPkmn(); - return null; - } - }.execute()); topPanel.add(renameSelected, gbc); - renameSelected.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - renameSelected(); - return null; - } - }.execute()); topPanel.add(transferSelected, gbc); - transferSelected.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - transferSelected(); - return null; - } - }.execute()); topPanel.add(evolveSelected, gbc); - evolveSelected.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - evolveSelected(); - return null; - } - }.execute()); topPanel.add(powerUpSelected, gbc); - powerUpSelected.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - powerUpSelected(); - return null; - } - }.execute()); topPanel.add(toggleFavorite, gbc); - toggleFavorite.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - toggleFavorite(); - return null; - } - }.execute()); - - ivTransfer.addKeyListener( - new KeyListener() { - @Override - public void keyPressed(final KeyEvent event) { - if (event.getKeyCode() == KeyEvent.VK_ENTER) { - new SwingWorker() { - @Override - protected Void doInBackground() { - selectLessThanIv(); - return null; - } - }.execute(); - } - } - - @Override - public void keyTyped(final KeyEvent event) { - // nothing here - } - - @Override - public void keyReleased(final KeyEvent event) { - // nothing here - } - }); - topPanel.add(ivTransfer, gbc); - - new GhostText(ivTransfer, "Pokemon IV"); - final JButton transferIv = new JButton("Select Pokemon < IV"); - transferIv.addActionListener(l -> new SwingWorker() { - @Override - protected Void doInBackground() { - selectLessThanIv(); - return null; - } - }.execute()); topPanel.add(transferIv, gbc); - + gbc.weightx = 1.0; gbc.weighty = 1.0; - gbc.gridwidth = 3; + gbc.gridwidth = GRID_WIDTH; gbc.fill = GridBagConstraints.HORIZONTAL; topPanel.add(searchBar, gbc); - - // Pokemon name language drop down - final String[] locales = {"en", "de", "fr", "ru", "zh_CN", "zh_HK", "ja"}; - final JComboBox pokelang = new JComboBox<>(locales); - pokelang.setSelectedItem(config.getString(ConfigKey.LANGUAGE)); - pokelang.addActionListener(e -> new SwingWorker() { - @Override - protected Void doInBackground() { - final String lang = (String) pokelang.getSelectedItem(); - changeLanguage(lang); - return null; - } - }.execute()); + topPanel.add(pokelang); - - // Set font size if specified in config - final Font font = pt.getFont(); - final int size = Math.max(MIN_FONT_SIZE, config.getInt(ConfigKey.FONT_SIZE, font.getSize())); - if (size != font.getSize()) { - pt.setFont(font.deriveFont((float) size)); - } - - // Font size dropdown - final String[] sizes = {"8", "10", "11", "12", "14", "16", "18"}; - final JComboBox fontSize = new JComboBox<>(sizes); - fontSize.setSelectedItem(String.valueOf(size)); - fontSize.addActionListener(e -> new SwingWorker() { - @Override - protected Void doInBackground() { - final String size = fontSize.getSelectedItem().toString(); - pt.setFont(pt.getFont().deriveFont(Float.parseFloat(size))); - config.setInt(ConfigKey.FONT_SIZE, Integer.parseInt(size)); - return null; - } - }.execute()); topPanel.add(fontSize); - LDocumentListener.addChangeListener(searchBar, e -> { - String search = searchBar.getText().replaceAll(StringLiterals.SPACE, "").replaceAll(StringLiterals.UNDERSCORE, "").replaceAll("snek", "ekans") - .toLowerCase(); - if ("searchpokémon...".equals(search)) { - search = ""; - } - pt.filterTable(search); - }); - new GhostText(searchBar, "Search Pokémon..."); - add(topPanel, BorderLayout.NORTH); final JScrollPane sp = new JScrollPane(pt); sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sp, BorderLayout.CENTER); - pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); + refreshPkmn.addActionListener(l -> new OperationWorker(this::refreshPkmn).execute()); + renameSelected.addActionListener(l -> new OperationWorker(this::renameSelected).execute()); + transferSelected.addActionListener(l -> new OperationWorker(this::transferSelected).execute()); + evolveSelected.addActionListener(l -> new OperationWorker(this::evolveSelected).execute()); + powerUpSelected.addActionListener(l -> new OperationWorker(this::powerUpSelected).execute()); + toggleFavorite.addActionListener(l -> new OperationWorker(this::toggleFavorite).execute()); + transferIv.addActionListener(l -> new OperationWorker(pt::selectLessThanIv, ivTransfer.getText()).execute()); + + pokelang.setSelectedItem(config.getString(ConfigKey.LANGUAGE)); + pokelang.addActionListener(e -> new OperationWorker(this::changeLanguage, (String) pokelang.getSelectedItem()).execute()); + + fontSize.setSelectedItem(String.valueOf(pt.getFont().getSize())); + fontSize.addActionListener(e -> new OperationWorker(() -> { + final String innerSize = fontSize.getSelectedItem().toString(); + pt.setFont(pt.getFont().deriveFont(Float.parseFloat(innerSize))); + config.setInt(ConfigKey.FONT_SIZE, Integer.parseInt(innerSize)); + }).execute()); } - + private void changeLanguage(final String langCode) { config.setString(ConfigKey.LANGUAGE, langCode); @@ -323,13 +229,18 @@ private void showFinishedText(final String message, final int size, final Mutabl } private void renameSelected() { - final ArrayList selection = getSelectedPokemon(); + final ArrayList selection = pt.getSelectedPokemon(); if (selection.isEmpty()) { return; } final PokeHandler handler = new PokeHandler(selection); - final String renamePattern = inputOperation(BatchOperation.RENAME, selection); + final String renamePattern = (String) JOptionPane.showInputDialog(null, buildPanelForRename(), + "Renaming " + selection.size() + " Pokémon.", JOptionPane.PLAIN_MESSAGE, null, null, + config.getString(ConfigKey.RENAME_PATTERN)); + if (renamePattern != null) { + config.setString(ConfigKey.RENAME_PATTERN, renamePattern); + } final MutableInt err = new MutableInt(), skipped = new MutableInt(), @@ -399,7 +310,7 @@ private void renameSelected() { } private void transferSelected() { - final ArrayList selection = getSelectedPokemon(); + final ArrayList selection = pt.getSelectedPokemon(); final ArrayList finalSelection = new ArrayList(); if (selection.isEmpty()) { return; @@ -470,7 +381,7 @@ private void transferSelected() { } private void evolveSelected() { - final ArrayList selection = getSelectedPokemon(); + final ArrayList selection = pt.getSelectedPokemon(); if (selection.isEmpty()) { return; } @@ -556,8 +467,8 @@ private void evolveSelected() { + "CP: %d[+%d], " + "HP: %d[+%d])", newCandies, candies, candiesToEvolve, candyRefund, - newCp, (newCp - cp), - newHp, (newHp - hp))); + newCp, newCp - cp, + newHp, newHp - hp)); } else { // Sleep before transferring final int sleepMin = config.getInt(ConfigKey.DELAY_EVOLVE_MIN); @@ -590,8 +501,8 @@ private void evolveSelected() { + "CP: %d[+%d], " + "HP: %d[+%d])", newCandies, candies, candiesToEvolve, candyRefund, - newCp, (newCp - cp), - newHp, (newHp - hp))); + newCp, newCp - cp, + newHp, newHp - hp)); } success.increment(); } else { @@ -604,8 +515,8 @@ private void evolveSelected() { // If not last element, sleep until the next one if (!selection.get(selection.size() - 1).equals(poke)) { - int sleepMin; - int sleepMax; + final int sleepMin; + final int sleepMax; if (afterTransfer) { sleepMin = config.getInt(ConfigKey.DELAY_TRANSFER_MIN); sleepMax = config.getInt(ConfigKey.DELAY_TRANSFER_MAX); @@ -637,7 +548,7 @@ private void evolveSelected() { } private void powerUpSelected() { - final ArrayList selection = getSelectedPokemon(); + final ArrayList selection = pt.getSelectedPokemon(); if (selection.isEmpty()) { return; } @@ -755,7 +666,7 @@ private void powerUpSelected() { // feature added by Ben Kauffman private void toggleFavorite() { - final ArrayList selection = getSelectedPokemon(); + final ArrayList selection = pt.getSelectedPokemon(); if (selection.isEmpty()) { return; } @@ -822,64 +733,6 @@ private void toggleFavorite() { err); } - private void selectLessThanIv() { - if (!NumberUtils.isNumber(ivTransfer.getText())) { - System.out.println("Please select a valid IV value (0-100)"); - return; - } - - final double ivLessThan = Double.parseDouble(ivTransfer.getText()); - if (ivLessThan > 100 || ivLessThan < 0) { - System.out.println("Please select a valid IV value (0-100)"); - return; - } - pt.clearSelection(); - System.out.println("Selecting Pokemon with IV less than: " + ivTransfer.getText()); - - for (int i = 0; i < pt.getRowCount(); i++) { - final double pIv = (double) pt.getValueAt(i, PokeColumn.IV_RATING.id) * 100; - //final double pIv = Double.parseDouble((String) pt.getValueAt(i, 3)); - if (pIv < ivLessThan) { - pt.getSelectionModel().addSelectionInterval(i, i); - } - } - } - - /** - * Handles.. idk why we have this. @author Cryptic - * - * @param operation operation to be done - * @param pokes list of pokemons - * @return rename pattern - */ - private String inputOperation(final BatchOperation operation, final ArrayList pokes) { - JPanel panel; - String message = ""; - String savedPattern = ""; - - switch (operation) { - case RENAME: - panel = buildPanelForRename(); - savedPattern = config.getString(ConfigKey.RENAME_PATTERN); - message = "Renaming " + pokes.size() + " Pokémon."; - break; - default: - panel = buildPanelForOperation(operation, pokes); - break; - } - - final String input = (String) JOptionPane.showInputDialog(null, panel, message, JOptionPane.PLAIN_MESSAGE, null, null, savedPattern); - if (input != null) { - switch (operation) { - case RENAME: - config.setString(ConfigKey.RENAME_PATTERN, input); - default: - break; - } - } - return input; - } - /** * Prompt for confirmation before doing the operation. * @@ -924,7 +777,8 @@ private JPanel buildPanelForOperation(final BatchOperation operation, final Arra // We take 20 px for each row, 5 px buffer, and cap that at may 400 // pixel. final int height = Math.min(400, pokes.size() * 20 + 5); - panel.setPreferredSize(new Dimension(500, height)); + final int width = 500; + panel.setPreferredSize(new Dimension(width, height)); pokes.forEach(p -> { String str = String.format("%s - CP: %d, IV: %s%%", @@ -994,8 +848,7 @@ private JPanel buildPanelForRename() { @Override public void mouseClicked(final MouseEvent mouseEvent) { @SuppressWarnings("unchecked") - final - JList theList = ((JList) mouseEvent.getSource()); + final JList theList = (JList) mouseEvent.getSource(); final boolean isDoubleClick = mouseEvent.getClickCount() == 2; if (isDoubleClick) { final int index = theList.locationToIndex(mouseEvent.getPoint()); @@ -1012,18 +865,6 @@ public void mouseClicked(final MouseEvent mouseEvent) { panel.add(scroll); return panel; } - - public ArrayList getSelectedPokemon() { - final ArrayList pokes = new ArrayList<>(); - final PokemonTableModel model = (PokemonTableModel) pt.getModel(); - for (final int i : pt.getSelectedRows()) { - final Pokemon poke = model.getPokemonByIndex(i); - if (poke != null) { - pokes.add(poke); - } - } - return pokes; - } /** * Helper method to remove the pokemon from the selectedRowsList. @@ -1041,7 +882,7 @@ public void refreshList() { try { pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); if (selectedRowsList != null) { - for (Integer index : selectedRowsList) { + for (final Integer index : selectedRowsList) { pt.addRowSelectionInterval(index, index); } } @@ -1061,7 +902,11 @@ public List getColumnErrors() { public void saveColumnOrder() { pt.saveColumnOrderToConfig(); } - + + public PokemonTable getPokemonTable() { + return pt; + } + /** * Provide custom formatting for the list of patterns. */ From 39d230dfb3485f243db99d4896c6b30d41f5bf53 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 3 Mar 2017 08:47:20 -0300 Subject: [PATCH 10/41] Updating PokeGOAPI-Java, reworking updateInventories again and update hash endpoint to the last one --- pom.xml | 6 +-- .../pokegoutil/utils/helpers/LoginHelper.java | 2 +- .../corriekay/pokegoutil/windows/MenuBar.java | 1 - .../pokegoutil/windows/PokemonTab.java | 44 ++++++++----------- 4 files changed, 22 insertions(+), 31 deletions(-) diff --git a/pom.xml b/pom.xml index 3b2a84aa..c6093f1e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 BPGM BPGM - 0.1.7-hotfix2 + 0.1.7-hotfix3 src test @@ -102,9 +102,9 @@ - com.github.FernandoTBarros + com.github.gegy1000 PokeGOAPI-Java - 84df3ebb045807f7645623268937bf3b9c9b27ff + 3846939d2870e37186b8d4cb9b9fec7912cc445f org.json diff --git a/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java b/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java index 60e797fd..0ae01d96 100644 --- a/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java +++ b/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java @@ -60,7 +60,7 @@ public void onChallenge(final PokemonGo api, final String challengeURL) { try { if (pokeHashKey != null) { final PokeHashProvider pokeHashProvider = new PokeHashProvider(PokeHashKey.from(pokeHashKey), true); - pokeHashProvider.setEndpoint("http://pokehash.buddyauth.com/api/v127_2/hash"); + pokeHashProvider.setEndpoint("http://pokehash.buddyauth.com/api/v127_3/hash"); go.login(credentialProvider, pokeHashProvider); } else { go.login(credentialProvider, new LegacyHashProvider()); diff --git a/src/me/corriekay/pokegoutil/windows/MenuBar.java b/src/me/corriekay/pokegoutil/windows/MenuBar.java index 07075b21..c5152587 100644 --- a/src/me/corriekay/pokegoutil/windows/MenuBar.java +++ b/src/me/corriekay/pokegoutil/windows/MenuBar.java @@ -152,7 +152,6 @@ private void logout() throws Exception { } private void displayTrainerStats() throws Exception { - go.getInventories().updateInventories(); PlayerProfile pp = go.getPlayerProfile(); Stats stats = pp.getStats(); Object[] tstats = { diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index a2ecd699..df2c0a22 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -43,6 +43,7 @@ import com.pokegoapi.exceptions.hash.HashException; import POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId; +import POGOProtos.Networking.Responses.GetInventoryResponseOuterClass.GetInventoryResponse; import POGOProtos.Networking.Responses.NicknamePokemonResponseOuterClass.NicknamePokemonResponse; import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse; import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse; @@ -54,6 +55,7 @@ import me.corriekay.pokegoutil.utils.Utilities; import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; import me.corriekay.pokegoutil.utils.helpers.LocationHelper; +import me.corriekay.pokegoutil.utils.logging.ConsolePrintStream; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler.ReplacePattern; import me.corriekay.pokegoutil.utils.pokemon.PokeNick; @@ -203,13 +205,18 @@ private void changeLanguage(final String langCode) { refreshPkmn(); } + /** + * Try to obtain the updated list of Pokemons from server. + */ private void refreshPkmn() { try { - go.getInventories().updateInventories(true); - PokemonGoMainWindow.getInstance().refreshTitle(); - } catch (final Exception e) { - e.printStackTrace(); + final GetInventoryResponse updateInventories = go.getInventories().updateInventories(true); + go.getInventories().updateInventories(updateInventories); + } catch (LoginFailedException | CaptchaActiveException | RemoteServerException | HashException e) { + System.out.println("Error obtaining updated list from server"); + ConsolePrintStream.printException(e); } + PokemonGoMainWindow.getInstance().refreshTitle(); SwingUtilities.invokeLater(this::refreshList); System.out.println("Done refreshing Pokémon list"); } @@ -300,11 +307,6 @@ private void renameSelected() { handler.bulkRenameWithPattern(renamePattern, perPokeCallback); - try { - go.getInventories().updateInventories(true); - } catch (final Exception e) { - e.printStackTrace(); - } SwingUtilities.invokeLater(this::refreshList); showFinishedText("Pokémon batch rename complete!", selection.size(), success, skipped, err); } @@ -353,7 +355,6 @@ private void transferSelected() { skipped.increment(); return; } - removeSelection(poke); finalSelection.add(poke); }); @@ -376,6 +377,7 @@ private void transferSelected() { Utilities.getRealExceptionMessage(e))); } } + selectedRowsList = null; SwingUtilities.invokeLater(this::refreshList); showFinishedText("Pokémon multi-transfer complete!", total.intValue(), success, skipped, err); } @@ -534,12 +536,7 @@ private void evolveSelected() { Utilities.getRealExceptionMessage(e))); } }); - - try { - go.getInventories().updateInventories(); - } catch (final Exception e) { - e.printStackTrace(); - } + PokemonGoMainWindow.getInstance().refreshTitle(); SwingUtilities.invokeLater(this::refreshList); showFinishedText(String.format( "Pokémon batch evolve%s complete!", @@ -653,12 +650,7 @@ private void powerUpSelected() { Utilities.getRealExceptionMessage(e))); } }); - try { - go.getInventories().updateInventories(true); - PokemonGoMainWindow.getInstance().refreshTitle(); - } catch (final RemoteServerException | LoginFailedException | CaptchaActiveException | HashException e) { - e.printStackTrace(); - } + PokemonGoMainWindow.getInstance().refreshTitle(); SwingUtilities.invokeLater(this::refreshList); showFinishedText("Pokémon batch powerup complete!", selection.size(), success, skipped, err); @@ -873,20 +865,20 @@ public void mouseClicked(final MouseEvent mouseEvent) { public void removeSelection(final Pokemon p) { final PokemonTableModel model = (PokemonTableModel) pt.getModel(); final int index = model.getIndexByPokemon(p); - if (index > 0) { + if (index > 0 && selectedRowsList!=null) { selectedRowsList.remove(index); } } public void refreshList() { + pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); try { - pt.constructNewTableModel(go.getInventories().getPokebank().getPokemons()); - if (selectedRowsList != null) { + if (selectedRowsList != null) { for (final Integer index : selectedRowsList) { pt.addRowSelectionInterval(index, index); } } - } catch (final Exception e) { + } catch (final IllegalArgumentException e) { e.printStackTrace(); } } From 2e56fdec128808701f19f41a36c3ac891fa3bfd2 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 3 Mar 2017 09:01:18 -0300 Subject: [PATCH 11/41] Fixing codeclimate issue --- src/me/corriekay/pokegoutil/windows/PokemonTab.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index df2c0a22..44b8b4ab 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -865,7 +865,7 @@ public void mouseClicked(final MouseEvent mouseEvent) { public void removeSelection(final Pokemon p) { final PokemonTableModel model = (PokemonTableModel) pt.getModel(); final int index = model.getIndexByPokemon(p); - if (index > 0 && selectedRowsList!=null) { + if (index > 0 && selectedRowsList != null) { selectedRowsList.remove(index); } } From 32096c725bcabac8b6d00293fb53118b2ab49293 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Fri, 10 Mar 2017 10:47:48 -0300 Subject: [PATCH 12/41] Updating stuffs again Updating PokeGOAPI for updating Hash Key login to the last version Including two new buttons for favorite yes or no --- pom.xml | 4 +- src/main/resources/version.txt | 2 +- .../pokegoutil/data/enums/BatchOperation.java | 4 +- .../data/managers/AccountController.java | 15 +-- .../data/managers/AccountManager.java | 21 ++--- .../data/managers/InventoryManager.java | 8 +- .../pokegoutil/data/models/PlayerAccount.java | 5 +- .../models/operations/EvolveOperation.java | 17 +--- .../data/models/operations/Operation.java | 8 +- .../models/operations/PowerupOperation.java | 4 +- .../models/operations/RenameOperation.java | 4 +- .../models/operations/TransferOperation.java | 17 +--- .../gui/controller/MainWindowController.java | 91 +++++++++---------- .../OperationConfirmationController.java | 4 +- .../pokegoutil/utils/SolveCaptcha.java | 8 +- .../pokegoutil/utils/helpers/LoginHelper.java | 27 ++---- .../pokegoutil/utils/helpers/TriConsumer.java | 19 ++++ .../pokegoutil/utils/pokemon/PokeHandler.java | 24 +++-- .../pokegoutil/windows/OperationWorker.java | 21 +++-- .../pokegoutil/windows/PokemonTab.java | 74 ++++++++------- .../operations/EvolveOperationTest.java | 12 +-- .../operations/TransferOperationTest.java | 9 +- 22 files changed, 180 insertions(+), 218 deletions(-) create mode 100644 src/me/corriekay/pokegoutil/utils/helpers/TriConsumer.java diff --git a/pom.xml b/pom.xml index c6093f1e..7171c0bd 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 BPGM BPGM - 0.1.7-hotfix3 + 0.1.7-hotfix4 src test @@ -104,7 +104,7 @@ com.github.gegy1000 PokeGOAPI-Java - 3846939d2870e37186b8d4cb9b9fec7912cc445f + 199cda2914ba0ac037d5e3690dee9021b32f37af org.json diff --git a/src/main/resources/version.txt b/src/main/resources/version.txt index 54f8b6e0..7a17aee9 100644 --- a/src/main/resources/version.txt +++ b/src/main/resources/version.txt @@ -1 +1 @@ -v0.1.8-develop +v0.1.7-hotfix4 diff --git a/src/me/corriekay/pokegoutil/data/enums/BatchOperation.java b/src/me/corriekay/pokegoutil/data/enums/BatchOperation.java index 569b0970..e0c48ffe 100644 --- a/src/me/corriekay/pokegoutil/data/enums/BatchOperation.java +++ b/src/me/corriekay/pokegoutil/data/enums/BatchOperation.java @@ -8,7 +8,9 @@ public enum BatchOperation { EVOLVE("Evolve"), POWER_UP("Power-Up"), TRANSFER("Transfer"), - FAVORITE("Toggle Favorite"); + FAVORITE("Toggle Favorite"), + SET_FAVORITE_YES("Set Favorite Yes"), + SET_FAVORITE_NO("Set Favorite No"); private final String friendlyName; diff --git a/src/me/corriekay/pokegoutil/data/managers/AccountController.java b/src/me/corriekay/pokegoutil/data/managers/AccountController.java index b642a194..984786ff 100644 --- a/src/me/corriekay/pokegoutil/data/managers/AccountController.java +++ b/src/me/corriekay/pokegoutil/data/managers/AccountController.java @@ -6,7 +6,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.concurrent.ExecutionException; import javax.swing.JLabel; import javax.swing.JOptionPane; @@ -21,10 +20,7 @@ import com.pokegoapi.auth.GoogleAutoCredentialProvider; import com.pokegoapi.auth.GoogleUserCredentialProvider; import com.pokegoapi.auth.PtcCredentialProvider; -import com.pokegoapi.exceptions.AsyncPokemonGoException; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import me.corriekay.pokegoutil.data.enums.LoginType; import me.corriekay.pokegoutil.utils.ConfigKey; @@ -345,14 +341,9 @@ public static void logOn() { } else { throw new IllegalStateException("credentialProvider is null."); } - } catch (LoginFailedException | AsyncPokemonGoException | IllegalStateException | CaptchaActiveException | HashException e) { - if (e instanceof AsyncPokemonGoException && e.getCause() instanceof RuntimeException && e.getCause().getCause() instanceof ExecutionException && e.getCause().getCause().getCause() instanceof HashException) { - alertFailedLogin(e.getCause().getCause().getCause().getClass().getSimpleName(), e.getCause().getCause().getCause().getMessage(), tries); - } else { - alertFailedLogin(e.getClass().getSimpleName(), e.getMessage(), tries); - } + } catch (RequestFailedException e) { + alertFailedLogin(e.getClass().getSimpleName(), e.getMessage(), tries); e.printStackTrace(); - // deleteLoginData(LoginType.ALL); } } } diff --git a/src/me/corriekay/pokegoutil/data/managers/AccountManager.java b/src/me/corriekay/pokegoutil/data/managers/AccountManager.java index 79734b23..096132c0 100644 --- a/src/me/corriekay/pokegoutil/data/managers/AccountManager.java +++ b/src/me/corriekay/pokegoutil/data/managers/AccountManager.java @@ -5,10 +5,8 @@ import com.pokegoapi.auth.CredentialProvider; import com.pokegoapi.auth.GoogleUserCredentialProvider; import com.pokegoapi.auth.PtcCredentialProvider; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.LoginFailedException; +import com.pokegoapi.exceptions.request.RequestFailedException; import me.corriekay.pokegoutil.data.enums.LoginType; import me.corriekay.pokegoutil.data.models.BpmResult; @@ -180,7 +178,7 @@ private BpmResult logOnGoogleAuth(final LoginData loginData) { } else if (!saveAuth) { deleteLoginData(LoginType.GOOGLE_AUTH); } - } catch (LoginFailedException | RemoteServerException | CaptchaActiveException e) { + } catch (RequestFailedException e) { deleteLoginData(LoginType.GOOGLE_APP_PASSWORD); return new BpmResult(e.getMessage()); } @@ -188,7 +186,7 @@ private BpmResult logOnGoogleAuth(final LoginData loginData) { try { prepareLogin(cp, http); return new BpmResult(); - } catch (LoginFailedException | RemoteServerException | CaptchaActiveException | HashException e) { + } catch (RequestFailedException e) { deleteLoginData(LoginType.ALL); return new BpmResult(e.getMessage()); } @@ -217,7 +215,7 @@ private BpmResult logOnPtc(final LoginData loginData) { } else { deleteLoginData(LoginType.PTC); } - } catch (LoginFailedException | RemoteServerException | CaptchaActiveException e) { + } catch (RequestFailedException e) { deleteLoginData(LoginType.PTC); return new BpmResult(e.getMessage()); } @@ -225,7 +223,7 @@ private BpmResult logOnPtc(final LoginData loginData) { try { prepareLogin(cp, http); return new BpmResult(); - } catch (LoginFailedException | RemoteServerException | CaptchaActiveException | HashException e) { + } catch (RequestFailedException e) { deleteLoginData(LoginType.ALL); return new BpmResult(e.getMessage()); } @@ -236,13 +234,10 @@ private BpmResult logOnPtc(final LoginData loginData) { * * @param cp contains the credential provider * @param http http client - * @throws LoginFailedException login failed - * @throws RemoteServerException server error - * @throws CaptchaActiveException captcha active error - * @throws HashException + * @throws RequestFailedException request failed */ private void prepareLogin(final CredentialProvider cp, final OkHttpClient http) - throws LoginFailedException, RemoteServerException, CaptchaActiveException, HashException { + throws RequestFailedException { go = new PokemonGo(http); LoginHelper.login(go, cp, api -> { playerAccount = new PlayerAccount(go.getPlayerProfile()); diff --git a/src/me/corriekay/pokegoutil/data/managers/InventoryManager.java b/src/me/corriekay/pokegoutil/data/managers/InventoryManager.java index f9487714..28422df1 100644 --- a/src/me/corriekay/pokegoutil/data/managers/InventoryManager.java +++ b/src/me/corriekay/pokegoutil/data/managers/InventoryManager.java @@ -2,11 +2,9 @@ import com.pokegoapi.api.PokemonGo; import com.pokegoapi.api.inventory.Inventories; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -/* - * This controller takes care of interactions with the inventory items +/** + * This controller takes care of interactions with the inventory items. */ public final class InventoryManager { @@ -33,7 +31,7 @@ public static void initialize(PokemonGo go) { sIsInit = true; } - public static Inventories getInventories() throws LoginFailedException, RemoteServerException { + public static Inventories getInventories() { return sIsInit ? S_INSTANCE.inventories : null; } } diff --git a/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java b/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java index b0009361..ee77bf51 100644 --- a/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java +++ b/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java @@ -3,8 +3,7 @@ import com.pokegoapi.api.player.PlayerProfile; import com.pokegoapi.api.player.PlayerProfile.Currency; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; +import com.pokegoapi.exceptions.request.LoginFailedException; public class PlayerAccount { @@ -27,7 +26,7 @@ public PlayerAccount(final PlayerProfile playerProfile) { * @throws LoginFailedException login failed * @throws RemoteServerException server error */ - public int getStardust() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public int getStardust() throws InvalidCurrencyException { return playerProfile.getCurrency(Currency.STARDUST); } } diff --git a/src/me/corriekay/pokegoutil/data/models/operations/EvolveOperation.java b/src/me/corriekay/pokegoutil/data/models/operations/EvolveOperation.java index 504e9077..504a2a27 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/EvolveOperation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/EvolveOperation.java @@ -2,10 +2,7 @@ import com.pokegoapi.api.map.pokemon.EvolutionResult; import com.pokegoapi.api.pokemon.Pokemon; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.models.BpmOperationResult; @@ -34,24 +31,18 @@ public EvolveOperation(final PokemonModel pokemon) { } @Override - protected BpmOperationResult doOperation() throws LoginFailedException, RemoteServerException { + protected BpmOperationResult doOperation() { final EvolutionResult evolutionResult; final String erroEvolvingString = "Error evolving %s, result: %s"; try { evolutionResult = pokemon.getPokemon().evolve(); - } catch (CaptchaActiveException e) { + } catch (RequestFailedException e) { e.printStackTrace(); return new BpmOperationResult(String.format( erroEvolvingString, pokemon.getSpecies(), - "Captcha active in account"), - OperationError.EVOLVE_FAIL); - } catch (HashException e) { - return new BpmOperationResult(String.format( - erroEvolvingString, - pokemon.getSpecies(), - "Error with Hash: " + e.getMessage()), + e.getMessage()), OperationError.EVOLVE_FAIL); } diff --git a/src/me/corriekay/pokegoutil/data/models/operations/Operation.java b/src/me/corriekay/pokegoutil/data/models/operations/Operation.java index 0a72ca70..a9f21aff 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/Operation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/Operation.java @@ -4,8 +4,6 @@ import java.util.List; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; import javafx.collections.ObservableList; import me.corriekay.pokegoutil.data.models.BpmOperationResult; @@ -61,9 +59,9 @@ public Operation(final PokemonModel pokemon) { this.pokemon = pokemon; } - protected abstract BpmOperationResult doOperation() throws LoginFailedException, RemoteServerException; + protected abstract BpmOperationResult doOperation(); - public BpmOperationResult execute() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public BpmOperationResult execute() throws InvalidCurrencyException { BpmOperationResult result = validateOperation(); if (result.isSuccess()) { @@ -98,5 +96,5 @@ public String toString() { } public abstract BpmOperationResult validateOperation() - throws InvalidCurrencyException, LoginFailedException, RemoteServerException; + throws InvalidCurrencyException; } diff --git a/src/me/corriekay/pokegoutil/data/models/operations/PowerupOperation.java b/src/me/corriekay/pokegoutil/data/models/operations/PowerupOperation.java index 0b533917..d5234bd4 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/PowerupOperation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/PowerupOperation.java @@ -1,8 +1,6 @@ package me.corriekay.pokegoutil.data.models.operations; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.managers.AccountManager; @@ -52,7 +50,7 @@ public OperationId getOperationId() { @Override public BpmOperationResult validateOperation() - throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + throws InvalidCurrencyException { if (pokemon.isInGym()) { return new BpmOperationResult("Pokemon is in gym", OperationError.IN_GYM); } diff --git a/src/me/corriekay/pokegoutil/data/models/operations/RenameOperation.java b/src/me/corriekay/pokegoutil/data/models/operations/RenameOperation.java index b0165f1a..3cb2fa96 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/RenameOperation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/RenameOperation.java @@ -1,8 +1,6 @@ package me.corriekay.pokegoutil.data.models.operations; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.models.BpmOperationResult; @@ -51,7 +49,7 @@ public OperationId getOperationId() { @Override public BpmOperationResult validateOperation() - throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + throws InvalidCurrencyException { // I think we need to check if in gym? Wasn't checked in previous code. // if (pokemon.isInGym()) { // return new BPMResult("Pokemon is in gym"); diff --git a/src/me/corriekay/pokegoutil/data/models/operations/TransferOperation.java b/src/me/corriekay/pokegoutil/data/models/operations/TransferOperation.java index d115d796..5a52d735 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/TransferOperation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/TransferOperation.java @@ -1,10 +1,7 @@ package me.corriekay.pokegoutil.data.models.operations; import com.pokegoapi.api.pokemon.Pokemon; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse.Result; import me.corriekay.pokegoutil.data.enums.OperationError; @@ -34,7 +31,7 @@ public TransferOperation(final PokemonModel pokemon) { } @Override - protected BpmOperationResult doOperation() throws LoginFailedException, RemoteServerException { + protected BpmOperationResult doOperation() { final Pokemon poke = pokemon.getPokemon(); final int candies = poke.getCandy(); @@ -43,18 +40,12 @@ protected BpmOperationResult doOperation() throws LoginFailedException, RemoteSe final String errorTransferingString = "Error transferring %s, result: %s"; try { transferResult = poke.transferPokemon(); - } catch (CaptchaActiveException e) { + } catch (RequestFailedException e) { e.printStackTrace(); return new BpmOperationResult(String.format( errorTransferingString, PokemonUtils.getLocalPokeName(poke), - "Captcha active in account"), - OperationError.EVOLVE_FAIL); - } catch (HashException e) { - return new BpmOperationResult(String.format( - errorTransferingString, - pokemon.getSpecies(), - "Error with Hash: " + e.getMessage()), + e.getMessage()), OperationError.EVOLVE_FAIL); } diff --git a/src/me/corriekay/pokegoutil/gui/controller/MainWindowController.java b/src/me/corriekay/pokegoutil/gui/controller/MainWindowController.java index d95855b5..4712618e 100644 --- a/src/me/corriekay/pokegoutil/gui/controller/MainWindowController.java +++ b/src/me/corriekay/pokegoutil/gui/controller/MainWindowController.java @@ -4,8 +4,6 @@ import com.pokegoapi.api.inventory.Stats; import com.pokegoapi.api.player.PlayerProfile; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; import POGOProtos.Data.PlayerDataOuterClass.PlayerData; import javafx.event.ActionEvent; @@ -127,56 +125,51 @@ private void refreshGUI(final PlayerProfile pp) { if (pp != null) { while (!done) { done = true; - try { - final PlayerData pd = pp.getPlayerData(); - final Stats stats = pp.getStats(); - - Color color = null; - switch (pd.getTeam().getNumber()) { - case 0 :// noteam - color = Color.rgb(160, 160, 160, 0.99); - break; - case 1 :// blue - color = Color.rgb(0, 0, 255, 0.99); - break; - case 2 :// red - color = Color.rgb(204, 0, 0, 0.99); - break; - case 3 :// yellow - color = Color.rgb(255, 255, 0, 0.99); - break; - } - if (color != null) { - final int width = (int) teamIcon.getFitWidth(); - final int height = (int) teamIcon.getFitHeight(); - final WritableImage dest = new WritableImage(width, height); - final PixelWriter writer = dest.getPixelWriter(); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - writer.setColor(x, y, color); - } + final PlayerData pd = pp.getPlayerData(); + final Stats stats = pp.getStats(); + + Color color = null; + switch (pd.getTeam().getNumber()) { + case 0 :// noteam + color = Color.rgb(160, 160, 160, 0.99); + break; + case 1 :// blue + color = Color.rgb(0, 0, 255, 0.99); + break; + case 2 :// red + color = Color.rgb(204, 0, 0, 0.99); + break; + case 3 :// yellow + color = Color.rgb(255, 255, 0, 0.99); + break; + } + if (color != null) { + final int width = (int) teamIcon.getFitWidth(); + final int height = (int) teamIcon.getFitHeight(); + final WritableImage dest = new WritableImage(width, height); + final PixelWriter writer = dest.getPixelWriter(); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + writer.setColor(x, y, color); } - teamIcon.setImage(dest); } - playerNameLabel.setText(pd.getUsername() + " "); - playerLvl.setText("Lvl: " + Integer.toString(stats.getLevel())); - final NumberFormat f = NumberFormat.getInstance(); - playerStardustLbl.setText(f.format( - pp.getCurrency(PlayerProfile.Currency.STARDUST)) - + " Stardust"); - nbPkmInBagsLbl.setText(Integer.toString(PokemonBagManager.getNbPokemon()) - + SLASH - + Integer.toString(pp.getPlayerData().getMaxPokemonStorage()) - + " Pokémon"); - nbItemsBagsLbl.setText( - Integer.toString(InventoryManager.getInventories().getItemBag().getItemsCount()) - + SLASH - + Integer.toString(pp.getPlayerData().getMaxItemStorage()) - + " Items"); - } catch (LoginFailedException | RemoteServerException e) { - System.out.println("bad stuff happened:" + e.toString()); - done = false; + teamIcon.setImage(dest); } + playerNameLabel.setText(pd.getUsername() + " "); + playerLvl.setText("Lvl: " + Integer.toString(stats.getLevel())); + final NumberFormat f = NumberFormat.getInstance(); + playerStardustLbl.setText(f.format( + pp.getCurrency(PlayerProfile.Currency.STARDUST)) + + " Stardust"); + nbPkmInBagsLbl.setText(Integer.toString(PokemonBagManager.getNbPokemon()) + + SLASH + + Integer.toString(pp.getPlayerData().getMaxPokemonStorage()) + + " Pokémon"); + nbItemsBagsLbl.setText( + Integer.toString(InventoryManager.getInventories().getItemBag().getItemsCount()) + + SLASH + + Integer.toString(pp.getPlayerData().getMaxItemStorage()) + + " Items"); } } } diff --git a/src/me/corriekay/pokegoutil/gui/controller/OperationConfirmationController.java b/src/me/corriekay/pokegoutil/gui/controller/OperationConfirmationController.java index 8cdb62c4..c0f13a2e 100644 --- a/src/me/corriekay/pokegoutil/gui/controller/OperationConfirmationController.java +++ b/src/me/corriekay/pokegoutil/gui/controller/OperationConfirmationController.java @@ -1,8 +1,6 @@ package me.corriekay.pokegoutil.gui.controller; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; import javafx.collections.ObservableList; import javafx.event.ActionEvent; @@ -84,7 +82,7 @@ private void doOperation(final Operation operation){ pokemon.getSummary(), result.getErrorMessage())); } - } catch (InvalidCurrencyException | LoginFailedException | RemoteServerException e) { + } catch (InvalidCurrencyException e) { System.out.println(String.format( "Error %s %s! %s", operation.getOperationId().getActionVerbDuring(), diff --git a/src/me/corriekay/pokegoutil/utils/SolveCaptcha.java b/src/me/corriekay/pokegoutil/utils/SolveCaptcha.java index 18d9c1d2..5564a132 100644 --- a/src/me/corriekay/pokegoutil/utils/SolveCaptcha.java +++ b/src/me/corriekay/pokegoutil/utils/SolveCaptcha.java @@ -21,12 +21,8 @@ import javax.swing.JFrame; import javax.swing.WindowConstants; -import com.google.protobuf.InvalidProtocolBufferException; import com.pokegoapi.api.PokemonGo; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import com.pokegoapi.util.CaptchaSolveHelper; import javafx.application.Platform; @@ -121,7 +117,7 @@ public void onTokenReceived(final String token) { /* Ask for a new challenge url, don't need to check the result, because the LoginListener will be called when this completed. */ api.checkChallenge(); } - } catch (InvalidProtocolBufferException | RemoteServerException | CaptchaActiveException | LoginFailedException | HashException e) { + } catch (RequestFailedException e) { e.printStackTrace(); } } diff --git a/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java b/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java index 0ae01d96..d8d8f14e 100644 --- a/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java +++ b/src/me/corriekay/pokegoutil/utils/helpers/LoginHelper.java @@ -6,10 +6,7 @@ import com.pokegoapi.api.device.DeviceInfo; import com.pokegoapi.api.listener.LoginListener; import com.pokegoapi.auth.CredentialProvider; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import com.pokegoapi.util.hash.legacy.LegacyHashProvider; import com.pokegoapi.util.hash.pokehash.PokeHashKey; import com.pokegoapi.util.hash.pokehash.PokeHashProvider; @@ -33,12 +30,10 @@ private LoginHelper() { * @param go PokemonGo api * @param credentialProvider CredentialProvider (Google or PTC) * @param loginFunction Consumer function that will receive API after successful login - * @throws LoginFailedException if Login fail - * @throws CaptchaActiveException if a Captcha is active - * @throws HashException + * @throws RequestFailedException if an error happens */ public static void login(final PokemonGo go, final CredentialProvider credentialProvider, final Consumer loginFunction) - throws LoginFailedException, CaptchaActiveException, HashException { + throws RequestFailedException { //Add listener to listen for the captcha URL go.addListener(new LoginListener() { @Override @@ -57,16 +52,12 @@ public void onChallenge(final PokemonGo api, final String challengeURL) { go.setDeviceInfo(new DeviceInfo(new CustomDeviceInfo())); } final String pokeHashKey = ConfigNew.getConfig().getString(ConfigKey.LOGIN_POKEHASHKEY); - try { - if (pokeHashKey != null) { - final PokeHashProvider pokeHashProvider = new PokeHashProvider(PokeHashKey.from(pokeHashKey), true); - pokeHashProvider.setEndpoint("http://pokehash.buddyauth.com/api/v127_3/hash"); - go.login(credentialProvider, pokeHashProvider); - } else { - go.login(credentialProvider, new LegacyHashProvider()); - } - } catch (RemoteServerException e) { - e.printStackTrace(); + if (pokeHashKey != null) { + final PokeHashProvider pokeHashProvider = new PokeHashProvider(PokeHashKey.from(pokeHashKey), true); + pokeHashProvider.setEndpoint("http://pokehash.buddyauth.com/api/v127_4/hash"); + go.login(credentialProvider, pokeHashProvider); + } else { + go.login(credentialProvider, new LegacyHashProvider()); } } } diff --git a/src/me/corriekay/pokegoutil/utils/helpers/TriConsumer.java b/src/me/corriekay/pokegoutil/utils/helpers/TriConsumer.java new file mode 100644 index 00000000..01aea58d --- /dev/null +++ b/src/me/corriekay/pokegoutil/utils/helpers/TriConsumer.java @@ -0,0 +1,19 @@ +package me.corriekay.pokegoutil.utils.helpers; + +/** + * FunctionalInterface for implementing a TriConsumer like BiConsumer. + * @param first argument type + * @param second argument type + * @param third argument type + */ +@FunctionalInterface +public interface TriConsumer { + + /** + * Applies this function to the given arguments. + * @param first the first function argument + * @param second the second function argument + * @param third the third function argument + */ + void accept(T first, U second, S third); +} diff --git a/src/me/corriekay/pokegoutil/utils/pokemon/PokeHandler.java b/src/me/corriekay/pokegoutil/utils/pokemon/PokeHandler.java index 1bdddc2e..53bfe2ae 100644 --- a/src/me/corriekay/pokegoutil/utils/pokemon/PokeHandler.java +++ b/src/me/corriekay/pokegoutil/utils/pokemon/PokeHandler.java @@ -4,20 +4,18 @@ import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; -import java.util.function.BiConsumer; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.pokegoapi.api.pokemon.Pokemon; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import com.pokegoapi.main.PokemonMeta; import POGOProtos.Networking.Responses.NicknamePokemonResponseOuterClass.NicknamePokemonResponse; import me.corriekay.pokegoutil.data.enums.PokeColumn; import me.corriekay.pokegoutil.utils.Utilities; +import me.corriekay.pokegoutil.utils.helpers.TriConsumer; import me.corriekay.pokegoutil.utils.helpers.UnicodeHelper; public class PokeHandler { @@ -62,7 +60,7 @@ public static NicknamePokemonResponse.Result renameWithPattern(final String patt try { final NicknamePokemonResponse.Result result = pokemon.renamePokemon(pokeNick.toString()); return result; - } catch (LoginFailedException | RemoteServerException | CaptchaActiveException | HashException e) { + } catch (RequestFailedException e) { System.out.println("Error while renaming " + PokemonUtils.getLocalPokeName(pokemon) + "(" + pokemon.getNickname() + ")! " + Utilities.getRealExceptionMessage(e)); @@ -73,22 +71,22 @@ public static NicknamePokemonResponse.Result renameWithPattern(final String patt // endregion /** - * Rename a bunch of Pokemon based on a pattern + * Rename a bunch of Pokemon based on a pattern. * * @param pattern The pattern to use for renaming * @param perPokeCallback Will be called for each Pokémon that has been (tried) to * rename. - * @return A LinkedHashMap with each Pokémon as key and the result as - * value. + * @return A LinkedHashMap with each Pokémon as key and the result as value. */ - public LinkedHashMap bulkRenameWithPattern(final String pattern, - final BiConsumer perPokeCallback) { - final LinkedHashMap results = new LinkedHashMap<>(); + public Map bulkRenameWithPattern(final String pattern, + final TriConsumer perPokeCallback) { + final Map results = new LinkedHashMap<>(); mons.forEach(p -> { + final String previousNickname = p.getNickname(); final NicknamePokemonResponse.Result result = renameWithPattern(pattern, p); if (perPokeCallback != null) { - perPokeCallback.accept(result, p); + perPokeCallback.accept(result, p, previousNickname); } results.put(p, result); }); diff --git a/src/me/corriekay/pokegoutil/windows/OperationWorker.java b/src/me/corriekay/pokegoutil/windows/OperationWorker.java index b10378f8..f836ed80 100644 --- a/src/me/corriekay/pokegoutil/windows/OperationWorker.java +++ b/src/me/corriekay/pokegoutil/windows/OperationWorker.java @@ -6,11 +6,12 @@ /** * Worker class to call the functions of each operation in a generic way. + * @param if a consumer this is the type */ -public final class OperationWorker extends SwingWorker { +public final class OperationWorker extends SwingWorker { private Runnable function; - private Consumer stringConsumer; - private String consumable; + private Consumer consumer; + private T consumable; /** * Constructor that receives a function that has none arguments and just call it. @@ -21,12 +22,12 @@ public OperationWorker(final Runnable function) { } /** - * Constructor that receives a function that expect to receive one String and call it. - * @param action function that will be called passin the consumable string to it. - * @param consumable string that will be passed to action function. + * Constructor that receives a function that expect to receive one Object and call it. + * @param action function that will be called passin the consumable Object to it. + * @param consumable Object that will be passed to action function. */ - public OperationWorker(final Consumer action, final String consumable) { - this.stringConsumer = action; + public OperationWorker(final Consumer action, final T consumable) { + this.consumer = action; this.consumable = consumable; } @@ -34,8 +35,8 @@ public OperationWorker(final Consumer action, final String consumable) { protected Void doInBackground() { if (function != null) { function.run(); - } else if (stringConsumer != null) { - stringConsumer.accept(consumable); + } else if (consumer != null) { + consumer.accept(consumable); } return null; } diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index 44b8b4ab..4a387e14 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -15,7 +15,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; import java.util.stream.Collectors; import javax.swing.BoxLayout; @@ -37,10 +36,7 @@ import com.pokegoapi.api.map.pokemon.EvolutionResult; import com.pokegoapi.api.player.PlayerProfile.Currency; import com.pokegoapi.api.pokemon.Pokemon; -import com.pokegoapi.exceptions.CaptchaActiveException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; -import com.pokegoapi.exceptions.hash.HashException; +import com.pokegoapi.exceptions.request.RequestFailedException; import POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId; import POGOProtos.Networking.Responses.GetInventoryResponseOuterClass.GetInventoryResponse; @@ -55,6 +51,7 @@ import me.corriekay.pokegoutil.utils.Utilities; import me.corriekay.pokegoutil.utils.helpers.EvolveHelper; import me.corriekay.pokegoutil.utils.helpers.LocationHelper; +import me.corriekay.pokegoutil.utils.helpers.TriConsumer; import me.corriekay.pokegoutil.utils.logging.ConsolePrintStream; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler; import me.corriekay.pokegoutil.utils.pokemon.PokeHandler.ReplacePattern; @@ -136,7 +133,9 @@ private void addAndInitializeComponents() { transferSelected = new JButton(BatchOperation.TRANSFER.toString()), evolveSelected = new JButton(BatchOperation.EVOLVE.toString()), powerUpSelected = new JButton(BatchOperation.POWER_UP.toString()), - toggleFavorite = new JButton(BatchOperation.FAVORITE.toString()); + toggleFavorite = new JButton(BatchOperation.FAVORITE.toString()), + setFavoriteYes = new JButton(BatchOperation.SET_FAVORITE_YES.toString()), + setFavoriteNo = new JButton(BatchOperation.SET_FAVORITE_NO.toString()); final IVTransferTextField ivTransfer = new IVTransferTextField(pt::selectLessThanIv); final JButton transferIv = new JButton("Select Pokemon < IV"); final JComboBox pokelang = new JComboBox(LOCALES); @@ -150,6 +149,8 @@ private void addAndInitializeComponents() { topPanel.add(evolveSelected, gbc); topPanel.add(powerUpSelected, gbc); topPanel.add(toggleFavorite, gbc); + topPanel.add(setFavoriteYes, gbc); + topPanel.add(setFavoriteNo, gbc); topPanel.add(ivTransfer, gbc); topPanel.add(transferIv, gbc); @@ -167,19 +168,21 @@ private void addAndInitializeComponents() { sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sp, BorderLayout.CENTER); - refreshPkmn.addActionListener(l -> new OperationWorker(this::refreshPkmn).execute()); - renameSelected.addActionListener(l -> new OperationWorker(this::renameSelected).execute()); - transferSelected.addActionListener(l -> new OperationWorker(this::transferSelected).execute()); - evolveSelected.addActionListener(l -> new OperationWorker(this::evolveSelected).execute()); - powerUpSelected.addActionListener(l -> new OperationWorker(this::powerUpSelected).execute()); - toggleFavorite.addActionListener(l -> new OperationWorker(this::toggleFavorite).execute()); - transferIv.addActionListener(l -> new OperationWorker(pt::selectLessThanIv, ivTransfer.getText()).execute()); + refreshPkmn.addActionListener(l -> new OperationWorker(this::refreshPkmn).execute()); + renameSelected.addActionListener(l -> new OperationWorker(this::renameSelected).execute()); + transferSelected.addActionListener(l -> new OperationWorker(this::transferSelected).execute()); + evolveSelected.addActionListener(l -> new OperationWorker(this::evolveSelected).execute()); + powerUpSelected.addActionListener(l -> new OperationWorker(this::powerUpSelected).execute()); + toggleFavorite.addActionListener(l -> new OperationWorker(this::toggleFavorite, null).execute()); + setFavoriteYes.addActionListener(l -> new OperationWorker(this::toggleFavorite, BatchOperation.SET_FAVORITE_YES).execute()); + setFavoriteNo.addActionListener(l -> new OperationWorker(this::toggleFavorite, BatchOperation.SET_FAVORITE_NO).execute()); + transferIv.addActionListener(l -> new OperationWorker(pt::selectLessThanIv, ivTransfer.getText()).execute()); pokelang.setSelectedItem(config.getString(ConfigKey.LANGUAGE)); - pokelang.addActionListener(e -> new OperationWorker(this::changeLanguage, (String) pokelang.getSelectedItem()).execute()); + pokelang.addActionListener(e -> new OperationWorker(this::changeLanguage, (String) pokelang.getSelectedItem()).execute()); fontSize.setSelectedItem(String.valueOf(pt.getFont().getSize())); - fontSize.addActionListener(e -> new OperationWorker(() -> { + fontSize.addActionListener(e -> new OperationWorker(() -> { final String innerSize = fontSize.getSelectedItem().toString(); pt.setFont(pt.getFont().deriveFont(Float.parseFloat(innerSize))); config.setInt(ConfigKey.FONT_SIZE, Integer.parseInt(innerSize)); @@ -212,7 +215,7 @@ private void refreshPkmn() { try { final GetInventoryResponse updateInventories = go.getInventories().updateInventories(true); go.getInventories().updateInventories(updateInventories); - } catch (LoginFailedException | CaptchaActiveException | RemoteServerException | HashException e) { + } catch (RequestFailedException e) { System.out.println("Error obtaining updated list from server"); ConsolePrintStream.printException(e); } @@ -254,7 +257,7 @@ private void renameSelected() { success = new MutableInt(), total = new MutableInt(1); - final BiConsumer perPokeCallback = (renameResult, pokemon) -> { + final TriConsumer perPokeCallback = (renameResult, pokemon, previousNickname) -> { System.out.println(String.format( "Doing Rename %d of %d", total.getValue(), @@ -286,14 +289,14 @@ private void renameSelected() { System.out.println(String.format( "Renaming %s from \"%s\" to \"%s\", Result: Success!", PokemonUtils.getLocalPokeName(pokemon), - pokemon.getNickname(), + previousNickname, PokeHandler.generatePokemonNickname(renamePattern, pokemon))); } else { err.increment(); System.out.println(String.format( "Renaming %s failed! Code: %s; Nick: \"%s\"", PokemonUtils.getLocalPokeName(pokemon), - renameResult.toString(), + previousNickname, PokeHandler.generatePokemonNickname(renamePattern, pokemon))); } @@ -370,7 +373,7 @@ private void transferSelected() { candies)); }); success.add(finalSelection.size()); - } catch (CaptchaActiveException | LoginFailedException | RemoteServerException | HashException e) { + } catch (RequestFailedException e) { err.add(finalSelection.size()); System.out.println(String.format( "Error transferring pokemons! %s", @@ -536,6 +539,7 @@ private void evolveSelected() { Utilities.getRealExceptionMessage(e))); } }); + selectedRowsList = null; PokemonGoMainWindow.getInstance().refreshTitle(); SwingUtilities.invokeLater(this::refreshList); showFinishedText(String.format( @@ -657,13 +661,13 @@ private void powerUpSelected() { } // feature added by Ben Kauffman - private void toggleFavorite() { + private void toggleFavorite(final BatchOperation operation) { final ArrayList selection = pt.getSelectedPokemon(); if (selection.isEmpty()) { return; } - if (!confirmOperation(BatchOperation.FAVORITE, selection)) { + if (!confirmOperation(operation, selection)) { return; } @@ -675,23 +679,30 @@ private void toggleFavorite() { selection.forEach(poke -> { try { System.out.println(String.format( - "Toggling favorite %d of %d", + "Setting favorite %d of %d", total.getValue(), selection.size())); total.increment(); + boolean favorite = !poke.isFavorite(); + if (operation != null) { + if (operation.equals(BatchOperation.SET_FAVORITE_YES)) { + favorite = true; + } else { + favorite = false; + } + } final SetFavoritePokemonResponse.Result favoriteResult = poke - .setFavoritePokemon(!poke.isFavorite()); + .setFavoritePokemon(favorite); System.out.println(String.format( "Attempting to set favorite for %s to %b...", PokemonUtils.getLocalPokeName(poke), - !poke.isFavorite())); - go.getPlayerProfile().updateProfile(); + favorite)); if (favoriteResult == SetFavoritePokemonResponse.Result.SUCCESS) { System.out.println(String.format( "Favorite for %s set to %b, Result: Success!", PokemonUtils.getLocalPokeName(poke), - !poke.isFavorite())); + favorite)); success.increment(); } else { err.increment(); @@ -715,13 +726,10 @@ private void toggleFavorite() { Utilities.getRealExceptionMessage(e))); } }); - try { - PokemonGoMainWindow.getInstance().refreshTitle(); - } catch (final Exception e) { - e.printStackTrace(); - } + + PokemonGoMainWindow.getInstance().refreshTitle(); SwingUtilities.invokeLater(this::refreshPkmn); - showFinishedText("Pokémon batch \"toggle favorite\" complete!", selection.size(), success, skipped, + showFinishedText(String.format("Pokémon batch \"%s\" complete!", operation), selection.size(), success, skipped, err); } diff --git a/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java b/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java index 791df3dc..9605585d 100644 --- a/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java +++ b/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java @@ -10,8 +10,7 @@ import org.junit.Test; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; +import com.pokegoapi.exceptions.request.LoginFailedException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.models.BpmOperationResult; @@ -44,7 +43,7 @@ public void beforeTest() { * @throws RemoteServerException sever error */ @Test - public void pokemonIsInGym() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void pokemonIsInGym() throws InvalidCurrencyException { doReturn(true).when(pokemon).isInGym(); final BpmOperationResult result = operation.execute(); @@ -58,10 +57,9 @@ public void pokemonIsInGym() throws InvalidCurrencyException, LoginFailedExcepti * * @throws InvalidCurrencyException invalid currency * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test - public void pokemonIsNotEvolvable() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void pokemonIsNotEvolvable() throws InvalidCurrencyException, LoginFailedException { final int noCandiesToEvolve = 0; doReturn(noCandiesToEvolve).when(pokemon).getCandies2Evlv(); @@ -79,7 +77,7 @@ public void pokemonIsNotEvolvable() throws InvalidCurrencyException, LoginFailed * @throws RemoteServerException sever error */ @Test - public void notEnoughCandies() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void notEnoughCandies() throws InvalidCurrencyException, LoginFailedException { final int insufficentCandies = 24; final int candiesToEvolve = 25; doReturn(insufficentCandies).when(pokemon).getCandies(); @@ -99,7 +97,7 @@ public void notEnoughCandies() throws InvalidCurrencyException, LoginFailedExcep * @throws RemoteServerException sever error */ @Test - public void sucessfullyEvolve() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void sucessfullyEvolve() throws InvalidCurrencyException, LoginFailedException { final int sufficentCandies = 25; final int candiesToEvolve = 25; doReturn(sufficentCandies).when(pokemon).getCandies(); diff --git a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java index d110bdba..eb890d32 100644 --- a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java +++ b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java @@ -10,8 +10,7 @@ import org.junit.Test; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.LoginFailedException; -import com.pokegoapi.exceptions.RemoteServerException; +import com.pokegoapi.exceptions.request.LoginFailedException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.models.BpmOperationResult; @@ -43,7 +42,7 @@ public void beforeTest() { * @throws RemoteServerException sever error */ @Test - public void pokemonIsFavorite() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void pokemonIsFavorite() throws InvalidCurrencyException { doReturn(true).when(pokemon).isIsFavorite(); final BpmOperationResult result = operation.execute(); @@ -60,7 +59,7 @@ public void pokemonIsFavorite() throws InvalidCurrencyException, LoginFailedExce * @throws RemoteServerException sever error */ @Test - public void pokemonIsInGym() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void pokemonIsInGym() throws InvalidCurrencyException { doReturn(true).when(pokemon).isInGym(); final BpmOperationResult result = operation.execute(); @@ -77,7 +76,7 @@ public void pokemonIsInGym() throws InvalidCurrencyException, LoginFailedExcepti * @throws RemoteServerException server error */ @Test - public void sucessfullyTransfer() throws InvalidCurrencyException, LoginFailedException, RemoteServerException { + public void sucessfullyTransfer() throws InvalidCurrencyException { doReturn(new BpmOperationResult()).when(operation).doOperation(); final BpmOperationResult result = operation.execute(); From 1e5e3f861885defa0c29e19eb39513235583211d Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Sun, 12 Mar 2017 01:50:58 -0300 Subject: [PATCH 13/41] Fixing codeclimate issues Configuring checkstyle SuppresionCommentFilter for the NullPointerException in PokemonTableModel class Erasing some throws tag in javadoc comment --- checkstyle.xml | 4 ++++ .../pokegoutil/utils/windows/PokemonTable.java | 7 +------ .../pokegoutil/utils/windows/PokemonTableModel.java | 13 ++++++++----- .../data/models/operations/EvolveOperationTest.java | 4 ---- .../models/operations/TransferOperationTest.java | 6 ------ 5 files changed, 13 insertions(+), 21 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 90c38612..09d7b38e 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -41,10 +41,14 @@ + + + + diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java index b72d773d..88536782 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTable.java @@ -102,12 +102,7 @@ public PokemonTable() { columnModel.getColumn(column.id).setCellEditor(column.getCellEditor()); } } - try { - restoreColumnOrder(); - } catch (Exception exc) { - System.out.println("Oooops, something went wrong with table order rearranging!"); - System.out.println(exc.toString()); - } + restoreColumnOrder(); } /** diff --git a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java index 4d8432ec..969f7e3a 100644 --- a/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java +++ b/src/me/corriekay/pokegoutil/utils/windows/PokemonTableModel.java @@ -38,21 +38,21 @@ public class PokemonTableModel extends AbstractTableModel { * Updates the table data with given pokemon list. * * @param pokes The list of pokemon that should be displayed - */ + */ public void updateTableData(final List pokes) { - ClearTable(); + clearTable(); final MutableInt i = new MutableInt(); pokes.forEach(p -> { pokeCol.add(i.getValue(), p); - for (final PokeColumn column : PokeColumn.values()) { // Reason: To avoid future problems inside whatever columns - // noinspection CheckStyle try { column.data.add(i.getValue(), column.get(p)); + //CHECKSTYLE:OFF } catch (NullPointerException e) { + //CHECKSTYLE:ON System.out.println("Error getting data for column: " + column.heading + " and value: " + i.getValue()); ConsolePrintStream.printException(e); } @@ -64,7 +64,10 @@ public void updateTableData(final List pokes) { fireTableDataChanged(); } - private void ClearTable() { + /** + * Clear the values from the table. + */ + private void clearTable() { pokeCol.clear(); for (final PokeColumn column : PokeColumn.values()) { column.data.clear(); diff --git a/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java b/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java index 9605585d..c5dce3a5 100644 --- a/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java +++ b/test/me/corriekay/pokegoutil/data/models/operations/EvolveOperationTest.java @@ -39,8 +39,6 @@ public void beforeTest() { * Evolve a pokemon that is in gym. * * @throws InvalidCurrencyException invalid currency - * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test public void pokemonIsInGym() throws InvalidCurrencyException { @@ -74,7 +72,6 @@ public void pokemonIsNotEvolvable() throws InvalidCurrencyException, LoginFailed * * @throws InvalidCurrencyException invalid currency * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test public void notEnoughCandies() throws InvalidCurrencyException, LoginFailedException { @@ -94,7 +91,6 @@ public void notEnoughCandies() throws InvalidCurrencyException, LoginFailedExcep * * @throws InvalidCurrencyException invalid currency * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test public void sucessfullyEvolve() throws InvalidCurrencyException, LoginFailedException { diff --git a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java index eb890d32..a940d6c6 100644 --- a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java +++ b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java @@ -38,8 +38,6 @@ public void beforeTest() { * Transfer a pokemon that is favorite. * * @throws InvalidCurrencyException invalid currency - * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test public void pokemonIsFavorite() throws InvalidCurrencyException { @@ -55,8 +53,6 @@ public void pokemonIsFavorite() throws InvalidCurrencyException { * Transfer a pokemon that is in gym. * * @throws InvalidCurrencyException invalid currency - * @throws LoginFailedException login fail - * @throws RemoteServerException sever error */ @Test public void pokemonIsInGym() throws InvalidCurrencyException { @@ -72,8 +68,6 @@ public void pokemonIsInGym() throws InvalidCurrencyException { * Transfer a pokemon successfully. * * @throws InvalidCurrencyException invalid currency - * @throws LoginFailedException login failed - * @throws RemoteServerException server error */ @Test public void sucessfullyTransfer() throws InvalidCurrencyException { From 7d14f5407cee0a981e7e62a3dd53183c92a32670 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Sun, 12 Mar 2017 21:59:59 -0300 Subject: [PATCH 14/41] Fixing more codeclimate issues --- .../pokegoutil/data/models/PlayerAccount.java | 3 - .../data/models/operations/Operation.java | 9 ++ .../pokegoutil/windows/PokemonTab.java | 127 +++++++++--------- .../operations/TransferOperationTest.java | 1 - 4 files changed, 73 insertions(+), 67 deletions(-) diff --git a/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java b/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java index ee77bf51..b97fc7cc 100644 --- a/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java +++ b/src/me/corriekay/pokegoutil/data/models/PlayerAccount.java @@ -3,7 +3,6 @@ import com.pokegoapi.api.player.PlayerProfile; import com.pokegoapi.api.player.PlayerProfile.Currency; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.request.LoginFailedException; public class PlayerAccount { @@ -23,8 +22,6 @@ public PlayerAccount(final PlayerProfile playerProfile) { * * @return number of stardust * @throws InvalidCurrencyException invalid currency - * @throws LoginFailedException login failed - * @throws RemoteServerException server error */ public int getStardust() throws InvalidCurrencyException { return playerProfile.getCurrency(Currency.STARDUST); diff --git a/src/me/corriekay/pokegoutil/data/models/operations/Operation.java b/src/me/corriekay/pokegoutil/data/models/operations/Operation.java index a9f21aff..26ed41e4 100644 --- a/src/me/corriekay/pokegoutil/data/models/operations/Operation.java +++ b/src/me/corriekay/pokegoutil/data/models/operations/Operation.java @@ -59,8 +59,17 @@ public Operation(final PokemonModel pokemon) { this.pokemon = pokemon; } + /** + * Abstract method to create the operation. + * @return BpmOperationResult with the operation created. + */ protected abstract BpmOperationResult doOperation(); + /** + * Execute the desired operation. + * @return BpmOperationResult with the result of the operation + * @throws InvalidCurrencyException when an invalidCurrencyException occours + */ public BpmOperationResult execute() throws InvalidCurrencyException { BpmOperationResult result = validateOperation(); diff --git a/src/me/corriekay/pokegoutil/windows/PokemonTab.java b/src/me/corriekay/pokegoutil/windows/PokemonTab.java index 4a387e14..4ae16675 100644 --- a/src/me/corriekay/pokegoutil/windows/PokemonTab.java +++ b/src/me/corriekay/pokegoutil/windows/PokemonTab.java @@ -126,7 +126,6 @@ public PokemonTab(final PokemonGo goInstance) { * Handle component creation and initialization inside PokemonTab constructor. */ private void addAndInitializeComponents() { - final SearchBarTextField searchBar = new SearchBarTextField(pt::filterTable); final JPanel topPanel = new JPanel(new GridBagLayout()); final JButton refreshPkmn = new JButton("Refresh List"), renameSelected = new JButton(BatchOperation.RENAME.toString()), @@ -158,7 +157,7 @@ private void addAndInitializeComponents() { gbc.weighty = 1.0; gbc.gridwidth = GRID_WIDTH; gbc.fill = GridBagConstraints.HORIZONTAL; - topPanel.add(searchBar, gbc); + topPanel.add(new SearchBarTextField(pt::filterTable), gbc); topPanel.add(pokelang); topPanel.add(fontSize); @@ -173,7 +172,7 @@ private void addAndInitializeComponents() { transferSelected.addActionListener(l -> new OperationWorker(this::transferSelected).execute()); evolveSelected.addActionListener(l -> new OperationWorker(this::evolveSelected).execute()); powerUpSelected.addActionListener(l -> new OperationWorker(this::powerUpSelected).execute()); - toggleFavorite.addActionListener(l -> new OperationWorker(this::toggleFavorite, null).execute()); + toggleFavorite.addActionListener(l -> new OperationWorker(this::toggleFavorite, BatchOperation.FAVORITE).execute()); setFavoriteYes.addActionListener(l -> new OperationWorker(this::toggleFavorite, BatchOperation.SET_FAVORITE_YES).execute()); setFavoriteNo.addActionListener(l -> new OperationWorker(this::toggleFavorite, BatchOperation.SET_FAVORITE_NO).execute()); transferIv.addActionListener(l -> new OperationWorker(pt::selectLessThanIv, ivTransfer.getText()).execute()); @@ -189,6 +188,10 @@ private void addAndInitializeComponents() { }).execute()); } + /** + * Change the language of the pokemons using the langCode. + * @param langCode language to change + */ private void changeLanguage(final String langCode) { config.setString(ConfigKey.LANGUAGE, langCode); @@ -660,77 +663,75 @@ private void powerUpSelected() { } - // feature added by Ben Kauffman + /** + * To favorite or not the selected Pokemon's. + * @author Ben Kauffman + * @param operation which operation to do regarding favorite: Toogle, Set Yes or Set No + */ private void toggleFavorite(final BatchOperation operation) { final ArrayList selection = pt.getSelectedPokemon(); - if (selection.isEmpty()) { - return; - } - - if (!confirmOperation(operation, selection)) { - return; - } - - final MutableInt err = new MutableInt(), - skipped = new MutableInt(), - success = new MutableInt(), - total = new MutableInt(1); - - selection.forEach(poke -> { - try { - System.out.println(String.format( - "Setting favorite %d of %d", - total.getValue(), - selection.size())); - total.increment(); - boolean favorite = !poke.isFavorite(); - if (operation != null) { + if (!selection.isEmpty() && confirmOperation(operation, selection)) { + final MutableInt err = new MutableInt(), + skipped = new MutableInt(), + success = new MutableInt(), + total = new MutableInt(1); + + selection.forEach(poke -> { + try { + System.out.println(String.format( + "Setting favorite %d of %d", + total.getValue(), + selection.size())); + total.increment(); + final boolean favorite; if (operation.equals(BatchOperation.SET_FAVORITE_YES)) { favorite = true; - } else { + } else if (operation.equals(BatchOperation.SET_FAVORITE_NO)) { favorite = false; + } else { + favorite = !poke.isFavorite(); } - } - final SetFavoritePokemonResponse.Result favoriteResult = poke - .setFavoritePokemon(favorite); - System.out.println(String.format( - "Attempting to set favorite for %s to %b...", - PokemonUtils.getLocalPokeName(poke), - favorite)); - - if (favoriteResult == SetFavoritePokemonResponse.Result.SUCCESS) { + final SetFavoritePokemonResponse.Result favoriteResult = poke + .setFavoritePokemon(favorite); System.out.println(String.format( - "Favorite for %s set to %b, Result: Success!", - PokemonUtils.getLocalPokeName(poke), - favorite)); - success.increment(); - } else { + "Attempting to set favorite for %s to %b...", + PokemonUtils.getLocalPokeName(poke), + favorite)); + + if (favoriteResult == SetFavoritePokemonResponse.Result.SUCCESS) { + System.out.println(String.format( + "Favorite for %s set to %b, Result: Success!", + PokemonUtils.getLocalPokeName(poke), + favorite)); + success.increment(); + } else { + err.increment(); + System.out.println(String.format( + "Error toggling favorite for %s, result: %s", + PokemonUtils.getLocalPokeName(poke), + favoriteResult.toString())); + } + + // If not last element, sleep until the next one + if (!selection.get(selection.size() - 1).equals(poke)) { + final int sleepMin = config.getInt(ConfigKey.DELAY_FAVORITE_MIN); + final int sleepMax = config.getInt(ConfigKey.DELAY_FAVORITE_MAX); + Utilities.sleepRandom(sleepMin, sleepMax); + } + } catch (final Exception e) { err.increment(); System.out.println(String.format( - "Error toggling favorite for %s, result: %s", - PokemonUtils.getLocalPokeName(poke), - favoriteResult.toString())); + "Error toggling favorite for %s! %s", + PokemonUtils.getLocalPokeName(poke), + Utilities.getRealExceptionMessage(e))); } + }); - // If not last element, sleep until the next one - if (!selection.get(selection.size() - 1).equals(poke)) { - final int sleepMin = config.getInt(ConfigKey.DELAY_FAVORITE_MIN); - final int sleepMax = config.getInt(ConfigKey.DELAY_FAVORITE_MAX); - Utilities.sleepRandom(sleepMin, sleepMax); - } - } catch (final Exception e) { - err.increment(); - System.out.println(String.format( - "Error toggling favorite for %s! %s", - PokemonUtils.getLocalPokeName(poke), - Utilities.getRealExceptionMessage(e))); - } - }); - - PokemonGoMainWindow.getInstance().refreshTitle(); - SwingUtilities.invokeLater(this::refreshPkmn); - showFinishedText(String.format("Pokémon batch \"%s\" complete!", operation), selection.size(), success, skipped, - err); + PokemonGoMainWindow.getInstance().refreshTitle(); + SwingUtilities.invokeLater(this::refreshPkmn); + showFinishedText(String.format("Pokémon batch \"%s\" complete!", operation), selection.size(), success, skipped, + err); + } } /** diff --git a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java index a940d6c6..b299e410 100644 --- a/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java +++ b/test/me/corriekay/pokegoutil/data/models/operations/TransferOperationTest.java @@ -10,7 +10,6 @@ import org.junit.Test; import com.pokegoapi.exceptions.InvalidCurrencyException; -import com.pokegoapi.exceptions.request.LoginFailedException; import me.corriekay.pokegoutil.data.enums.OperationError; import me.corriekay.pokegoutil.data.models.BpmOperationResult; From 5915571eb26a096e6dae9fca26ae75ae26384b28 Mon Sep 17 00:00:00 2001 From: FernandoTBarros Date: Tue, 14 Mar 2017 02:54:52 -0300 Subject: [PATCH 15/41] Rebuilding login form. Turning on JavaFX nature again. --- src/main/resources/layout/Login.fxml | 90 ++++++++---- .../pokegoutil/BlossomsPoGoManager.java | 87 +++++++----- .../data/managers/AccountManager.java | 31 ++-- .../pokegoutil/data/models/LoginData.java | 22 +++ .../gui/controller/LoginController.java | 132 ++++++++++++++---- .../corriekay/pokegoutil/windows/MenuBar.java | 4 +- 6 files changed, 266 insertions(+), 100 deletions(-) diff --git a/src/main/resources/layout/Login.fxml b/src/main/resources/layout/Login.fxml index 915e32c4..dfabe4bc 100644 --- a/src/main/resources/layout/Login.fxml +++ b/src/main/resources/layout/Login.fxml @@ -1,39 +1,77 @@ + + + + - - - - - - - - -