diff options
author | Eduardo Pedroni <e.pedroni91@gmail.com> | 2015-06-24 18:58:15 +0200 |
---|---|---|
committer | Eduardo Pedroni <e.pedroni91@gmail.com> | 2015-06-24 18:58:15 +0200 |
commit | bf29c3d96160eeaa64f60a512a0a9f4d7c85167a (patch) | |
tree | d748a0fa4016c188b3d4be5bdd719261b40655b0 /src/eu/equalparts/cardbase | |
parent | 59174889aba82c64ae63e0a5622d6cbcab63dc39 (diff) |
Mulling over the generic comparator issue
Diffstat (limited to 'src/eu/equalparts/cardbase')
7 files changed, 201 insertions, 90 deletions
diff --git a/src/eu/equalparts/cardbase/Cardbase.java b/src/eu/equalparts/cardbase/Cardbase.java index 211f865..9245870 100644 --- a/src/eu/equalparts/cardbase/Cardbase.java +++ b/src/eu/equalparts/cardbase/Cardbase.java @@ -2,9 +2,11 @@ package eu.equalparts.cardbase; import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerationException; @@ -12,11 +14,12 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; +import eu.equalparts.cardbase.comparator.CardComparator; import eu.equalparts.cardbase.data.Card; import eu.equalparts.cardbase.utils.JSON; /** - * Provides a variety of utility methods to interact with the loaded cardbase. + * Provides a variety of utility methods to interact with an optionally loaded cardbase. * * @author Eduardo Pedroni */ @@ -32,7 +35,6 @@ public class Cardbase { * information to be printed to the console. */ public static final boolean DEBUG = System.getenv("CB_DEBUG") != null; - /** * Used in the hash generation. */ @@ -134,12 +136,22 @@ public class Cardbase { } /** + * @param field the name of the field by which to sort. + * @return an unmodifiable collection representing the cardbase sorted in the required order. + * @throws NoSuchFieldException if the field provided is invalid. + */ + public Collection<Card> sort(String field) throws NoSuchFieldException { + List<Card> sortedCards = new ArrayList<Card>(cards.values()); + sortedCards.sort(new CardComparator(Card.class.getDeclaredField(field))); + return Collections.unmodifiableCollection(sortedCards); + } + + /** * Returns a card from the cardbase by set code and number. * If no such card is in the cardbase, returns null. * * @param setCode the set to which the requested card belongs. * @param number the requested card's set number. - * key * @return the requested {@code Card} or null if no card is found. */ public Card getCard(String setCode, String number) { @@ -152,7 +164,6 @@ public class Cardbase { * If no such card is in the cardbase, returns null. * * @param hash the Cardbase hash of the requested card. - * * @return the requested {@code Card} or null if no card is found. */ public Card getCardFromHash(String hash) { diff --git a/src/eu/equalparts/cardbase/cli/CardbaseCLI.java b/src/eu/equalparts/cardbase/cli/CardbaseCLI.java index 7a2e581..6a7f013 100644 --- a/src/eu/equalparts/cardbase/cli/CardbaseCLI.java +++ b/src/eu/equalparts/cardbase/cli/CardbaseCLI.java @@ -96,15 +96,15 @@ public class CardbaseCLI { * * @param args a list of arguments. Only the first argument is used, as a cardbase JSON. */ - private CardbaseCLI(String... args) { + public CardbaseCLI(String... args) { System.out.println("Welcome to Cardbase CLI!"); // set debug flag if we are debugging if (Cardbase.DEBUG) System.out.println("Debug mode is on."); - // make the CardbaseManager - if (args.length > 0) { - File cardbaseFile = new File(args[0]); + // make the Cardbase + if (args != null && args.length > 0) { + cardbaseFile = new File(args[0]); if (cardbaseFile.exists() && cardbaseFile.isFile() && cardbaseFile.canRead()) { System.out.println("Loading cardbase from \"" + args[0] + "\"."); try { @@ -124,7 +124,7 @@ public class CardbaseCLI { System.exit(1); } } else { - System.out.println(args[0] + " appears to be invalid."); + System.out.println(args[0] + " appears to be an invalid path."); System.exit(0); } } else { @@ -202,7 +202,7 @@ public class CardbaseCLI { public void write(String[] args) { File outputFile; // user-provided file overrides everything else - if (args.length > 0) { + if (args != null && args.length > 0) { outputFile = new File(sanitiseFileName(args[0])); } else { outputFile = cardbaseFile; @@ -261,7 +261,7 @@ public class CardbaseCLI { * @param args the code of the chosen set. */ public void set(String[] args) { - if (args.length > 0) { + if (args != null && args.length > 0) { try { selectedSet = MTGUniverse.getFullCardSet(args[0]); // if the set code is invalid, null is returned @@ -306,7 +306,7 @@ public class CardbaseCLI { */ public void peruse(String[] args) { // if a card is specified, peruse only that - if (args.length > 0) { + if (args != null && args.length > 0) { if (selectedSet != null) { Card card = cardbase.getCard(selectedSet.code, args[0]); if (card != null) { @@ -352,7 +352,7 @@ public class CardbaseCLI { */ public void remove(String[] args) { if (selectedSet != null) { - if (args.length > 0) { + if (args != null && args.length > 0) { Card cardToRemove = selectedSet.getCardByNumber(args[0]); if (cardToRemove != null) { Integer count = 1; @@ -391,7 +391,7 @@ public class CardbaseCLI { Card cardToAdd = selectedSet.getCardByNumber(number); if (cardToAdd != null) { Integer count = 1; - if (args.length > 0 && args[0].matches("[0-9]+")) { + if (args != null && args.length > 0 && args[0].matches("[0-9]+")) { count = Integer.valueOf(args[0]); if (count <= 0) { System.out.println("Can't add " + count + " cards."); diff --git a/src/eu/equalparts/cardbase/comparator/CardComparator.java b/src/eu/equalparts/cardbase/comparator/CardComparator.java new file mode 100644 index 0000000..78200b8 --- /dev/null +++ b/src/eu/equalparts/cardbase/comparator/CardComparator.java @@ -0,0 +1,126 @@ +package eu.equalparts.cardbase.comparator; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Comparator; +import java.util.function.BiFunction; + +import eu.equalparts.cardbase.Cardbase; +import eu.equalparts.cardbase.data.Card; + +/** + * I'm new to this reflection business, so bear with me. + * <br><br> + * The idea here is to avoid having to write one class + * for each comparable field in {@code Card}. The program + * can dynamically instantiate them as cards are compared + * by different fields. + * <br><br> + * This class uses reflection to determine if the specified + * field is comparable with itself upon construction, and throws + * an {@code IllegalArgumentException} if that is not the case. + * + * @author Eduardo Pedroni + * + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +public class CardComparator implements Comparator<Card> { + + public enum Order { + NATURAL, REVERSE; + } + + /** + * The field being compared. + */ + private Field fieldToCompare; + + private BiFunction<Comparable, Comparable, Integer> comparisonDelegate = this::defaultComparison; + + /** + * Creates a new comparator for the specified field only. This class + * will only be constructed successfully if the field comes from + * {@code Card} and can be compared to itself (i.e. implements + * {@code Comparable<T>} where T is its own type. + * <br> + * For reference, {@code String} and {@code Integer} are both self comparable. + * + * @param fieldToCompare the field this comparator will use to compare cards, as declared in {@code Card}. + */ + public CardComparator(Field fieldToCompare) { + if (fieldToCompare.getDeclaringClass().equals(Card.class) && + isSelfComparable(fieldToCompare.getType())) { + + this.fieldToCompare = fieldToCompare; + + // if annotated with a special comparator, set the comparison delegate here + this.comparisonDelegate = ComparatorDelegates::compareManaCost; + + } else { + System.out.println(fieldToCompare.isAccessible()); + System.out.println(fieldToCompare.getDeclaringClass().equals(Card.class)); + System.out.println(isSelfComparable(fieldToCompare.getType())); + throw new IllegalArgumentException("The field provided is not valid."); + } + } + + @Override + public int compare(Card o1, Card o2) { + /* + * we've already checked that the field is self comparable, + * so we are now free to cast to whatever type it is and compare. + */ + try { + Comparable field1 = (Comparable) fieldToCompare.get(o1); + Comparable field2 = (Comparable) fieldToCompare.get(o2); + + return comparisonDelegate.apply(field1, field2); + } catch (IllegalArgumentException e) { + System.out.println("Error: class Card does not define field" + fieldToCompare.getName() + "."); + if (Cardbase.DEBUG) e.printStackTrace(); + } catch (IllegalAccessException e) { + System.out.println("Error: field " + fieldToCompare.getName() + " in Card is not visible."); + if (Cardbase.DEBUG) e.printStackTrace(); + } + + // fallback, this shouldn't happen + return 0; + } + + /** + * The standard comparison operation, which uses the field's own {@code compareTo()} + * method. + * + * @param field1 the first object to be compared. + * @param field2 the second object to be compared. + * @return a negative integer, zero, or a positive integer as the + * first argument is less than, equal to, or greater than the + * second. + */ + private int defaultComparison(Comparable field1, Comparable field2) { + return field1.compareTo(field2); + } + + /** + * Use reflection to determine if the specified class can be compared with itself. + * + * @param type the type to analyse. + * @return true if the type can be compared to itself using {@code compareTo()}, false otherwise. + */ + private boolean isSelfComparable(Class<?> type) { + + // go through all interfaces implemented by this class + for (Type implementedInterface : type.getGenericInterfaces()) { + // check if any parameterised interface found is "Comparable" + if (implementedInterface instanceof ParameterizedType) { + ParameterizedType genericInterface = (ParameterizedType) implementedInterface; + if (genericInterface.getRawType().equals(Comparable.class)) { + // check that the type argument of comparable is the same as the field type itself + return genericInterface.getActualTypeArguments()[0].equals(type); + } + } + } + return false; + } +} diff --git a/src/eu/equalparts/cardbase/comparator/ComparatorDelegates.java b/src/eu/equalparts/cardbase/comparator/ComparatorDelegates.java new file mode 100644 index 0000000..5736381 --- /dev/null +++ b/src/eu/equalparts/cardbase/comparator/ComparatorDelegates.java @@ -0,0 +1,39 @@ +package eu.equalparts.cardbase.comparator; + + +abstract class ComparatorDelegates { + + private ComparatorDelegates() {} + + public static Integer compareManaCost(Comparable<String> field1, Comparable<String> field2) { + // avoid casting syntax nightmare + String mc1 = (String) field1, mc2 = (String) field2; + + // first by number of colours + int mc1count = 0, mc2count = 0; + if (mc1.contains("W")) mc1count++; + if (mc1.contains("U")) mc1count++; + if (mc1.contains("B")) mc1count++; + if (mc1.contains("R")) mc1count++; + if (mc1.contains("G")) mc1count++; + + if (mc2.contains("W")) mc2count++; + if (mc2.contains("U")) mc2count++; + if (mc2.contains("B")) mc2count++; + if (mc2.contains("R")) mc2count++; + if (mc2.contains("G")) mc2count++; + + if (mc1count != mc2count) + return (mc1count < mc2count) ? -1 : ((mc1count == mc2count) ? 0 : 1); + + // next by colour wheel + + return 0; + } + +} +/* + * first by number of colours + * next by colour wheel: white > blue > black > red > green + * next by cmc + */
\ No newline at end of file diff --git a/src/eu/equalparts/cardbase/comparator/SpecialFields.java b/src/eu/equalparts/cardbase/comparator/SpecialFields.java new file mode 100644 index 0000000..8ecc82c --- /dev/null +++ b/src/eu/equalparts/cardbase/comparator/SpecialFields.java @@ -0,0 +1,8 @@ +package eu.equalparts.cardbase.comparator; + + +public class SpecialFields { + + public @interface ManaCost {} + +} diff --git a/src/eu/equalparts/cardbase/comparators/CardComparators.java b/src/eu/equalparts/cardbase/comparators/CardComparators.java deleted file mode 100644 index 99f7ded..0000000 --- a/src/eu/equalparts/cardbase/comparators/CardComparators.java +++ /dev/null @@ -1,76 +0,0 @@ -package eu.equalparts.cardbase.comparators; - -import java.util.Comparator; - -import eu.equalparts.cardbase.data.Card; - -public final class CardComparators { - - private CardComparators() {} - - public enum Order { - NATURAL, REVERSE; - } - - public static class NameComparator implements Comparator<Card> { - - private Order order = Order.NATURAL; - - public NameComparator() {} - - public NameComparator(Order order) { - this.order = order; - } - - @Override - public int compare(Card o1, Card o2) { - if (order == Order.NATURAL) { - return o1.name.compareTo(o2.name); - } else { - return o2.name.compareTo(o1.name); - } - - } - } - - public static class LayoutComparator implements Comparator<Card> { - - private Order order = Order.NATURAL; - - public LayoutComparator() {} - - public LayoutComparator(Order order) { - this.order = order; - } - - @Override - public int compare(Card o1, Card o2) { - if (order == Order.NATURAL) { - return o1.layout.compareTo(o2.layout); - } else { - return o2.layout.compareTo(o1.layout); - } - } - } - - public static class ManaCostComparator implements Comparator<Card> { - - private Order order = Order.NATURAL; - - public ManaCostComparator() {} - - public ManaCostComparator(Order order) { - this.order = order; - } - - @Override - public int compare(Card o1, Card o2) { - if (order == Order.NATURAL) { - return o1.manaCost.compareTo(o2.manaCost); - } else { - return o2.manaCost.compareTo(o1.manaCost); - } - } - } - -} diff --git a/src/eu/equalparts/cardbase/data/Card.java b/src/eu/equalparts/cardbase/data/Card.java index 2810564..7202660 100644 --- a/src/eu/equalparts/cardbase/data/Card.java +++ b/src/eu/equalparts/cardbase/data/Card.java @@ -1,9 +1,12 @@ package eu.equalparts.cardbase.data; +import eu.equalparts.cardbase.comparator.SpecialFields.ManaCost; + public class Card { public String name; public String layout; + @ManaCost public String manaCost; public Integer cmc; public String type; |