From 800c802c2b43a325b42412d9f6e6ae0d5c86adbc Mon Sep 17 00:00:00 2001 From: Vest Date: Sat, 16 Nov 2024 01:55:02 +0100 Subject: [PATCH] CODE-3531: increased the number of recent files from 8 to 20 (#7222) * CODE-3531: increased the number of recent files from 8 to 20, but it is not configurable Massive refactoring of PropertyContext.java and switching to Java's Optional and Streams if possible. Slightly reduced the dependency to ApacheCommons. Resolved many warnings suggested by IDEA and SonarLint. Signed-off-by: Vest * Replaced 4 spaces with \t Added two @param descriptions (for IDEA). Signed-off-by: Vest --------- Signed-off-by: Vest --- .../java/pcgen/core/SystemCollections.java | 15 +- .../pcgen/facade/core/CharacterFacade.java | 402 +++++++++--------- .../facade/core/SourceSelectionFacade.java | 18 +- .../pcgen/facade/util/ReferenceFacade.java | 12 +- code/src/java/pcgen/gui2/PCGenFrame.java | 22 +- .../gui2/facade/CharacterFacadeImpl.java | 107 ++--- .../java/pcgen/system/CharacterManager.java | 36 +- code/src/java/pcgen/system/FacadeFactory.java | 74 ++-- .../java/pcgen/system/PropertyContext.java | 91 ++-- .../src/java/pcgen/system/RecentFileList.java | 63 ++- code/src/java/pcgen/util/Logging.java | 52 ++- 11 files changed, 432 insertions(+), 460 deletions(-) diff --git a/code/src/java/pcgen/core/SystemCollections.java b/code/src/java/pcgen/core/SystemCollections.java index ae6f0945df9..c147f8f1eb2 100644 --- a/code/src/java/pcgen/core/SystemCollections.java +++ b/code/src/java/pcgen/core/SystemCollections.java @@ -84,15 +84,10 @@ private SystemCollections() */ public static GameMode getGameModeNamed(final String aString) { - for (GameMode gameMode : GAME_MODE_LIST) - { - if (gameMode.getName().equalsIgnoreCase(aString)) - { - return gameMode; - } - } - - return null; + return GAME_MODE_LIST.stream() + .filter(gameMode -> gameMode.getName().equalsIgnoreCase(aString)) + .findFirst() + .orElse(null); } /** @@ -171,7 +166,7 @@ public static List getUnmodifiableEquipSlotList() } /** - * Return an unmodifiable version of the body structure list for the + * Return an unmodifiable version of the body structure list for the * current gamemode. * @return an unmodifiable version of the body structure list. */ diff --git a/code/src/java/pcgen/facade/core/CharacterFacade.java b/code/src/java/pcgen/facade/core/CharacterFacade.java index 798d6e6b1a3..59669e14dc9 100644 --- a/code/src/java/pcgen/facade/core/CharacterFacade.java +++ b/code/src/java/pcgen/facade/core/CharacterFacade.java @@ -1,20 +1,20 @@ /* * Copyright 2008 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * + * */ package pcgen.facade.core; @@ -71,244 +71,244 @@ public interface CharacterFacade extends CompanionFacade { - public InfoFactory getInfoFactory(); + InfoFactory getInfoFactory(); - public ReferenceFacade getGenderRef(); + ReferenceFacade getGenderRef(); - public void setAlignment(PCAlignment alignment); + void setAlignment(PCAlignment alignment); - public ReferenceFacade getAlignmentRef(); + ReferenceFacade getAlignmentRef(); - public void setGender(Gender gender); + void setGender(Gender gender); - public void setGender(String gender); + void setGender(String gender); /** * @param stat The stat to retrieve the base for * @return A reference to the base score for the stat */ - public ReferenceFacade getScoreBaseRef(PCStat stat); + ReferenceFacade getScoreBaseRef(PCStat stat); /** * @param stat The stat to retrieve the mod total for * @return The modifier for the stat total */ - public int getModTotal(PCStat stat); + int getModTotal(PCStat stat); /** * @param stat The stat to retrieve the base score of * @return The base (user set) score for the stat */ - public int getScoreBase(PCStat stat); + int getScoreBase(PCStat stat); /** * Update the base score of the stat. * @param stat The stat to be set. * @param score The new base score. */ - public void setScoreBase(PCStat stat, int score); + void setScoreBase(PCStat stat, int score); /** - * Retrieve the display string for the score total. This may be a + * Retrieve the display string for the score total. This may be a * non-number if the stat is a non-ability (e.g. ghost constitution) - * or if the game mode has named stat values (see the STATROLLTEXT + * or if the game mode has named stat values (see the STATROLLTEXT * game mode token). - * + * * @param stat The stat to be retrieved * @return The display string for the score total */ - public String getScoreTotalString(PCStat stat); + String getScoreTotalString(PCStat stat); /** * @param stat The stat to retrieve the racial bonus of. * @return The racial bonus to the stat score. */ - public int getScoreRaceBonus(PCStat stat); + int getScoreRaceBonus(PCStat stat); /** - * Retrieve the bonus to the stat score from sources other than the + * Retrieve the bonus to the stat score from sources other than the * character's race. e.g. templates, abilities. Also called the misc bonus. * @param stat The stat to retrieve the other bonus of. * @return The misc bonus to the stat score */ - public int getScoreOtherBonus(PCStat stat); + int getScoreOtherBonus(PCStat stat); - public void addAbility(AbilityCategory category, AbilityFacade ability); + void addAbility(AbilityCategory category, AbilityFacade ability); - public void removeAbility(AbilityCategory category, AbilityFacade ability); + void removeAbility(AbilityCategory category, AbilityFacade ability); /** * Note: This method should never return null. If the character does not possess * any abilities in the parameter category, this method should create a new * DefaultGenericListModel for that category and keep a reference to it for future use. - * @param category - * @return a List of Abilities the character posseses in the specified category + * @param category for which abilities are returned + * @return a List of Abilities the character possesses in the specified category */ - public ListFacade getAbilities(AbilityCategory category); + ListFacade getAbilities(AbilityCategory category); /** - * Retrieve a list of the ability categories that are currently relevant to - * the character. That is those ability categories that the character has - * abilities or unspent pool points in. The list will be updated as + * Retrieve a list of the ability categories that are currently relevant to + * the character. That is those ability categories that the character has + * abilities or unspent pool points in. The list will be updated as * categories become active or inactive. * @return The list of active categories. */ - public ListFacade getActiveAbilityCategories(); + ListFacade getActiveAbilityCategories(); - public void addCharacterLevels(PCClass[] classes); + void addCharacterLevels(PCClass[] classes); - public void removeCharacterLevels(int levels); + void removeCharacterLevels(int levels); /** * This returns the number of times that a given class has been taken by this character. * @param c a ClassFacade * @return the total level of a class */ - public int getClassLevel(PCClass c); + int getClassLevel(PCClass c); - public int getTotalSelections(AbilityCategory category); + int getTotalSelections(AbilityCategory category); - public int getRemainingSelections(AbilityCategory category); + int getRemainingSelections(AbilityCategory category); - public void setRemainingSelection(AbilityCategory category, int remaining); + void setRemainingSelection(AbilityCategory category, int remaining); /** * Adjust the cash held by the character. * @param modVal The amount to add to the character's funds. */ - public void adjustFunds(BigDecimal modVal); + void adjustFunds(BigDecimal modVal); /** * Set the cash held by the character. * @param newVal The new amount for the character's funds. */ - public void setFunds(BigDecimal newVal); + void setFunds(BigDecimal newVal); /** * @return A reference to the amount of gold the character owns. */ - public ReferenceFacade getFundsRef(); + ReferenceFacade getFundsRef(); /** * @return A reference to the total wealth of the character. */ - public ReferenceFacade getWealthRef(); + ReferenceFacade getWealthRef(); /** * @return A reference to the chosen buy sell rate scheme for the character. */ - public ReferenceFacade getGearBuySellRef(); + ReferenceFacade getGearBuySellRef(); /** * Set a new buy sell rate scheme for the character. * @param scheme The new buy sell rate scheme. */ - public void setGearBuySellRef(GearBuySellFacade scheme); + void setGearBuySellRef(GearBuySellFacade scheme); /** * @param allowed Is the character allowed to spend more funds than they have. */ - public void setAllowDebt(boolean allowed); + void setAllowDebt(boolean allowed); /** * @return True if the character is allowed to spend more funds than they have. */ - public boolean isAllowDebt(); + boolean isAllowDebt(); - public ListFacade getEquipmentSets(); + ListFacade getEquipmentSets(); - public ReferenceFacade getEquipmentSetRef(); + ReferenceFacade getEquipmentSetRef(); - public void setEquipmentSet(EquipmentSetFacade set); + void setEquipmentSet(EquipmentSetFacade set); - public EquipmentListFacade getPurchasedEquipment(); + EquipmentListFacade getPurchasedEquipment(); - public void addPurchasedEquipment(EquipmentFacade equipment, int quantity, boolean customize, boolean free); + void addPurchasedEquipment(EquipmentFacade equipment, int quantity, boolean customize, boolean free); - public void removePurchasedEquipment(EquipmentFacade equipment, int quantity, boolean free); + void removePurchasedEquipment(EquipmentFacade equipment, int quantity, boolean free); //public int getQuantity(EquipmentFacade equipment); - public boolean isQualifiedFor(EquipmentFacade equipment); + boolean isQualifiedFor(EquipmentFacade equipment); /** - * Create an equipment item sized for the character. Will return an existing - * item if a suitable one already exists, including the passed in item if it - * is already the correct size ir if the item is not the type of item that + * Create an equipment item sized for the character. Will return an existing + * item if a suitable one already exists, including the passed in item if it + * is already the correct size ir if the item is not the type of item that * can be resized. - * + * * @param equipment The equipment item to be resized. * @return The item at the correct size. */ - public EquipmentFacade getEquipmentSizedForCharacter(EquipmentFacade equipment); + EquipmentFacade getEquipmentSizedForCharacter(EquipmentFacade equipment); /** - * Whether we should automatically resize all purchased gear to match the + * Whether we should automatically resize all purchased gear to match the * character's size. * @return true if equipment should be auto resize. */ - public boolean isAutoResize(); + boolean isAutoResize(); /** - * Update whether we should automatically resize all purchased gear to match + * Update whether we should automatically resize all purchased gear to match * the character's size. - * + * * @param autoResize The new value for auto resize equipment option. */ - public void setAutoResize(boolean autoResize); + void setAutoResize(boolean autoResize); - public EquipmentSetFacade createEquipmentSet(String name); + EquipmentSetFacade createEquipmentSet(String name); - public void deleteEquipmentSet(EquipmentSetFacade set); + void deleteEquipmentSet(EquipmentSetFacade set); - public boolean isQualifiedFor(PCClass c); + boolean isQualifiedFor(PCClass c); - public boolean isAutomatic(Language language); + boolean isAutomatic(Language language); /** - * Is the user allowed to remove this language currently? - * e.g Automatic languages may not be removed. + * Is the user allowed to remove this language currently? + * e.g Automatic languages may not be removed. * @param language The language to be checked. * @return true if the language can be removed. */ - public boolean isRemovable(Language language); + boolean isRemovable(Language language); - public void addTemplate(PCTemplate template); + void addTemplate(PCTemplate template); - public void removeTemplate(PCTemplate template); + void removeTemplate(PCTemplate template); - public ListFacade getTemplates(); + ListFacade getTemplates(); /** * Note: this returns both the bonuses that the character * has applied as well as the ones that haven't been applied. * @return a list of bonuses than the character can apply */ - public ListFacade getAvailableTempBonuses(); + ListFacade getAvailableTempBonuses(); /** * adds a temp bonus to the character * @param bonus the bonus to add */ - public void addTempBonus(TempBonusFacade bonus); + void addTempBonus(TempBonusFacade bonus); /** * removes a bonus from the character * @param bonus the bonus to remove */ - public void removeTempBonus(TempBonusFacade bonus); + void removeTempBonus(TempBonusFacade bonus); /** * Enables or disables a temporary bonus to the character. * @param bonusFacade the bonus to change - * @param active True: Make the bonus active, False: Make the bonus inactive + * @param active True: Make the bonus active, False: Make the bonus inactive */ - public void setTempBonusActive(TempBonusFacade bonusFacade, boolean active); + void setTempBonusActive(TempBonusFacade bonusFacade, boolean active); /** - * + * * @return a list of bonuses that have been added to the character */ - public ListFacade getTempBonuses(); + ListFacade getTempBonuses(); /** * This returns a DataSetFacade that contains all @@ -317,331 +317,331 @@ public interface CharacterFacade extends CompanionFacade * of the other facades available for this character. * @return the DataSetFacade for this character */ - public DataSetFacade getDataSet(); + DataSetFacade getDataSet(); /** * @return a reference to this character's Race */ @Override - public ReferenceFacade getRaceRef(); + ReferenceFacade getRaceRef(); /** * Sets this character's race - * @param race + * @param race a character's race to be set */ - public void setRace(Race race); + void setRace(Race race); /** * @return a reference to this character's tab name */ - public ReferenceFacade getTabNameRef(); + ReferenceFacade getTabNameRef(); /** * @param name the text to displayed in the character's tab */ - public void setTabName(String name); + void setTabName(String name); /** * @return a reference to this character's name */ @Override - public ReferenceFacade getNameRef(); + ReferenceFacade getNameRef(); /** * Sets this character's name * @param name the name of the character */ - public void setName(String name); + void setName(String name); /** * @return a reference to this character's player's name */ - public ReferenceFacade getPlayersNameRef(); + ReferenceFacade getPlayersNameRef(); /** * @param name The name of the player */ - public void setPlayersName(String name); + void setPlayersName(String name); /** * @return a reference to this character's handedness string */ - public ReferenceFacade getHandedRef(); + ReferenceFacade getHandedRef(); /** * @param handedness The new handedness string for the character */ - public void setHanded(Handed handedness); + void setHanded(Handed handedness); /** * @see CharacterFacade#setFile(File) * @return a reference to the character's file */ @Override - public ReferenceFacade getFileRef(); + ReferenceFacade getFileRef(); /** * Sets the file that this character will be saved to. * @see CharacterFacade#getFileRef() * @param file the File to associate with this character */ - public void setFile(File file); + void setFile(File file); - public ReferenceFacade getDeityRef(); + ReferenceFacade getDeityRef(); - public void setDeity(Deity deity); + void setDeity(Deity deity); /** * @return The domains that the character knows */ - public ListFacade> getDomains(); + ListFacade> getDomains(); /** * Add a domain to the list of those the character knows. * @param domain The domain to add. */ - public void addDomain(QualifiedObject domain); + void addDomain(QualifiedObject domain); /** * Remove a domain from the list of those the character knows. * @param domain The domain to remove. */ - public void removeDomain(QualifiedObject domain); + void removeDomain(QualifiedObject domain); - public ReferenceFacade getRemainingDomainSelectionsRef(); + ReferenceFacade getRemainingDomainSelectionsRef(); - public ListFacade getAvailableHands(); + ListFacade getAvailableHands(); - public ListFacade getAvailableGenders(); + ListFacade getAvailableGenders(); /** * @return The domains which the character has access to. */ - public ListFacade> getAvailableDomains(); + ListFacade> getAvailableDomains(); - public ListFacade getLanguages(); + ListFacade getLanguages(); - public ListFacade getLanguageChoosers(); + ListFacade getLanguageChoosers(); /** * Remove a bonus language from the character. * @param lang The language to be removed */ - public void removeLanguage(Language lang); + void removeLanguage(Language lang); /** * Write the character details, as defined by the export handler to the writer. - * + * * @param theHandler The ExportHandler that defines how the output will be formatted. * @param buf The writer the character details are to be output to. * @throws ExportException If the export fails. */ - public void export(ExportHandler theHandler, BufferedWriter buf) throws ExportException; + void export(ExportHandler theHandler, BufferedWriter buf) throws ExportException; /** * gets the UIDelegate that this character uses to display messages * and choosers * @return the UIDelegate that this character uses */ - public UIDelegate getUIDelegate(); + UIDelegate getUIDelegate(); /** * @return The facade for character levels for this character. */ - public CharacterLevelsFacade getCharacterLevelsFacade(); + CharacterLevelsFacade getCharacterLevelsFacade(); /** * @return The facade for description for this character. */ - public DescriptionFacade getDescriptionFacade(); + DescriptionFacade getDescriptionFacade(); /** * Set the character's current experience point value * @param xp The new XP value to be set */ - public void setXP(int xp); + void setXP(int xp); /** * @return a reference to this character's current experience point value */ - public ReferenceFacade getXPRef(); + ReferenceFacade getXPRef(); /** * Adjust the character's current experience point value * @param xp The value to be added to the character's current experience point value */ - public void adjustXP(int xp); + void adjustXP(int xp); /** * @return A reference to the XP total that will qualify the character for the next level */ - public ReferenceFacade getXPForNextLevelRef(); + ReferenceFacade getXPForNextLevelRef(); /** * Set the character's XP table. * * * @param xpTableName The name of the XP table to be set */ - public void setXPTable(String xpTableName); + void setXPTable(String xpTableName); /** * Set the character's character type. * * * @param characterType The character type to be set */ - public void setCharacterType(String characterType); + void setCharacterType(String characterType); /** * Set the character's associated preview sheet * * * @param previewSheet The preview sheet to be set */ - public void setPreviewSheet(String previewSheet); + void setPreviewSheet(String previewSheet); /** * Set the character's display filter for skills * * * @param filter The skill filter to be set */ - public void setSkillFilter(SkillFilter filter); + void setSkillFilter(SkillFilter filter); /** * @return A reference to the name of the character's XP table */ - public ReferenceFacade getXPTableNameRef(); + ReferenceFacade getXPTableNameRef(); /** * @return A reference to the name of the character's type */ - public ReferenceFacade getCharacterTypeRef(); + ReferenceFacade getCharacterTypeRef(); /** - * @return A reference to the name of the character's + * @return A reference to the name of the character's * associated preview sheet */ - public ReferenceFacade getPreviewSheetRef(); + ReferenceFacade getPreviewSheetRef(); /** - * @return A reference to the character's display filter + * @return A reference to the character's display filter * for skills */ - public ReferenceFacade getSkillFilterRef(); + ReferenceFacade getSkillFilterRef(); /** * Set the character's age in years. * @param age The new age to be set. */ - public void setAge(int age); + void setAge(int age); /** * @return A reference to the age of the character */ - public ReferenceFacade getAgeRef(); + ReferenceFacade getAgeRef(); /** - * @return A list of the defined age categories. + * @return A list of the defined age categories. */ - public ListFacade getAgeCategories(); + ListFacade getAgeCategories(); /** - * Set the character's age category. Will also reset their age if the age category + * Set the character's age category. Will also reset their age if the age category * has changed. * @param ageCat The new age category to be set */ - public void setAgeCategory(String ageCat); + void setAgeCategory(String ageCat); /** * @return A reference to the age category of the character. */ - public ReferenceFacade getAgeCategoryRef(); + ReferenceFacade getAgeCategoryRef(); /** - * @return A reference to the label text for the character's stats total + * @return A reference to the label text for the character's stats total */ - public ReferenceFacade getStatTotalLabelTextRef(); + ReferenceFacade getStatTotalLabelTextRef(); /** - * @return A reference to the text for the character's stats total + * @return A reference to the text for the character's stats total */ - public ReferenceFacade getStatTotalTextRef(); + ReferenceFacade getStatTotalTextRef(); /** * @return A reference to the label text for the character's modifier total */ - public ReferenceFacade getModTotalLabelTextRef(); + ReferenceFacade getModTotalLabelTextRef(); /** * @return A reference to the text for the character's modifier total */ - public ReferenceFacade getModTotalTextRef(); + ReferenceFacade getModTotalTextRef(); /** * @return A list of things to be done for the character */ - public ListFacade getTodoList(); + ListFacade getTodoList(); /** * Roll a new set of ability scores for the character. */ - public void rollStats(); + void rollStats(); /** - * @return true If the current stat generation method supports randomly rolling stats. + * @return true If the current stat generation method supports randomly rolling stats. */ - public boolean isStatRollEnabled(); + boolean isStatRollEnabled(); - public ReferenceFacade getTotalHPRef(); + ReferenceFacade getTotalHPRef(); - public ReferenceFacade getCarriedWeightRef(); + ReferenceFacade getCarriedWeightRef(); - public ReferenceFacade getLoadRef(); + ReferenceFacade getLoadRef(); - public ReferenceFacade getWeightLimitRef(); + ReferenceFacade getWeightLimitRef(); /** - * @return A reference to the stat roll method for the character + * @return A reference to the stat roll method for the character */ - public ReferenceFacade getRollMethodRef(); + ReferenceFacade getRollMethodRef(); /** - * Notify that the roll method may have changed. + * Notify that the roll method may have changed. */ - public void refreshRollMethod(); + void refreshRollMethod(); /** * Check if the character meets all requirements to be of the object. * @param infoFacade The object to be checked. * @return True if the character qualifies for the object, false if not. */ - public boolean isQualifiedFor(InfoFacade infoFacade); + boolean isQualifiedFor(InfoFacade infoFacade); /** * Check if the character meets all requirements to be of the race. * @param race The race to be checked. * @return True if the character qualifies for the race, false if not. */ - public boolean isQualifiedFor(Race race); + boolean isQualifiedFor(Race race); /** * Check if the character meets all requirements to take the domain. * @param domain The domain to be checked. * @return True if the character can take the domain, false if not. */ - public boolean isQualifiedFor(QualifiedObject domain); + boolean isQualifiedFor(QualifiedObject domain); /** * Check if the character meets all requirements to take the deity. * @param deity The deity to be checked. * @return True if the character can take the deity, false if not. */ - public boolean isQualifiedFor(Deity deity); + boolean isQualifiedFor(Deity deity); /** * Check if the character meets all requirements to take the temporary bonus. * @param tempBonusFacade The temporary bonus to be checked. * @return True if the character can take the bonus, false if not. */ - public boolean isQualifiedFor(TempBonusFacade tempBonusFacade); + boolean isQualifiedFor(TempBonusFacade tempBonusFacade); /** * Check if the character meets all requirements to know the spell. @@ -649,7 +649,7 @@ public interface CharacterFacade extends CompanionFacade * @param pcClass The class the spell would be added within. * @return True if the character can know the spell, false if not. */ - public boolean isQualifiedFor(SpellFacade spell, PCClass pcClass); + boolean isQualifiedFor(SpellFacade spell, PCClass pcClass); /** * Is the modifier able to be added to the item of equipment? @@ -657,9 +657,9 @@ public interface CharacterFacade extends CompanionFacade * @param eqMod The equipment modifier to be checked. * @return True if it can be added, false if not. */ - public boolean isQualifiedFor(EquipmentFacade equipFacade, EquipmentModifier eqMod); + boolean isQualifiedFor(EquipmentFacade equipFacade, EquipmentModifier eqMod); - public Nature getAbilityNature(AbilityFacade ability); + Nature getAbilityNature(AbilityFacade ability); // // /** // * @param category the category of the ability @@ -668,18 +668,18 @@ public interface CharacterFacade extends CompanionFacade // */ // public String getAbilityChoiceDisplayString(AbilityCategoryFacade category, AbilityFacade ability); - public SpellSupportFacade getSpellSupport(); + SpellSupportFacade getSpellSupport(); /** * @return a reference to the character's full portrait image */ - public ReferenceFacade getPortraitRef(); + ReferenceFacade getPortraitRef(); /** * Sets the file containing the portrait image * @param file a File containing the portrait image */ - public void setPortrait(File file); + void setPortrait(File file); /** * The thumbnail cropping rectangle is used to indicate the area @@ -688,168 +688,168 @@ public interface CharacterFacade extends CompanionFacade * reference. * @return a reference to the cropping rectangle for the thumbnail */ - public ReferenceFacade getThumbnailCropRef(); + ReferenceFacade getThumbnailCropRef(); - public void setThumbnailCrop(Rectangle rect); + void setThumbnailCrop(Rectangle rect); /** * @return a reference to this character's skin color. */ - public ReferenceFacade getSkinColorRef(); + ReferenceFacade getSkinColorRef(); /** * @param color the skin color to set. */ - public void setSkinColor(String color); + void setSkinColor(String color); /** * @return a reference to this character's hair color. */ - public ReferenceFacade getHairColorRef(); + ReferenceFacade getHairColorRef(); /** * @param color the hair color to set. */ - public void setHairColor(String color); + void setHairColor(String color); /** * @return a reference to this character's eye color. */ - public ReferenceFacade getEyeColorRef(); + ReferenceFacade getEyeColorRef(); /** * @param color the eye color to set. */ - public void setEyeColor(String color); + void setEyeColor(String color); /** * @return a reference to this character's weight. */ - public ReferenceFacade getWeightRef(); + ReferenceFacade getWeightRef(); /** * @param weight the weight to set. */ - public void setWeight(int weight); + void setWeight(int weight); /** - * Register a listener to be advised of potential changes in the number of - * selections for an ability category. + * Register a listener to be advised of potential changes in the number of + * selections for an ability category. * @param listener The class to be advised of a change. */ - public void addAbilityCatSelectionListener(ChangeListener listener); + void addAbilityCatSelectionListener(ChangeListener listener); /** * Deregister a listener that should no longer be advised of potential changes - * in the number of selections for an ability category. + * in the number of selections for an ability category. * @param listener The class to no longer be advised of a change. */ - public void removeAbilityCatSelectionListener(ChangeListener listener); + void removeAbilityCatSelectionListener(ChangeListener listener); /** * @return true if the character has been changed and needs to be saved. */ - public boolean isDirty(); + boolean isDirty(); /** - * @return The kits that have been applied to the character + * @return The kits that have been applied to the character */ - public DefaultListFacade getKits(); + DefaultListFacade getKits(); /** - * Add a kit to the character. This will test the kit is valid and warn the - * user if there are potential errors before applying the kit. + * Add a kit to the character. This will test the kit is valid and warn the + * user if there are potential errors before applying the kit. * @param object The kit to be added */ - public void addKit(Kit object); + void addKit(Kit object); /** * @return The list of kits currently available to the character. */ - public List getAvailableKits(); + List getAvailableKits(); /** * Record the default output sheet for this character. * @param pdf Is this the PDF sheet? * @param outputSheet The new default. */ - public void setDefaultOutputSheet(boolean pdf, File outputSheet); + void setDefaultOutputSheet(boolean pdf, File outputSheet); /** * Return the default output sheet for this character. * @param pdf Is this the PDF sheet? * @return The default output sheet. */ - public String getDefaultOutputSheet(boolean pdf); + String getDefaultOutputSheet(boolean pdf); - public CompanionSupportFacade getCompanionSupport(); + CompanionSupportFacade getCompanionSupport(); /** * @return a character stub representing this character's master */ - public CharacterStubFacade getMaster(); + CharacterStubFacade getMaster(); /** * @return the type of companion the current character is, or null if not a companion */ @Override - public String getCompanionType(); + String getCompanionType(); /** * @return the variable processor for the current character */ - public VariableProcessor getVariableProcessor(); + VariableProcessor getVariableProcessor(); /** * @return calculate a variable for the current character */ - public Float getVariable(String variableString, boolean isMax); + Float getVariable(String variableString, boolean isMax); /** * Advise the character facade that it is being closed. */ - public void closeCharacter(); + void closeCharacter(); /** * Identify if this character facade is a facade for the supplied character. * @param pc The character to check for. * @return True if this is a facade for the supplied character, false otherwise. */ - public boolean matchesCharacter(PlayerCharacter pc); + boolean matchesCharacter(PlayerCharacter pc); /** - * Modify the number of charges of the items of equipment. + * Modify the number of charges of the items of equipment. * @param targets The equipment to be updated. */ - public void modifyCharges(List targets); + void modifyCharges(List targets); /** * Delete the custom equipment item, ignored if the equip is not custom. * @param equip The equipment item to be deleted. */ - public void deleteCustomEquipment(EquipmentFacade equip); + void deleteCustomEquipment(EquipmentFacade equip); /** - * Modify the user-defined notes for the items of equipment. + * Modify the user-defined notes for the items of equipment. * @param targets The equipment to be updated. */ - public void addNote(List targets); + void addNote(List targets); - public List getCoreViewTree(CorePerspective pers); + List getCoreViewTree(CorePerspective pers); CharID getCharID(); - public boolean isQualifiedFor(PCTemplate element); + boolean isQualifiedFor(PCTemplate element); - public boolean isQualifiedFor(Kit element); + boolean isQualifiedFor(Kit element); /** * Return true if the feature with the given name is enabled for this PC; false * otherwise. */ - public boolean isFeatureEnabled(String feature); + boolean isFeatureEnabled(String feature); - public String getPreviewSheetVar(String key); + String getPreviewSheetVar(String key); - public void addPreviewSheetVar(String key, String value); + void addPreviewSheetVar(String key, String value); } diff --git a/code/src/java/pcgen/facade/core/SourceSelectionFacade.java b/code/src/java/pcgen/facade/core/SourceSelectionFacade.java index c8090a781f4..9dadce83005 100644 --- a/code/src/java/pcgen/facade/core/SourceSelectionFacade.java +++ b/code/src/java/pcgen/facade/core/SourceSelectionFacade.java @@ -1,20 +1,20 @@ /* * Copyright 2010 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * + * */ package pcgen.facade.core; @@ -27,13 +27,11 @@ public interface SourceSelectionFacade extends LoadableFacade { + ListFacade getCampaigns(); - public ListFacade getCampaigns(); + ReferenceFacade getGameMode(); - public ReferenceFacade getGameMode(); - - public void setCampaigns(List campaign); - - public void setGameMode(GameMode gameMode); + void setCampaigns(List campaign); + void setGameMode(GameMode gameMode); } diff --git a/code/src/java/pcgen/facade/util/ReferenceFacade.java b/code/src/java/pcgen/facade/util/ReferenceFacade.java index e0b453f843b..52ae962cfeb 100644 --- a/code/src/java/pcgen/facade/util/ReferenceFacade.java +++ b/code/src/java/pcgen/facade/util/ReferenceFacade.java @@ -1,20 +1,20 @@ /* * Copyright 2010 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * + * */ package pcgen.facade.util; @@ -30,9 +30,7 @@ */ public interface ReferenceFacade extends Supplier { - void addReferenceListener(ReferenceListener listener); void removeReferenceListener(ReferenceListener listener); - -} + } diff --git a/code/src/java/pcgen/gui2/PCGenFrame.java b/code/src/java/pcgen/gui2/PCGenFrame.java index 684e56e56b9..2160dee417e 100644 --- a/code/src/java/pcgen/gui2/PCGenFrame.java +++ b/code/src/java/pcgen/gui2/PCGenFrame.java @@ -1,20 +1,20 @@ /* * Copyright 2008 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * + * */ package pcgen.gui2; @@ -117,7 +117,7 @@ /** * The main window for PCGen. In addition, this class is responsible for providing - * global UI functions such as message dialogs. + * global UI functions such as message dialogs. */ public final class PCGenFrame extends JFrame implements UIDelegate, CharacterSelectionListener { @@ -263,7 +263,7 @@ public void run() } /** - * If the preference to auto load sources at start is set, find the + * If the preference to auto load sources at start is set, find the * sources that were last loaded and load them now. * @return true if the sources have been loaded, false if not. * @throws InterruptedException If the load was interrupted. @@ -460,7 +460,7 @@ public PCGenStatusBar getStatusBar() } /** - * Unload any currently loaded sources. + * Unload any currently loaded sources. */ public void unloadSources() { @@ -594,8 +594,8 @@ public boolean reallySaveCharacter(CharacterFacade character) } /** - * Prepare the character for a save. This is primarily concerned with - * ensuring all companions (or masters) have file names before the save is + * Prepare the character for a save. This is primarily concerned with + * ensuring all companions (or masters) have file names before the save is * done. * @param character The character being saved. */ @@ -1258,7 +1258,7 @@ private void updateTitle() String sourceName = null; if (currentCharacterRef != null && currentCharacterRef.get() != null) { - // characterFileName The file name (without path) of the active character + // characterFileName The file name (without path) of the active character // sourceName The name of the source selection. characterFile = currentCharacterRef.get().getFileRef().get(); @@ -1464,7 +1464,7 @@ public void showLevelUpInfo(CharacterFacade character, int oldLevel) @Override public boolean showGeneralChooser(ChooserFacade chooserFacade) { - // Check for an override of the chooser to be used + // Check for an override of the chooser to be used Optional choiceHandler = ChooserFactory.getChoiceHandler(); if (choiceHandler.isPresent()) { diff --git a/code/src/java/pcgen/gui2/facade/CharacterFacadeImpl.java b/code/src/java/pcgen/gui2/facade/CharacterFacadeImpl.java index 58017c3f13f..f6023ad531a 100644 --- a/code/src/java/pcgen/gui2/facade/CharacterFacadeImpl.java +++ b/code/src/java/pcgen/gui2/facade/CharacterFacadeImpl.java @@ -173,8 +173,8 @@ /** * The Class {@code CharacterFacadeImpl} is an implementation of - * the {@link CharacterFacade} interface for the new user interface. It is - * intended to provide a full implementation of the new ui/core + * the {@link CharacterFacade} interface for the new user interface. It is + * intended to provide a full implementation of the new ui/core * interaction layer. * TODO: Who is responsible for undo management and how will it work? */ @@ -265,7 +265,7 @@ public class CharacterFacadeImpl /** * Create a new character facade for an existing character. - * + * * @param pc The character to be represented * @param delegate the UIDelegate for this CharacterFacade * @param dataSetFacade The data set in use for the character @@ -432,6 +432,7 @@ private void initForCharacter() initTodoList(); + poolPointText = new DefaultReferenceFacade<>(); statTotalLabelText = new DefaultReferenceFacade<>(); statTotalText = new DefaultReferenceFacade<>(); modTotalLabelText = new DefaultReferenceFacade<>(); @@ -487,8 +488,8 @@ private GearBuySellFacade findGearBuySellRate() } /** - * Initialize the equipment set facades, ensuring that the character has a - * default equipment set. + * Initialize the equipment set facades, ensuring that the character has a + * default equipment set. */ private void initEquipSet() { @@ -540,7 +541,7 @@ private void initEquipSet() } /** - * Create the list of known age categories in the current BioSet. + * Create the list of known age categories in the current BioSet. */ private void buildAgeCategories() { @@ -568,7 +569,7 @@ private void buildAgeCategories() } /** - * Create an initial list of todo items + * Create an initial list of todo items */ private void initTodoList() { @@ -679,7 +680,7 @@ public void setRemainingSelection(AbilityCategory category, int remaining) @Override public Nature getAbilityNature(AbilityFacade ability) { - if (ability == null || !(ability instanceof Ability)) + if (!(ability instanceof Ability)) { return null; } @@ -802,7 +803,7 @@ public void removeCharacterLevels(int levels) charLevelsFacade.removeLastLevel(); } - // Clean up the class list + // Clean up the class list for (Iterator iterator = pcClasses.iterator(); iterator.hasNext();) { PCClass pcClass = iterator.next(); @@ -1115,7 +1116,7 @@ private void buildAppliedTempBonusList() @Override public void addTempBonus(TempBonusFacade bonusFacade) { - if (bonusFacade == null || !(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) + if (!(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) { return; } @@ -1153,7 +1154,7 @@ public void addTempBonus(TempBonusFacade bonusFacade) @Override public void removeTempBonus(TempBonusFacade bonusFacade) { - if (bonusFacade == null || !(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) + if (!(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) { return; } @@ -1174,7 +1175,7 @@ public void removeTempBonus(TempBonusFacade bonusFacade) @Override public void setTempBonusActive(TempBonusFacade bonusFacade, boolean active) { - if (bonusFacade == null || !(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) + if (!(bonusFacade instanceof TempBonusFacadeImpl tempBonus)) { return; } @@ -1218,10 +1219,10 @@ public void setAlignment(PCAlignment alignment) } /** - * Validate the new alignment matches those allowed for the character's - * classes. If not offer the user a choice of backing out or making the + * Validate the new alignment matches those allowed for the character's + * classes. If not offer the user a choice of backing out or making the * classes into ex-classes. - * + * * @param newAlign The alignment to be set */ private boolean validateAlignmentChange(PCAlignment newAlign) @@ -1248,7 +1249,7 @@ private boolean validateAlignmentChange(PCAlignment newAlign) { if (aClass.containsKey(ObjectKey.EX_CLASS)) { - if (unqualified.length() > 0) + if (!unqualified.isEmpty()) { unqualified.append(", "); //$NON-NLS-1$ } @@ -1263,7 +1264,7 @@ private boolean validateAlignmentChange(PCAlignment newAlign) // // Give the user a chance to bail // - if (unqualified.length() > 0) + if (!unqualified.isEmpty()) { if (!delegate.showWarningConfirm(Constants.APPLICATION_NAME, LanguageBundle.getString("in_sumExClassesWarning") + Constants.LINE_SEPARATOR + unqualified)) @@ -1522,7 +1523,7 @@ else if (poolMod < 0) /** * Assess if the new score is valid for the stat. - * + * * @param score The new score being checked. * @param pcStat The stats being checked * @param pcPlayerLevels The number of non monster levels the character currently has. @@ -1607,7 +1608,7 @@ public boolean isStatRollEnabled() } /** - * Update the + * Update the */ private void showPointPool() { @@ -1993,10 +1994,10 @@ private void buildAvailableDomainsList() /** * Check if a domain is a list of domains, irrespective of prerequisites. - * + * * @param qualDomainList The list of domains with their prerequisites. * @param domain The domain to search for. - * @return true if the domain is in the list + * @return true if the domain is in the list */ private boolean isDomainInList(List> qualDomainList, Domain domain) { @@ -2199,8 +2200,8 @@ public void removeLanguage(Language lang) } /** - * Identify the object that the language is associated with. i.e. The rules - * object that granted the ability to use the language. + * Identify the object that the language is associated with. i.e. The rules + * object that granted the ability to use the language. * @param lang The language to be found. * @return The granting rules object, or null if none or automatic. */ @@ -2226,6 +2227,11 @@ public ReferenceFacade getFileRef() @Override public void setFile(File file) { + if (file == null) + { + throw new IllegalArgumentException("Cannot set a null as a character's file"); + } + this.file.set(file); try { @@ -2239,10 +2245,10 @@ public void setFile(File file) } /** - * Retrieve a copy of the current character suitable for export. This - * attempts to minimize the expensive cloning function, by returning the - * previously cloned character if the base character has not changed in - * the meantime. + * Retrieve a copy of the current character suitable for export. This + * attempts to minimize the expensive cloning function, by returning the + * previously cloned character if the base character has not changed in + * the meantime. * @return A copy of the current character. */ private synchronized PlayerCharacter getExportCharacter() @@ -2414,8 +2420,8 @@ public UIDelegate getUIDelegate() } /** - * Save the character to disc using its filename. Note this method is not - * part of the CharacterFacade and should only be used by the + * Save the character to disc using its filename. Note this method is not + * part of the CharacterFacade and should only be used by the * ChracterManager class. */ public void save() @@ -2641,9 +2647,9 @@ public ReferenceFacade getAgeCategoryRef() } /** - * This method updates the purchase point pool and the stat total text. The - * stat total text will be updated whether we are in purchase mode or not. - * displayed + * This method updates the purchase point pool and the stat total text. The + * stat total text will be updated whether we are in purchase mode or not. + * displayed * @param checkPurchasePoints boolean true if the pool should be checked * for available points before doing the update. */ @@ -2734,8 +2740,8 @@ private void updateScorePurchasePool(boolean checkPurchasePoints) } /** - * Identify if the character can still change purchase pool values - spent - * or available. This action is restricted by level. + * Identify if the character can still change purchase pool values - spent + * or available. This action is restricted by level. * @return true if the character is allowed to change the purchase pool */ public boolean canChangePurchasePool() @@ -2842,9 +2848,9 @@ public void refreshRollMethod() } /** - * Reset the stat score to the neutral value (usually 10) for + * Reset the stat score to the neutral value (usually 10) for * the point buy method. - * + * * @param pcStat The stat being adjusted. * @param scoreRef The reference to the current score. */ @@ -3146,8 +3152,7 @@ public void removePurchasedEquipment(EquipmentFacade equipment, int quantity, bo // Update the PC and equipment if (!free) { - @SuppressWarnings("PMD.AvoidDecimalLiteralsInBigDecimalConstructor") - BigDecimal removed = new BigDecimal(numRemoved); + BigDecimal removed = BigDecimal.valueOf(numRemoved); BigDecimal itemCost = calcItemCost(updatedItem, removed.negate(), (GearBuySellScheme) gearBuySellSchemeRef.get()); BigDecimal currentGold = @@ -3164,7 +3169,7 @@ public void removePurchasedEquipment(EquipmentFacade equipment, int quantity, bo @Override public void deleteCustomEquipment(EquipmentFacade eqFacade) { - if (eqFacade == null || !(eqFacade instanceof Equipment itemToBeDeleted)) + if (!(eqFacade instanceof Equipment itemToBeDeleted)) { return; } @@ -3267,7 +3272,7 @@ public EquipmentFacade getEquipmentSizedForCharacter(EquipmentFacade equipment) } /** - * Whether we should automatically resize all purchased gear to match the + * Whether we should automatically resize all purchased gear to match the * character's size. * @return true if equipment should be auto resize. */ @@ -3278,9 +3283,9 @@ public boolean isAutoResize() } /** - * Update whether we should automatically resize all purchased gear to match + * Update whether we should automatically resize all purchased gear to match * the character's size. - * + * * @param autoResize The new value for auto resize equipment option. */ @Override @@ -3305,7 +3310,7 @@ public EquipmentSetFacade createEquipmentSet(String setName) @Override public void deleteEquipmentSet(EquipmentSetFacade set) { - if (set == null || !(set instanceof EquipmentSetFacadeImpl setImpl)) + if (!(set instanceof EquipmentSetFacadeImpl setImpl)) { return; } @@ -3364,7 +3369,7 @@ public void elementModified(ListEvent e) } /** - * Refreshes the total weight by reading it from the current equipment set. + * Refreshes the total weight by reading it from the current equipment set. */ private void refreshTotalWeight() { @@ -3751,9 +3756,9 @@ private void refreshEquipment() } /** - * Show the user any warnings from thekit application and get + * Show the user any warnings from thekit application and get * their approval to continue. - * + * * @param kit The kit being applied. * @param warnings The warnings generated in the test application. * @return true if the kit should be applied, false if not. @@ -3825,9 +3830,9 @@ public void modifyCharges(List targets) List chargedEquip = new ArrayList<>(); for (EquipmentFacade equipmentFacade : targets) { - if (equipmentFacade instanceof Equipment && ((Equipment) equipmentFacade).getMaxCharges() > 0) + if (equipmentFacade instanceof Equipment equipment && equipment.getMaxCharges() > 0) { - chargedEquip.add((Equipment) equipmentFacade); + chargedEquip.add(equipment); } } @@ -3888,9 +3893,9 @@ public void addNote(List targets) List notedEquip = new ArrayList<>(); for (EquipmentFacade equipmentFacade : targets) { - if (equipmentFacade instanceof Equipment) + if (equipmentFacade instanceof Equipment equipment) { - notedEquip.add((Equipment) equipmentFacade); + notedEquip.add(equipment); } } @@ -3999,7 +4004,7 @@ public void dataRemoved(DataFacetChangeEvent dfce) } /** - * The Class {@code AutoEquipListener} tracks changes to the character's + * The Class {@code AutoEquipListener} tracks changes to the character's * automatically granted equipment. */ public class AutoEquipListener implements DataFacetChangeListener>> diff --git a/code/src/java/pcgen/system/CharacterManager.java b/code/src/java/pcgen/system/CharacterManager.java index e19c4906ecf..00364971c85 100644 --- a/code/src/java/pcgen/system/CharacterManager.java +++ b/code/src/java/pcgen/system/CharacterManager.java @@ -1,16 +1,16 @@ /* * Copyright 2010 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA @@ -95,7 +95,7 @@ public static CharacterFacade createNewCharacter(UIDelegate delegate, DataSetFac String name = createNewCharacterName(); character.setName(name); CHARACTERS.addElement(character); - Logging.log(Logging.INFO, "Created new character " + name + '.'); //$NON-NLS-1$ + Logging.log(Logging.INFO, "Created new character " + name + '.'); //$NON-NLS-1$ MESSAGE_HANDLER.handleMessage(new PlayerCharacterWasLoadedMessage(delegate, pc)); return character; } @@ -223,10 +223,10 @@ private static CharacterFacade createChracterFacade(UIDelegate delegate, DataSet } /** - * Show the user any warnings or errors from the character load and get + * Show the user any warnings or errors from the character load and get * their approval to continue. - * - * @param errors Is this a list of errors? + * + * @param errors Is this a list of errors? * @param warnings The warnings generated on load. * @param fileName The name of the file being loaded. * @param delegate The UIDelegate to use for notifications. @@ -275,7 +275,7 @@ private static boolean showLoadNotices(boolean errors, List warnings, St /** * This opens an existing party from a file and adds all characters to the * list of open characters. - * + * * @param file the file to load this party from * @param delegate the UIDelegate that these characters will use * @param dataset the dataset that this will be loaded with @@ -328,7 +328,7 @@ else if (gameMode != game) } /** - * + * * @param pcgFile a character file * @param delegate The UIDelegate used to display message to the user * @return a SourceSelectionFacade or null if no sources could be found @@ -354,7 +354,7 @@ public static SourceSelectionFacade getRequiredSourcesForCharacter(File pcgFile, } /** - * Check if the character's filename is ready to be saved to. + * Check if the character's filename is ready to be saved to. * @param character The character to be checked. * @return true if the file can be written to, false otherwise. */ @@ -379,7 +379,7 @@ public static boolean characterFilenameValid(CharacterFacade character) * This is expected to be called before a character is to * be removed from the list of open characters. * @param character the character to be saved - * @return true if the save succeeded, false if not + * @return true if the save succeeded, false if not */ public static boolean saveCharacter(CharacterFacade character) { @@ -392,12 +392,12 @@ public static boolean saveCharacter(CharacterFacade character) Logging.log(Logging.INFO, "Saving character " + character.getNameRef().get() //$NON-NLS-1$ + " - " + file.getAbsolutePath()); //$NON-NLS-1$ - if (character instanceof CharacterFacadeImpl) + if (character instanceof CharacterFacadeImpl characterFacade) { UIDelegate delegate = character.getUIDelegate(); try { - ((CharacterFacadeImpl) character).save(); + characterFacade.save(); } catch (final NullPointerException e) { @@ -471,11 +471,11 @@ public static PartyFacade getCharacters() } /** - * Retrieve the loaded character matching the character stub. The character - * may not have been saved yet, so may not have a file name, in which case - * the match is made on character name. This is often used for retrieval of - * a loaded master or companion. - * + * Retrieve the loaded character matching the character stub. The character + * may not have been saved yet, so may not have a file name, in which case + * the match is made on character name. This is often used for retrieval of + * a loaded master or companion. + * * @param companion The companion to be searched for. * @return The character, or null if the companion is not loaded. */ diff --git a/code/src/java/pcgen/system/FacadeFactory.java b/code/src/java/pcgen/system/FacadeFactory.java index ad127234a48..c35228994e1 100644 --- a/code/src/java/pcgen/system/FacadeFactory.java +++ b/code/src/java/pcgen/system/FacadeFactory.java @@ -24,7 +24,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.StreamSupport; import pcgen.cdom.base.CDOMObject; import pcgen.cdom.enumeration.ObjectKey; @@ -101,7 +103,7 @@ private static void initCampaigns() DefaultListFacade campaignList = campaignListMap.get(gameMode); if (campaignList.containsElement(campaign)) { - String sourceUri = ((CDOMObject) campaign).getSourceURI().toString(); + String sourceUri = campaign.getSourceURI().toString(); Logging .errorPrint("Campaign " + sourceUri + " lists GAMEMODE:" + gameMode + " multiple times."); } @@ -110,7 +112,7 @@ private static void initCampaigns() campaignList.addElement(campaign); } } - if (campaign.getSafe(ObjectKey.SHOW_IN_MENU) && !gameModeList.isEmpty()) + if (Boolean.TRUE.equals(campaign.getSafe(ObjectKey.SHOW_IN_MENU)) && !gameModeList.isEmpty()) { GameMode game = gameModeList.getElementAt(0); ListFacade list = new DefaultListFacade<>(Collections.singleton(campaign)); @@ -128,7 +130,7 @@ private static void initGameModes(List modes) { title = mode.getName(); } - if (title != null && !"".equals(title)) + if (title != null && !title.isEmpty()) { DefaultListFacade qcamps = new DefaultListFacade<>(); List sources = mode.getDefaultDataSetList(); @@ -165,13 +167,8 @@ private static void initDisplayedSources() private static void initCustomSourceSelections() { - String[] keys = SOURCES_CONTEXT.getStringArray("selectionNames"); - if (keys == null) - { - return; - } - for (String name : keys) - { + var keys = SOURCES_CONTEXT.getStringList("selectionNames"); + keys.forEach(name -> { PropertyContext context = SOURCES_CONTEXT.createChildContext(name); String modeName = context.getProperty("gamemode"); GameMode mode = SystemCollections.getGameModeNamed(modeName); @@ -179,41 +176,36 @@ private static void initCustomSourceSelections() { Logging .errorPrint("Unable to load quick source '" + name + "'. Game mode '" + modeName + "' is missing"); - continue; - } - String[] selectionArray = context.getStringArray("campaigns"); - List sources = new ArrayList<>(); - boolean error = false; - for (String campaign : selectionArray) - { - Campaign c = campaignMap.get(campaign); - if (c != null) - { - sources.add(c); - } - else - { - error = true; - Logging.log(Logging.WARNING, '\'' + campaign + '\'' + " campaign not found, custom quick source '" - + name + "' might not work correctly."); - } + return; } + var selectionList = context.getStringList("campaigns"); + + var groupedCampaigns = selectionList.stream() + .collect(Collectors.partitioningBy(campaignMap::containsKey)); + var availableCampaigns = groupedCampaigns.getOrDefault(true, Collections.emptyList()); + var absentCampaigns = groupedCampaigns.getOrDefault(false, Collections.emptyList()); + absentCampaigns.forEach(campaign -> + Logging.log(Logging.WARNING, '\'' + campaign + '\'' + " campaign not found, custom quick source '" + name + "' might not work correctly.")); + + List sources = availableCampaigns.stream() + .map(campaignMap::get) + .toList(); if (sources.isEmpty()) { Logging.errorPrint("Unable to load quick source '" + name + "'. All of its sources are missing"); - continue; + return; } CustomSourceSelectionFacade selection = new CustomSourceSelectionFacade(name); selection.setGameMode(mode); selection.setCampaigns(sources); - if (error) + if (!absentCampaigns.isEmpty()) { selection.setLoadingState(LoadingState.LOADED_WITH_ERRORS); selection.setErrorMessage("Some campaigns are missing"); } customSources.addElement(selection); quickSources.addElement(selection); - } + }); } public static SourceSelectionFacade createCustomSourceSelection(String name) @@ -243,12 +235,10 @@ public static void deleteCustomSourceSelection(SourceSelectionFacade source) private static void setCustomSourceSelectionArray() { - List sources = new ArrayList<>(); - for (SourceSelectionFacade csel : customSources) - { - sources.add(csel.toString()); - } - SOURCES_CONTEXT.setStringArray("selectionNames", sources); + var sources = StreamSupport.stream(customSources.spliterator(), false) + .map(Object::toString) + .toList(); + SOURCES_CONTEXT.setStringList("selectionNames", sources); } public static SourceSelectionFacade createSourceSelection(GameMode gameMode, @@ -436,12 +426,10 @@ public boolean isModifiable() public void setCampaigns(List campaign) { campaigns.setContents(campaign); - List camps = new ArrayList<>(); - for (Campaign camp : campaign) - { - camps.add(camp.getKeyName()); - } - context.setStringArray("campaigns", camps); + var camps = campaign.stream() + .map(CDOMObject::getKeyName) + .toList(); + context.setStringList("campaigns", camps); } @Override diff --git a/code/src/java/pcgen/system/PropertyContext.java b/code/src/java/pcgen/system/PropertyContext.java index e9d1a8aab35..5075890cf06 100644 --- a/code/src/java/pcgen/system/PropertyContext.java +++ b/code/src/java/pcgen/system/PropertyContext.java @@ -1,42 +1,43 @@ /* * Copyright 2009 Connor Petty - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * + * */ package pcgen.system; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; +import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.Properties; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; /** - * This class acts similarly to the Properties class but behaves defferntly + * This class acts similarly to the Properties class but behaves differently * in that SubContexts can be created. These SubContexts share the properties - * of its parent but they use a different namespace than the parent when + * of its parent, but they use a different namespace than the parent when * a property is set. The root parent contains all the properties of its - * children and likewise, all of the properties of the children can be edited + * children, and likewise, all the properties of the children can be edited * from the root parent. In child contexts, the properties of all other children * that share its ancestors are visible but only that child's namespace is editable. - * It is considered bad practice to look at the other siblings properties from within + * It is considered bad practice to look at the other siblings' properties from within * a child. */ public class PropertyContext implements PropertyChangeListener @@ -62,10 +63,10 @@ protected PropertyContext(String name, PropertyContext parent) /** * Create a new PropertyContext with a supplied properties object. As - * the property object is supplied, it is expected that the parent will + * the property object is supplied, it is expected that the parent will * normally be null. - * - * @param name The filename of the context. Normally ends in .ini + * + * @param name The filename of the context. Normally ends in .ini * @param parent The parent context, normally null * @param properties The properties object to be used. */ @@ -134,7 +135,7 @@ public String initProperty(String key, String defaultValue) } /** - * Searches for the property with the specified key in this property context. + * Searches for the property with the specified key in this property context. * The method returns the default value argument if the property is not found. * * @param key the property key. @@ -184,47 +185,41 @@ Object removeProperty(String key) return oldValue; } - String[] getStringArray(String key) - { - String prop = getProperty(key); - if (prop == null) - { - return null; - } - return StringUtils.split(prop, ';'); - } - - String[] getStringArray(String key, String[] defaultValue) + /** + * Gets a property of the specified key as a list of String. If the list is not found, an empty list is returned. + * Note: This converts the string into a list by splitting it using ';' as a separator + * @param key the property key + * @return the value in this property context with the specified key value. + */ + List getStringList(String key) { - String prop = getProperty(key); - if (prop == null) - { - return defaultValue; - } - return StringUtils.split(prop, ';'); + return getStringList(key, Collections.emptyList()); } /** - * Sets property to the specified key to an array of Strings - * Note: This converts the string array into a single string - * by joining them using ';' as a separator - * @param key - * @param value + * Gets a property of the specified key as a list of String + * Note: This converts the string into a list by splitting it using ';' as a separator + * @param key the property key + * @param defaultValue the default value, if the key value is not found + * @return the value in this property context with the specified key value, or {@code defaultValue}. */ - private void setStringArray(String key, String[] value) + List getStringList(String key, List defaultValue) { - setProperty(key, StringUtils.join(value, ';')); + return Optional.ofNullable(getProperty(key)) + .map(prop -> Arrays.asList(prop.split(";"))) + .orElse(defaultValue); } /** - * Note: this is mearly shorthand for:
- * {@code setStringArray(key, value.toArray(ArrayUtils.EMPTY_STRING_ARRAY))} - * @param key the property key - * @param value a list of strings + * Sets property to the specified key to a list of String + * Note: This converts the string list into a single string + * by joining them using ';' as a separator + * @param key key the property key + * @param value the list of String, that will be stored into the property context */ - void setStringArray(String key, List value) + void setStringList(String key, List value) { - setStringArray(key, value.toArray(ArrayUtils.EMPTY_STRING_ARRAY)); + setProperty(key, String.join(";", value)); } public int getInt(String key) @@ -274,16 +269,16 @@ public void propertyChange(PropertyChangeEvent evt) } /** - * Called after properties have been loaded to allow any required - * post-load processing to be performed. + * Called after properties have been loaded to allow any required + * post-load processing to be performed. */ protected void afterPropertiesLoaded() { } /** - * Called before properties are saved to allow any required - * pre-save processing to be performed. + * Called before properties are saved to allow any required + * pre-save processing to be performed. */ protected void beforePropertiesSaved() { diff --git a/code/src/java/pcgen/system/RecentFileList.java b/code/src/java/pcgen/system/RecentFileList.java index 7f77c1e5ec2..4cf90740b52 100644 --- a/code/src/java/pcgen/system/RecentFileList.java +++ b/code/src/java/pcgen/system/RecentFileList.java @@ -17,43 +17,44 @@ import java.io.File; import java.net.URI; -import java.util.ArrayList; +import java.util.Collections; import java.util.LinkedList; import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; import java.util.stream.IntStream; import pcgen.facade.util.AbstractListFacade; -import org.apache.commons.lang3.ArrayUtils; - class RecentFileList extends AbstractListFacade { - - private static final int MAX_RECENT_FILES = 8; - private final LinkedList fileList = new LinkedList<>(); + private static final int MAX_RECENT_FILES = 20; + private final List fileList = new LinkedList<>(); private final String contextProp; RecentFileList(String contextProp) { this.contextProp = contextProp; - String[] recentFiles = PCGenSettings.getInstance().getStringArray(contextProp); - if (!ArrayUtils.isEmpty(recentFiles)) - { - URI userdir = new File(ConfigurationSettings.getUserDir()).toURI(); - for (int i = recentFiles.length - 1; i >= 0; i--) - { - addRecentFile(new File(userdir.resolve(recentFiles[i]))); - } - } + + URI userDir = new File(ConfigurationSettings.getUserDir()).toURI(); + var recentFiles = PCGenSettings.getInstance().getStringList(contextProp); + recentFiles.stream() + .sorted(Collections.reverseOrder()) + .map(userDir::resolve) + .map(File::new) + .forEach(this::addRecentFile); } private void updateRecentFileProp() { - URI userdir = new File(ConfigurationSettings.getUserDir()).toURI(); + URI userDir = new File(ConfigurationSettings.getUserDir()).toURI(); - List uris = new ArrayList<>(fileList.size()); - fileList.stream().map(file -> userdir.relativize(file.toURI()).toString()).forEach(uris::add); - PCGenSettings.getInstance().setStringArray(contextProp, uris); + List uris = fileList.stream() + .map(File::toURI) + .map(userDir::relativize) + .map(URI::toString) + .toList(); + PCGenSettings.getInstance().setStringList(contextProp, uris); } void addRecentFile(File file) @@ -63,12 +64,11 @@ void addRecentFile(File file) return; } //Remove the file if it already exists, that way it gets moved to the top - int index = indexOf(file); - if (index != -1) - { + indexOf(file).ifPresent(index -> { File oldFile = fileList.remove(index); fireElementRemoved(this, oldFile, index); - } + }); + //add it to the front fileList.addFirst(file); fireElementAdded(this, file, 0); @@ -96,18 +96,15 @@ public int getSize() @Override public boolean containsElement(File element) { - return indexOf(element) != -1; + return indexOf(element).isPresent(); } - private int indexOf(File element) + private OptionalInt indexOf(File element) { - if (element != null) - { - return IntStream.range(0, fileList.size()) - .filter(i -> fileList.get(i).getAbsolutePath().equals(element.getAbsolutePath())).findFirst() - .orElse(-1); - } - return -1; + return Optional.ofNullable(element) + .map(e -> IntStream.range(0, fileList.size()) + .filter(i -> fileList.get(i).getAbsolutePath().equals(e.getAbsolutePath())) + .findFirst()) + .orElse(OptionalInt.empty()); } - } diff --git a/code/src/java/pcgen/util/Logging.java b/code/src/java/pcgen/util/Logging.java index 4050aba29cc..d3c390434a1 100644 --- a/code/src/java/pcgen/util/Logging.java +++ b/code/src/java/pcgen/util/Logging.java @@ -40,7 +40,7 @@ import org.apache.commons.lang3.SystemUtils; /** - * This contains logging functions. It is a proxy for the + * This contains logging functions. It is a proxy for the * Java logging API. */ @SuppressWarnings({"PMD.MoreThanOneLogger", "UseOfSystemOutOrSystemErr", "PMD.AvoidPrintStackTrace"}) @@ -90,7 +90,7 @@ public final class Logging } //System.out.println("Using log settings from " + propsFile.getAbsolutePath()); - // Get Java Logging to read in the config. + // Get Java Logging to read in the config. try { LogManager.getLogManager().readConfiguration(); @@ -129,7 +129,7 @@ public static void setDebugMode(final boolean argDebugMode) } /** - * Ensure that our root loggers (pcgen and plugin) do not get garbage + * Ensure that our root loggers (pcgen and plugin) do not get garbage * collected, otherwise we lose the logging level! */ private static void retainRootLoggers() @@ -149,8 +149,8 @@ public static boolean isDebugMode() } /** - * Check if the level of logs would be output for the caller. This can - * be used to prevent building logging output if it will not be used. + * Check if the level of logs would be output for the caller. This can + * be used to prevent building logging output if it will not be used. * @param level The logging level to be checked. * @return true if the level would be output, false if not. */ @@ -190,7 +190,7 @@ public static void debugPrint(final String param1, Object param2) } /** - * Print localised information message if PCGen is debugging. + * Print a localized information message if PCGen is debugging. * * @param message String information message (usually variable) * @param params Object information message (usually value) @@ -239,7 +239,7 @@ public static void errorPrintLocalised(final String aKey) *

* This method accepts a variable number of parameters and will replace * {@code {argno}} in the string with each passed paracter in turn. - * + * * @param aKey * A key for the localized string in the language bundle * @param varargs @@ -265,7 +265,7 @@ public static void deprecationPrint(final String s) * Beep and print error message if PCGen is debugging. * * @param s String error message - * @param context the LoadContext containing the deprecated resource + * @param context the LoadContext containing the deprecated resource */ public static void deprecationPrint(final String s, final LoadContext context) { @@ -286,7 +286,7 @@ public static void deprecationPrint(final String s, final LoadContext context) /** * Report where an issue was encountered. * - * @param context the LoadContext containing the resource + * @param context the LoadContext containing the resource */ public static void reportSource(final Level lvl, final LoadContext context) { @@ -307,7 +307,7 @@ public static void reportSource(final Level lvl, final LoadContext context) /** * Report where an issue was encountered. * - * @param sourceUri the source containing the resource + * @param sourceUri the source containing the resource */ public static void reportSource(final Level lvl, final URI sourceUri) { @@ -332,18 +332,14 @@ public static void reportSource(final Level lvl, final URI sourceUri) */ public static void errorPrint(final String s) { - Logger l = getLogger(); - if (l.isLoggable(ERROR)) - { - l.log(ERROR, s); - } + log(ERROR, s); } /** * Beep and print error message if PCGen is debugging. * * @param s String error message - * @param params Varargs list of parameters for substitution into the + * @param params Varargs list of parameters for substitution into the * error message. */ public static void errorPrint(final String s, final Object... params) @@ -415,9 +411,9 @@ public static void errorPrint(final String s, final Throwable thr) } /** - * Log a message, if logging is enabled at the - * supplied level of detail. - * + * Log a message if logging is enabled at the + * supplied level of detail. + * * @param lvl The detail level of the message * @param msg String message */ @@ -432,8 +428,8 @@ public static void log(final Level lvl, final String msg) /** * Log a message with a stack trace, if logging is enabled at the - * supplied level of detail. - * + * supplied level of detail. + * * @param lvl The detail level of the message * @param msg String message * @param thr Throwable stack frame @@ -449,9 +445,9 @@ public static void log(final Level lvl, final String msg, final Throwable thr) /** * Log a message with a stack trace, if logging is enabled at the - * supplied level of detail. + * supplied level of detail. * This is mainly for use with the pcgen.rules.persistence.token.ParseResult class. - * + * * @param lvl The detail level of the message * @param msg String message * @param stackTrace The stack trace @@ -507,10 +503,10 @@ private static String memoryReportStr() } /** - * Retrieve a Logger object with the specified name. Generally - * this name should be either the fully qualified class name, + * Retrieve a Logger object with the specified name. Generally + * this name should be either the fully qualified class name, * or the package name. - * + * * @return An instance of Logger that deals with the specified name. */ private static java.util.logging.Logger getLogger() @@ -545,7 +541,7 @@ private static java.util.logging.Logger getLogger() } /** - * List the current stack of all threads to STDOUT. + * List the current stack of all threads to STDOUT. */ public static void reportAllThreads() { @@ -586,7 +582,7 @@ public static void removeHandler(Handler handler) } /** - * Return a list of the supported logging levels in + * Return a list of the supported logging levels in * descending order of rank. * @return List of logging levels. */