diff options
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc/utils')
144 files changed, 2899 insertions, 3139 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/PropertyDB.java b/BJC-Utils2/src/main/java/bjc/utils/PropertyDB.java index daaf423..755d7e0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/PropertyDB.java +++ b/BJC-Utils2/src/main/java/bjc/utils/PropertyDB.java @@ -1,16 +1,16 @@ package bjc.utils; -import bjc.utils.funcutils.LambdaLock; -import bjc.utils.ioutils.SimpleProperties; - import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.regex.Pattern; +import bjc.utils.funcutils.LambdaLock; +import bjc.utils.ioutils.SimpleProperties; + /** * Database for storage of properties from external files. - * + * * @author EVE * */ @@ -33,30 +33,30 @@ public class PropertyDB { /** * Reload all the properties from their files. - * + * * NOTE: Any attempts to read from the property DB while properties are * being loaded will block, to prevent reads from partial states. */ public static void reloadProperties() { loadLock.write(() -> { - if(LOGLOAD) { + if (LOGLOAD) { System.out.println("Reading regex properties:"); } regexes = new SimpleProperties(); regexes.loadFrom(PropertyDB.class.getResourceAsStream("/regexes.sprop"), false); - if(LOGLOAD) { + if (LOGLOAD) { regexes.outputProperties(); System.out.println(); } compiledRegexes = new HashMap<>(); - if(LOGLOAD) { + if (LOGLOAD) { System.out.println("Reading format properties:"); } formats = new SimpleProperties(); formats.loadFrom(PropertyDB.class.getResourceAsStream("/formats.sprop"), false); - if(LOGLOAD) { + if (LOGLOAD) { formats.outputProperties(); System.out.println(); } @@ -65,16 +65,16 @@ public class PropertyDB { /** * Retrieve a persisted regular expression. - * + * * @param key * The name of the regular expression. - * + * * @return The regular expression with that name. */ - public static String getRegex(String key) { + public static String getRegex(final String key) { return loadLock.read(() -> { - if(!regexes.containsKey(key)) { - String msg = String.format("No regular expression named '%s' found", key); + if (!regexes.containsKey(key)) { + final String msg = String.format("No regular expression named '%s' found", key); throw new NoSuchElementException(msg); } @@ -86,16 +86,16 @@ public class PropertyDB { /** * Retrieve a persisted regular expression, compiled into a regular * expression. - * + * * @param key * The name of the regular expression. - * + * * @return The regular expression with that name. */ - public static Pattern getCompiledRegex(String key) { + public static Pattern getCompiledRegex(final String key) { return loadLock.read(() -> { - if(!regexes.containsKey(key)) { - String msg = String.format("No regular expression named '%s' found", key); + if (!regexes.containsKey(key)) { + final String msg = String.format("No regular expression named '%s' found", key); throw new NoSuchElementException(msg); } @@ -108,16 +108,16 @@ public class PropertyDB { /** * Retrieve a persisted format string. - * + * * @param key * The name of the format string. - * + * * @return The format string with that name. */ - public static String getFormat(String key) { + public static String getFormat(final String key) { return loadLock.read(() -> { - if(!formats.containsKey(key)) { - String msg = String.format("No format string named '%s' found", key); + if (!formats.containsKey(key)) { + final String msg = String.format("No format string named '%s' found", key); throw new NoSuchElementException(msg); } @@ -129,16 +129,16 @@ public class PropertyDB { /** * Retrieve a persisted format string, and apply it to a set of * arguments. - * + * * @param key * The name of the format string. - * + * * @param objects * The parameters to the format string. - * + * * @return The format string with that name. */ - public static String applyFormat(String key, Object... objects) { + public static String applyFormat(final String key, final Object... objects) { return String.format(getFormat(key), objects); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java index 56a4be0..cccb255 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java @@ -16,9 +16,9 @@ public class CLICommander { /* * The streams used for input and normal/error output. */ - private InputStream input; - private OutputStream output; - private OutputStream error; + private final InputStream input; + private final OutputStream output; + private final OutputStream error; /* * The command mode to start execution in. @@ -35,14 +35,16 @@ public class CLICommander { * @param error * The stream to send error output to. */ - public CLICommander(InputStream input, OutputStream output, OutputStream error) { - if(input == null) throw new NullPointerException("Input stream must not be null"); - else if(output == null) throw new NullPointerException("Output stream must not be null"); - else if(error == null) throw new NullPointerException("Error stream must not be null"); - - this.input = input; + public CLICommander(final InputStream input, final OutputStream output, final OutputStream error) { + if (input == null) + throw new NullPointerException("Input stream must not be null"); + else if (output == null) + throw new NullPointerException("Output stream must not be null"); + else if (error == null) throw new NullPointerException("Error stream must not be null"); + + this.input = input; this.output = output; - this.error = error; + this.error = error; } /** @@ -50,10 +52,10 @@ public class CLICommander { */ public void runCommands() { /* - * Setup output streams. + * Setup output streams. */ - PrintStream normalOutput = new PrintStream(output); - PrintStream errorOutput = new PrintStream(error); + final PrintStream normalOutput = new PrintStream(output); + final PrintStream errorOutput = new PrintStream(error); /* * Set up input streams. @@ -62,7 +64,7 @@ public class CLICommander { * stream multiple times. */ @SuppressWarnings("resource") - Scanner inputSource = new Scanner(input); + final Scanner inputSource = new Scanner(input); /* * The mode currently being used to handle commands. @@ -72,42 +74,42 @@ public class CLICommander { CommandMode currentMode = initialMode; /* - * Process commands until we're told to stop. + * Process commands until we're told to stop. */ - while(currentMode != null) { + while (currentMode != null) { /* * Print out the command prompt, using a custom prompt * if one is specified. */ - if(currentMode.isCustomPromptEnabled()) { + if (currentMode.isCustomPromptEnabled()) { normalOutput.print(currentMode.getCustomPrompt()); } else { normalOutput.print(currentMode.getName() + ">> "); } /* - * Read in a command. + * Read in a command. */ - String currentLine = inputSource.nextLine(); + final String currentLine = inputSource.nextLine(); /* - * Handle commands we can handle. + * Handle commands we can handle. */ - if(currentMode.canHandle(currentLine)) { - String[] commandTokens = currentLine.split(" "); - String[] commandArgs = null; + if (currentMode.canHandle(currentLine)) { + final String[] commandTokens = currentLine.split(" "); + String[] commandArgs = null; - int argCount = commandTokens.length; + final int argCount = commandTokens.length; /* - * Parse args if they are present. + * Parse args if they are present. */ - if(argCount > 1) { + if (argCount > 1) { commandArgs = Arrays.copyOfRange(commandTokens, 1, argCount); } /* - * Process command. + * Process command. */ currentMode = currentMode.process(commandTokens[0], commandArgs); } else { @@ -124,8 +126,8 @@ public class CLICommander { * @param initialMode * The initial command mode to use. */ - public void setInitialCommandMode(CommandMode initialMode) { - if(initialMode == null) throw new NullPointerException("Initial mode must be non-zero"); + public void setInitialCommandMode(final CommandMode initialMode) { + if (initialMode == null) throw new NullPointerException("Initial mode must be non-zero"); this.initialMode = initialMode; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHandler.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHandler.java index 0a3534f..2548248 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHandler.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHandler.java @@ -18,7 +18,7 @@ public interface CommandHandler extends Function<String[], CommandMode> { * @return The command mode to switch to after this command, or null to * stop executing commands */ - default CommandMode handle(String[] args) { + default CommandMode handle(final String[] args) { return this.apply(args); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHelp.java index 68ed41a..86567a0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandHelp.java @@ -18,8 +18,12 @@ public interface CommandHelp { * Get the summary line for a command. * * A summary line should consist of a string of the following format - * <pre>"<command-name>\t<command-summary>"</pre> where anything in angle brackets - * should be filled in. + * + * <pre> + * "<command-name>\t<command-summary>" + * </pre> + * + * where anything in angle brackets should be filled in. * * @return The summary line line for a command */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandMode.java index d26b176..39c72fc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CommandMode.java @@ -16,7 +16,7 @@ public interface CommandMode extends Comparable<CommandMode> { * @return Whether or not this mode can handle the command. It is * assumed not by default */ - default boolean canHandle(String command) { + default boolean canHandle(final String command) { return false; }; @@ -61,12 +61,12 @@ public interface CommandMode extends Comparable<CommandMode> { * @return The command mode to use for the next command. Defaults to * returning this, and doing nothing else */ - default CommandMode process(String command, String[] args) { + default CommandMode process(final String command, final String[] args) { return this; } @Override - default int compareTo(CommandMode o) { + default int compareTo(final CommandMode o) { return getName().compareTo(o.getName()); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java index dbbb047..acaa3a6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -10,7 +10,7 @@ class DelegatingCommand implements Command { /* * The command to delegate to. */ - private Command delegate; + private final Command delegate; /** * Create a new command that delegates to another command. @@ -18,7 +18,7 @@ class DelegatingCommand implements Command { * @param delegate * The command to delegate to. */ - public DelegatingCommand(Command delegate) { + public DelegatingCommand(final Command delegate) { this.delegate = delegate; } @@ -44,15 +44,15 @@ class DelegatingCommand implements Command { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("DelegatingCommand ["); - if(delegate != null) { + if (delegate != null) { builder.append("delegate="); builder.append(delegate); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java index c49b4b9..4ae4dea 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java @@ -10,7 +10,7 @@ public class GenericCommand implements Command { /* * The behavior for invoking the command. */ - private CommandHandler handler; + private final CommandHandler handler; /* * The help for the command. @@ -30,12 +30,12 @@ public class GenericCommand implements Command { * null, in which case the description is repeated for * the detailed help. */ - public GenericCommand(CommandHandler handler, String description, String help) { - if(handler == null) throw new NullPointerException("Command handler must not be null"); + public GenericCommand(final CommandHandler handler, final String description, final String help) { + if (handler == null) throw new NullPointerException("Command handler must not be null"); this.handler = handler; - if(description == null) { + if (description == null) { this.help = new NullHelp(); } else { this.help = new GenericHelp(description, help); @@ -64,15 +64,15 @@ public class GenericCommand implements Command { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("GenericCommand ["); - if(help != null) { + if (help != null) { builder.append("help="); builder.append(help); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java index 7977391..8764537 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -1,12 +1,12 @@ package bjc.utils.cli; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IMap; - import java.util.TreeMap; import java.util.function.BiConsumer; import java.util.function.Consumer; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IMap; + /** * A general command mode, with a customizable set of commands * @@ -21,13 +21,13 @@ public class GenericCommandMode implements CommandMode { /* * Contains the commands this mode handles */ - private IMap<String, Command> commandHandlers; - private IMap<String, Command> defaultHandlers; + private final IMap<String, Command> commandHandlers; + private final IMap<String, Command> defaultHandlers; /* * Contains help topics without an associated command */ - private IMap<String, CommandHelp> helpTopics; + private final IMap<String, CommandHelp> helpTopics; /* * The action to execute upon encountering an unknown command @@ -37,8 +37,8 @@ public class GenericCommandMode implements CommandMode { /* * The functions to use for input/output */ - private Consumer<String> errorOutput; - private Consumer<String> normalOutput; + private final Consumer<String> errorOutput; + private final Consumer<String> normalOutput; /* * The name of this command mode, or null if it is unnamed @@ -58,10 +58,10 @@ public class GenericCommandMode implements CommandMode { * @param errorOutput * The function to use for error output */ - public GenericCommandMode(Consumer<String> normalOutput, Consumer<String> errorOutput) { - if(normalOutput == null) + public GenericCommandMode(final Consumer<String> normalOutput, final Consumer<String> errorOutput) { + if (normalOutput == null) throw new NullPointerException("Normal output source must be non-null"); - else if(errorOutput == null) throw new NullPointerException("Error output source must be non-null"); + else if (errorOutput == null) throw new NullPointerException("Error output source must be non-null"); this.normalOutput = normalOutput; this.errorOutput = errorOutput; @@ -92,20 +92,20 @@ public class GenericCommandMode implements CommandMode { * handler, or if the alias name already has a bound * value */ - public void addCommandAlias(String commandName, String aliasName) { - if(commandName == null) + public void addCommandAlias(final String commandName, final String aliasName) { + if (commandName == null) throw new NullPointerException("Command name must not be null"); - else if(aliasName == null) + else if (aliasName == null) throw new NullPointerException("Alias name must not be null"); - else if(!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) + else if (!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) throw new IllegalArgumentException("Cannot alias non-existant command '" + commandName + "'"); - else if(commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) + else if (commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) throw new IllegalArgumentException( "Cannot bind alias '" + aliasName + "' to a command with a bound handler"); else { Command aliasedCommand; - if(defaultHandlers.containsKey(commandName)) { + if (defaultHandlers.containsKey(commandName)) { aliasedCommand = defaultHandlers.get(commandName).aliased(); } else { aliasedCommand = commandHandlers.get(commandName).aliased(); @@ -127,12 +127,12 @@ public class GenericCommandMode implements CommandMode { * if the specified command already has a handler * registered */ - public void addCommandHandler(String command, Command handler) { - if(command == null) + public void addCommandHandler(final String command, final Command handler) { + if (command == null) throw new NullPointerException("Command must not be null"); - else if(handler == null) + else if (handler == null) throw new NullPointerException("Handler must not be null"); - else if(canHandle(command)) + else if (canHandle(command)) throw new IllegalArgumentException("Command " + command + " already has a handler registered"); else { commandHandlers.put(command, handler); @@ -147,7 +147,7 @@ public class GenericCommandMode implements CommandMode { * @param topic * The contents of the topic */ - public void addHelpTopic(String topicName, CommandHelp topic) { + public void addHelpTopic(final String topicName, final CommandHelp topic) { helpTopics.put(topicName, topic); } @@ -156,8 +156,8 @@ public class GenericCommandMode implements CommandMode { */ private GenericCommand buildAliasCommand() { - String aliasShortHelp = "alias\tAlias one command to another"; - String aliasLongHelp = "Gives a command another name it can be invoked by." + final String aliasShortHelp = "alias\tAlias one command to another"; + final String aliasLongHelp = "Gives a command another name it can be invoked by." + " Invoke with two arguments: the name of the command to alias" + "followed by the name of the alias to give that command."; @@ -169,8 +169,8 @@ public class GenericCommandMode implements CommandMode { } private GenericCommand buildClearCommands() { - String clearShortHelp = "clear\tClear the screen"; - String clearLongHelp = "Clears the screen of all the text on it," + " and prints a new prompt."; + final String clearShortHelp = "clear\tClear the screen"; + final String clearLongHelp = "Clears the screen of all the text on it," + " and prints a new prompt."; return new GenericCommand((args) -> { errorOutput.accept("ERROR: This console doesn't support screen clearing"); @@ -180,8 +180,8 @@ public class GenericCommandMode implements CommandMode { } private GenericCommand buildExitCommand() { - String exitShortHelp = "exit\tExit the console"; - String exitLongHelp = "First prompts the user to make sure they want to" + final String exitShortHelp = "exit\tExit the console"; + final String exitLongHelp = "First prompts the user to make sure they want to" + " exit, then quits if they say they do"; return new GenericCommand((args) -> { @@ -192,14 +192,14 @@ public class GenericCommandMode implements CommandMode { } private GenericCommand buildHelpCommand() { - String helpShortHelp = "help\tConsult the help system"; - String helpLongHelp = "Consults the internal help system." + final String helpShortHelp = "help\tConsult the help system"; + final String helpLongHelp = "Consults the internal help system." + " Invoked in two different ways. Invoking with no arguments" + " causes all the topics you can ask for details on to be list," + " while invoking with the name of a topic will print the entry" + " for that topic"; return new GenericCommand((args) -> { - if(args == null || args.length == 0) { + if (args == null || args.length == 0) { /* * Invoke general help */ @@ -216,8 +216,8 @@ public class GenericCommandMode implements CommandMode { } private GenericCommand buildListCommand() { - String listShortHelp = "list\tList available commands"; - String listLongHelp = "Lists all of the commands available in this mode," + final String listShortHelp = "list\tList available commands"; + final String listLongHelp = "Lists all of the commands available in this mode," + " as well as commands available in any mode"; return new GenericCommand((args) -> { @@ -228,7 +228,7 @@ public class GenericCommandMode implements CommandMode { } @Override - public boolean canHandle(String command) { + public boolean canHandle(final String command) { return commandHandlers.containsKey(command) || defaultHandlers.containsKey(command); } @@ -236,17 +236,17 @@ public class GenericCommandMode implements CommandMode { * Implement default commands */ - private void doAliasCommands(String[] args) { - if(args.length != 2) { + private void doAliasCommands(final String[] args) { + if (args.length != 2) { errorOutput.accept("ERROR: Alias requires two arguments." + " The command name, and the alias for that command"); } else { - String commandName = args[0]; - String aliasName = args[1]; + final String commandName = args[0]; + final String aliasName = args[1]; - if(!canHandle(commandName)) { + if (!canHandle(commandName)) { errorOutput.accept("ERROR: '" + commandName + "' is not a valid command."); - } else if(canHandle(aliasName)) { + } else if (canHandle(aliasName)) { errorOutput.accept("ERROR: Cannot overwrite command '" + aliasName + "'"); } else { addCommandAlias(commandName, aliasName); @@ -254,16 +254,16 @@ public class GenericCommandMode implements CommandMode { } } - private void doHelpCommand(String commandName) { - if(commandHandlers.containsKey(commandName)) { - String desc = commandHandlers.get(commandName).getHelp().getDescription(); + private void doHelpCommand(final String commandName) { + if (commandHandlers.containsKey(commandName)) { + final String desc = commandHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if(defaultHandlers.containsKey(commandName)) { - String desc = defaultHandlers.get(commandName).getHelp().getDescription(); + } else if (defaultHandlers.containsKey(commandName)) { + final String desc = defaultHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if(helpTopics.containsKey(commandName)) { + } else if (helpTopics.containsKey(commandName)) { normalOutput.accept("\n" + helpTopics.get(commandName).getDescription()); } else { errorOutput.accept( @@ -274,9 +274,9 @@ public class GenericCommandMode implements CommandMode { private void doHelpSummary() { normalOutput.accept("Help topics for this command mode are as follows:\n"); - if(commandHandlers.size() > 0) { + if (commandHandlers.size() > 0) { commandHandlers.forEachValue(command -> { - if(!command.isAlias()) { + if (!command.isAlias()) { normalOutput.accept("\t" + command.getHelp().getSummary() + "\n"); } }); @@ -285,9 +285,9 @@ public class GenericCommandMode implements CommandMode { } normalOutput.accept("\nHelp topics available in all command modes are as follows\n"); - if(defaultHandlers.size() > 0) { + if (defaultHandlers.size() > 0) { defaultHandlers.forEachValue(command -> { - if(!command.isAlias()) { + if (!command.isAlias()) { normalOutput.accept("\t" + command.getHelp().getSummary() + "\n"); } }); @@ -296,7 +296,7 @@ public class GenericCommandMode implements CommandMode { } normalOutput.accept("\nHelp topics not associated with a command are as follows\n"); - if(helpTopics.size() > 0) { + if (helpTopics.size() > 0) { helpTopics.forEachValue(topic -> { normalOutput.accept("\t" + topic.getSummary() + "\n"); }); @@ -322,14 +322,14 @@ public class GenericCommandMode implements CommandMode { @Override public String getCustomPrompt() { - if(customPrompt != null) return customPrompt; + if (customPrompt != null) return customPrompt; return CommandMode.super.getCustomPrompt(); } @Override public String getName() { - if(modeName != null) return modeName; + if (modeName != null) return modeName; return CommandMode.super.getName(); } @@ -340,21 +340,21 @@ public class GenericCommandMode implements CommandMode { } @Override - public CommandMode process(String command, String[] args) { + public CommandMode process(final String command, final String[] args) { normalOutput.accept("\n"); - if(defaultHandlers.containsKey(command)) + if (defaultHandlers.containsKey(command)) return defaultHandlers.get(command).getHandler().handle(args); - else if(commandHandlers.containsKey(command)) + else if (commandHandlers.containsKey(command)) return commandHandlers.get(command).getHandler().handle(args); else { - if(args != null) { + if (args != null) { errorOutput.accept("ERROR: Unrecognized command " + command + String.join(" ", args)); } else { errorOutput.accept("ERROR: Unrecognized command " + command); } - if(unknownCommandHandler == null) + if (unknownCommandHandler == null) throw new UnsupportedOperationException("Command " + command + " is invalid."); unknownCommandHandler.accept(command, args); @@ -370,7 +370,7 @@ public class GenericCommandMode implements CommandMode { * The custom prompt for this mode, or null to disable * the custom prompt */ - public void setCustomPrompt(String prompt) { + public void setCustomPrompt(final String prompt) { customPrompt = prompt; } @@ -381,7 +381,7 @@ public class GenericCommandMode implements CommandMode { * The desired name of this mode, or null to use the * default name */ - public void setModeName(String name) { + public void setModeName(final String name) { modeName = name; } @@ -392,8 +392,8 @@ public class GenericCommandMode implements CommandMode { * The handler to use for unknown commands, or null to * throw on unknown commands */ - public void setUnknownCommandHandler(BiConsumer<String, String[]> handler) { - if(handler == null) throw new NullPointerException("Handler must not be null"); + public void setUnknownCommandHandler(final BiConsumer<String, String[]> handler) { + if (handler == null) throw new NullPointerException("Handler must not be null"); unknownCommandHandler = handler; } @@ -424,38 +424,38 @@ public class GenericCommandMode implements CommandMode { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("GenericCommandMode ["); - - if(commandHandlers != null) { + + if (commandHandlers != null) { builder.append("commandHandlers="); builder.append(commandHandlers); } - if(defaultHandlers != null) { + if (defaultHandlers != null) { builder.append(", "); builder.append("defaultHandlers="); builder.append(defaultHandlers); } - if(helpTopics != null) { + if (helpTopics != null) { builder.append(", "); builder.append("helpTopics="); builder.append(helpTopics); } - if(modeName != null) { + if (modeName != null) { builder.append(", "); builder.append("modeName="); builder.append(modeName); } - if(customPrompt != null) { + if (customPrompt != null) { builder.append(", "); builder.append("customPrompt="); builder.append(customPrompt); diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java index edda5c0..38adf57 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java @@ -8,8 +8,8 @@ package bjc.utils.cli; */ public class GenericHelp implements CommandHelp { // The strings for this help topic - private String summary; - private String description; + private final String summary; + private final String description; /** * Create a new help topic @@ -20,8 +20,8 @@ public class GenericHelp implements CommandHelp { * The description of this help topic, or null if this * help topic doesn't have a more detailed description */ - public GenericHelp(String summary, String description) { - if(summary == null) throw new NullPointerException("Help summary must be non-null"); + public GenericHelp(final String summary, final String description) { + if (summary == null) throw new NullPointerException("Help summary must be non-null"); this.summary = summary; this.description = description; @@ -29,7 +29,7 @@ public class GenericHelp implements CommandHelp { @Override public String getDescription() { - if(description == null) return summary; + if (description == null) return summary; return description; } @@ -41,23 +41,23 @@ public class GenericHelp implements CommandHelp { @Override public String toString() { - StringBuilder builder = new StringBuilder(); - + final StringBuilder builder = new StringBuilder(); + builder.append("GenericHelp ["); - - if(summary != null) { + + if (summary != null) { builder.append("summary="); builder.append(summary); } - - if(description != null) { + + if (description != null) { builder.append(", "); builder.append("description="); builder.append(description); } - + builder.append("]"); - + return builder.toString(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java index 289d9c1..6c49ae6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java @@ -16,6 +16,5 @@ public class NullHelp implements CommandHelp { public String getSummary() { return "No summary provided"; } - - + } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java index b750848..28f81d1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java @@ -7,29 +7,30 @@ package bjc.utils.components; * */ public class ComponentDescription implements IDescribedComponent { - private static void sanityCheckArgs(String name, String author, String description, int version) { - if(name == null) + private static void sanityCheckArgs(final String name, final String author, final String description, + final int version) { + if (name == null) throw new NullPointerException("Component name can't be null"); - else if(version <= 0) throw new IllegalArgumentException("Component version must be greater than 0"); + else if (version <= 0) throw new IllegalArgumentException("Component version must be greater than 0"); } /** * The author of the component */ - private String author; + private final String author; /** * The description of the component */ - private String description; + private final String description; /** * The name of the component */ - private String name; + private final String name; /** * The version of the component */ - private int version; + private final int version; /** * Create a new component description @@ -45,7 +46,8 @@ public class ComponentDescription implements IDescribedComponent { * @throws IllegalArgumentException * thrown if version is less than 1 */ - public ComponentDescription(String name, String author, String description, int version) { + public ComponentDescription(final String name, final String author, final String description, + final int version) { sanityCheckArgs(name, author, description, version); this.name = name; @@ -56,14 +58,14 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getAuthor() { - if(author == null) return IDescribedComponent.super.getAuthor(); + if (author == null) return IDescribedComponent.super.getAuthor(); return author; } @Override public String getDescription() { - if(description == null) return IDescribedComponent.super.getDescription(); + if (description == null) return IDescribedComponent.super.getDescription(); return description; } @@ -85,7 +87,7 @@ public class ComponentDescription implements IDescribedComponent { /* * (non-Javadoc) - * + * * @see java.lang.Object#hashCode() */ @Override @@ -93,9 +95,9 @@ public class ComponentDescription implements IDescribedComponent { final int prime = 31; int result = 1; - result = prime * result + ((author == null) ? 0 : author.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + (author == null ? 0 : author.hashCode()); + result = prime * result + (description == null ? 0 : description.hashCode()); + result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + version; return result; @@ -103,30 +105,30 @@ public class ComponentDescription implements IDescribedComponent { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(getClass() != obj.getClass()) return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; - ComponentDescription other = (ComponentDescription) obj; + final ComponentDescription other = (ComponentDescription) obj; - if(author == null) { - if(other.author != null) return false; - } else if(!author.equals(other.author)) return false; + if (author == null) { + if (other.author != null) return false; + } else if (!author.equals(other.author)) return false; - if(description == null) { - if(other.description != null) return false; - } else if(!description.equals(other.description)) return false; + if (description == null) { + if (other.description != null) return false; + } else if (!description.equals(other.description)) return false; - if(name == null) { - if(other.name != null) return false; - } else if(!name.equals(other.name)) return false; + if (name == null) { + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; - if(version != other.version) return false; + if (version != other.version) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java index 5f98ce9..f7ddaff 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java @@ -40,10 +40,11 @@ public class ComponentDescriptionFileParser { * The stream to parse from * @return The description parsed from the stream */ - public static ComponentDescription fromStream(InputStream inputSource) { - if(inputSource == null) throw new NullPointerException("Input source must not be null"); + public static ComponentDescription fromStream(final InputStream inputSource) { + if (inputSource == null) throw new NullPointerException("Input source must not be null"); - ComponentDescriptionState readState = reader.fromStream(inputSource, new ComponentDescriptionState()); + final ComponentDescriptionState readState = reader.fromStream(inputSource, + new ComponentDescriptionState()); return readState.toDescription(); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java index d6fbc5a..8d66f85 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java @@ -25,7 +25,7 @@ public class ComponentDescriptionState { * @param author * The author of this component */ - public void setAuthor(String author) { + public void setAuthor(final String author) { this.author = author; } @@ -35,7 +35,7 @@ public class ComponentDescriptionState { * @param description * The description of this component */ - public void setDescription(String description) { + public void setDescription(final String description) { this.description = description; } @@ -45,7 +45,7 @@ public class ComponentDescriptionState { * @param name * The name of this component */ - public void setName(String name) { + public void setName(final String name) { this.name = name; } @@ -55,7 +55,7 @@ public class ComponentDescriptionState { * @param version * The version of this component */ - public void setVersion(int version) { + public void setVersion(final int version) { this.version = version; } @@ -73,62 +73,62 @@ public class ComponentDescriptionState { final int prime = 31; int result = 1; - result = prime * result + ((author == null) ? 0 : author.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + (author == null ? 0 : author.hashCode()); + result = prime * result + (description == null ? 0 : description.hashCode()); + result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + version; return result; } @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(getClass() != obj.getClass()) return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; - ComponentDescriptionState other = (ComponentDescriptionState) obj; + final ComponentDescriptionState other = (ComponentDescriptionState) obj; - if(author == null) { - if(other.author != null) return false; - } else if(!author.equals(other.author)) return false; + if (author == null) { + if (other.author != null) return false; + } else if (!author.equals(other.author)) return false; - if(description == null) { - if(other.description != null) return false; - } else if(!description.equals(other.description)) return false; + if (description == null) { + if (other.description != null) return false; + } else if (!description.equals(other.description)) return false; - if(name == null) { - if(other.name != null) return false; - } else if(!name.equals(other.name)) return false; + if (name == null) { + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; - if(version != other.version) return false; + if (version != other.version) return false; return true; } /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("ComponentDescriptionState ["); - if(name != null) { + if (name != null) { builder.append("name="); builder.append(name); builder.append(", "); } - if(description != null) { + if (description != null) { builder.append("description="); builder.append(description); builder.append(", "); } - if(author != null) { + if (author != null) { builder.append("author="); builder.append(author); builder.append(", "); diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java index 6fd6177..efde5c7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -1,12 +1,5 @@ package bjc.utils.components; -import bjc.utils.data.IHolder; -import bjc.utils.data.Identity; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.IMap; -import bjc.utils.funcutils.FileUtils; - import java.io.File; import java.io.IOException; import java.nio.file.Path; @@ -16,6 +9,13 @@ import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; +import bjc.utils.data.IHolder; +import bjc.utils.data.Identity; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.IMap; +import bjc.utils.funcutils.FileUtils; + /** * A component repository that loads its components from files in a directory * @@ -47,33 +47,37 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> * @param componentReader * The function to use to convert files to components */ - public FileComponentRepository(File directory, Function<File, ? extends ComponentType> componentReader) { + public FileComponentRepository(final File directory, + final Function<File, ? extends ComponentType> componentReader) { // Make sure we have valid arguments - if(directory == null) + if (directory == null) throw new NullPointerException("Directory must not be null"); - else if(!directory.isDirectory()) + else if (!directory.isDirectory()) throw new IllegalArgumentException("File " + directory + " is not a directory.\n" + "Components can only be read from a directory"); - else if(componentReader == null) throw new NullPointerException("Component reader must not be null"); + else if (componentReader == null) throw new NullPointerException("Component reader must not be null"); // Initialize our fields components = new FunctionalMap<>(); sourceDirectory = directory.toPath().toAbsolutePath(); // Marker for making sure we don't skip the parent - IHolder<Boolean> isFirstDir = new Identity<>(true); + final IHolder<Boolean> isFirstDir = new Identity<>(true); // Predicate to use to traverse all the files in a directory, // but // not recurse into sub-directories - BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, attr) -> { - if(attr.isDirectory() && !isFirstDir - .getValue()) /* - * Skip directories, - * they probably have - * component support - * files. - */ + final BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, attr) -> { + if (attr.isDirectory() && !isFirstDir.getValue()) /* + * Skip + * directories, + * they + * probably + * have + * component + * support + * files. + */ return false; /* @@ -94,7 +98,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> // failed return true; }); - } catch(IOException ioex) { + } catch (final IOException ioex) { CLASS_LOGGER.log(Level.WARNING, ioex, () -> "Error found reading component from file."); } } @@ -105,7 +109,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> } @Override - public ComponentType getByName(String name) { + public ComponentType getByName(final String name) { return components.get(name); } @@ -122,19 +126,19 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> /* * Load a component from a file */ - private void loadComponent(Function<File, ? extends ComponentType> componentReader, Path pth) { + private void loadComponent(final Function<File, ? extends ComponentType> componentReader, final Path pth) { try { // Try to load the component - ComponentType component = componentReader.apply(pth.toFile()); + final ComponentType component = componentReader.apply(pth.toFile()); - if(component == null) + if (component == null) throw new NullPointerException("Component reader read null component"); - else if(!components.containsKey(component.getName())) { + else if (!components.containsKey(component.getName())) { // We only care about the latest version of a // component - ComponentType oldComponent = components.put(component.getName(), component); + final ComponentType oldComponent = components.put(component.getName(), component); - if(oldComponent.getVersion() > component.getVersion()) { + if (oldComponent.getVersion() > component.getVersion()) { components.put(oldComponent.getName(), oldComponent); } } else { @@ -143,7 +147,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> + "Only the latest version of the component" + component + " will be registered ."); } - } catch(Exception ex) { + } catch (final Exception ex) { CLASS_LOGGER.log(Level.WARNING, ex, () -> "Error found reading component from file " + pth.toString() + ". This component will not be loaded"); } @@ -151,21 +155,21 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("FileComponentRepository ["); - if(components != null) { + if (components != null) { builder.append("components="); builder.append(components); builder.append(", "); } - if(sourceDirectory != null) { + if (sourceDirectory != null) { builder.append("sourceDirectory="); builder.append(sourceDirectory); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java b/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java index f231924..952b375 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java @@ -7,7 +7,7 @@ package bjc.utils.components; * @author ben * */ -public interface IDescribedComponent extends Comparable<IDescribedComponent>{ +public interface IDescribedComponent extends Comparable<IDescribedComponent> { /** * Get the author of this component * @@ -50,16 +50,15 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent>{ default int getVersion() { return 1; } - - + @Override - default int compareTo(IDescribedComponent o) { + default int compareTo(final IDescribedComponent o) { int res = getName().compareTo(o.getName()); - - if(res == 0) { + + if (res == 0) { res = getVersion() - o.getVersion(); } - + return res; } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/BooleanToggle.java b/BJC-Utils2/src/main/java/bjc/utils/data/BooleanToggle.java index 68399a0..12e3b2e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/BooleanToggle.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/BooleanToggle.java @@ -2,7 +2,7 @@ package bjc.utils.data; /** * A simple {@link ValueToggle} that swaps between true and false. - * + * * @author EVE * */ @@ -18,17 +18,17 @@ public class BooleanToggle implements Toggle<Boolean> { /** * Create a flip-flop with the specified initial value. - * + * * @param initial * The initial value of the flip-flop. */ - public BooleanToggle(boolean initial) { + public BooleanToggle(final boolean initial) { val = initial; } @Override public Boolean get() { - boolean res = val; + final boolean res = val; val = !res; @@ -41,7 +41,7 @@ public class BooleanToggle implements Toggle<Boolean> { } @Override - public void set(boolean vl) { + public void set(final boolean vl) { val = vl; } @@ -57,14 +57,14 @@ public class BooleanToggle implements Toggle<Boolean> { } @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof BooleanToggle)) return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof BooleanToggle)) return false; - BooleanToggle other = (BooleanToggle) obj; + final BooleanToggle other = (BooleanToggle) obj; - if(val != other.val) return false; + if (val != other.val) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java index 4b84243..a708eba 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java @@ -4,7 +4,7 @@ import java.util.Iterator; /** * An iterator that repeats elements from a provided iterable. - * + * * @author EVE * * @param <E> @@ -30,15 +30,15 @@ public class CircularIterator<E> implements Iterator<E> { /** * Create a new circular iterator. - * + * * @param src * The iterable to iterate from. - * + * * @param circ * Should we actually do circular iteration, or just * repeat the terminal element? */ - public CircularIterator(Iterable<E> src, boolean circ) { + public CircularIterator(final Iterable<E> src, final boolean circ) { source = src; curr = source.iterator(); @@ -47,11 +47,11 @@ public class CircularIterator<E> implements Iterator<E> { /** * Create a new circular iterator that does actual circular iteration. - * + * * @param src * The iterable to iterate from. */ - public CircularIterator(Iterable<E> src) { + public CircularIterator(final Iterable<E> src) { this(src, true); } @@ -64,10 +64,9 @@ public class CircularIterator<E> implements Iterator<E> { @Override public E next() { if (!curr.hasNext()) { - if (doCircle) + if (doCircle) { curr = source.iterator(); - else - return curElm; + } else return curElm; } curElm = curr.next(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Either.java b/BJC-Utils2/src/main/java/bjc/utils/data/Either.java index d07fbbe..36b3324 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Either.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Either.java @@ -25,7 +25,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * The value to put on the left * @return An either with the left side occupied */ - public static <LeftType, RightType> Either<LeftType, RightType> left(LeftType left) { + public static <LeftType, RightType> Either<LeftType, RightType> left(final LeftType left) { return new Either<>(left, null); } @@ -40,7 +40,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * The value to put on the right * @return An either with the right side occupied */ - public static <LeftType, RightType> Either<LeftType, RightType> right(RightType right) { + public static <LeftType, RightType> Either<LeftType, RightType> right(final RightType right) { return new Either<>(null, right); } @@ -50,7 +50,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { private boolean isLeft; - private Either(LeftType left, RightType right) { + private Either(final LeftType left, final RightType right) { if (left == null) { rightVal = right; } else { @@ -62,53 +62,46 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if (binder == null) - throw new NullPointerException("Binder must not be null"); + final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { + if (binder == null) throw new NullPointerException("Binder must not be null"); return binder.apply(leftVal, rightVal); } @Override public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if (leftBinder == null) - throw new NullPointerException("Left binder must not be null"); + final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + if (leftBinder == null) throw new NullPointerException("Left binder must not be null"); - if (isLeft) - return leftBinder.apply(leftVal); + if (isLeft) return leftBinder.apply(leftVal); return new Either<>(null, rightVal); } @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( - Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if (rightBinder == null) - throw new NullPointerException("Right binder must not be null"); + final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { + if (rightBinder == null) throw new NullPointerException("Right binder must not be null"); - if (isLeft) - return new Either<>(leftVal, null); + if (isLeft) return new Either<>(leftVal, null); return rightBinder.apply(rightVal); } @Override public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { + final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { if (otherPair == null) throw new NullPointerException("Other pair must not be null"); else if (leftCombiner == null) throw new NullPointerException("Left combiner must not be null"); - else if (rightCombiner == null) - throw new NullPointerException("Right combiner must not be null"); + else if (rightCombiner == null) throw new NullPointerException("Right combiner must not be null"); - if (isLeft) - return otherPair.bind((otherLeft, otherRight) -> { - return new Either<>(leftCombiner.apply(leftVal, otherLeft), null); - }); + if (isLeft) return otherPair.bind((otherLeft, otherRight) -> { + return new Either<>(leftCombiner.apply(leftVal, otherLeft), null); + }); return otherPair.bind((otherLeft, otherRight) -> { return new Either<>(null, rightCombiner.apply(rightVal, otherRight)); @@ -116,31 +109,26 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { - if (mapper == null) - throw new NullPointerException("Mapper must not be null"); + public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); - if (isLeft) - return new Either<>(mapper.apply(leftVal), null); + if (isLeft) return new Either<>(mapper.apply(leftVal), null); return new Either<>(null, rightVal); } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { - if (mapper == null) - throw new NullPointerException("Mapper must not be null"); + public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); - if (isLeft) - return new Either<>(leftVal, null); + if (isLeft) return new Either<>(leftVal, null); return new Either<>(null, mapper.apply(rightVal)); } @Override - public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { - if (merger == null) - throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { + if (merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftVal, rightVal); } @@ -151,37 +139,29 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { int result = 1; result = prime * result + (isLeft ? 1231 : 1237); - result = prime * result + ((leftVal == null) ? 0 : leftVal.hashCode()); - result = prime * result + ((rightVal == null) ? 0 : rightVal.hashCode()); + result = prime * result + (leftVal == null ? 0 : leftVal.hashCode()); + result = prime * result + (rightVal == null ? 0 : rightVal.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Either<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Either<?, ?>)) return false; - Either<?, ?> other = (Either<?, ?>) obj; + final Either<?, ?> other = (Either<?, ?>) obj; - if (isLeft != other.isLeft) - return false; + if (isLeft != other.isLeft) return false; if (leftVal == null) { - if (other.leftVal != null) - return false; - } else if (!leftVal.equals(other.leftVal)) - return false; + if (other.leftVal != null) return false; + } else if (!leftVal.equals(other.leftVal)) return false; if (rightVal == null) { - if (other.rightVal != null) - return false; - } else if (!rightVal.equals(other.rightVal)) - return false; + if (other.rightVal != null) return false; + } else if (!rightVal.equals(other.rightVal)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java index 1d380c8..ca0b2ba 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java @@ -1,15 +1,15 @@ package bjc.utils.data; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.UnaryOperator; + import bjc.utils.data.internals.BoundListHolder; import bjc.utils.data.internals.WrappedLazy; import bjc.utils.data.internals.WrappedOption; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.theory.Functor; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.UnaryOperator; - /** * A holder of a single value. * @@ -36,7 +36,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * @param action * The action to apply to the value */ - public default void doWith(Consumer<? super ContainedType> action) { + public default void doWith(final Consumer<? super ContainedType> action) { transform(value -> { action.accept(value); @@ -46,15 +46,15 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { @Override default <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( - Function<ArgType, ReturnType> func) { + final Function<ArgType, ReturnType> func) { return argumentFunctor -> { if (!(argumentFunctor instanceof IHolder<?>)) { - String msg = "This functor only supports mapping over instances of IHolder"; + final String msg = "This functor only supports mapping over instances of IHolder"; throw new IllegalArgumentException(msg); } - IHolder<ArgType> holder = (IHolder<ArgType>) argumentFunctor; + final IHolder<ArgType> holder = (IHolder<ArgType>) argumentFunctor; return holder.map(func); }; @@ -124,7 +124,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * The value to hold instead * @return The holder itself */ - public default IHolder<ContainedType> replace(ContainedType newValue) { + public default IHolder<ContainedType> replace(final ContainedType newValue) { return transform(oldValue -> { return newValue; }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java index ae54a88..db8a1cb 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java @@ -1,11 +1,11 @@ package bjc.utils.data; -import bjc.utils.funcdata.theory.Bifunctor; - import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; +import bjc.utils.funcdata.theory.Bifunctor; + /** * Represents a pair of values * @@ -67,7 +67,7 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * @return The pairs, pairwise combined together */ public default <OtherLeft, OtherRight> IPair<IPair<LeftType, OtherLeft>, IPair<RightType, OtherRight>> combine( - IPair<OtherLeft, OtherRight> otherPair) { + final IPair<OtherLeft, OtherRight> otherPair) { return combine(otherPair, Pair<LeftType, OtherLeft>::new, Pair<RightType, OtherRight>::new); } @@ -100,7 +100,7 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * @param consumer * The action to perform on the pair */ - public default void doWith(BiConsumer<LeftType, RightType> consumer) { + public default void doWith(final BiConsumer<LeftType, RightType> consumer) { merge((leftValue, rightValue) -> { consumer.accept(leftValue, rightValue); @@ -110,15 +110,15 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp @Override default <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> fmapLeft( - Function<OldLeft, NewLeft> func) { + final Function<OldLeft, NewLeft> func) { return argumentPair -> { - if(!(argumentPair instanceof IPair<?, ?>)) { - String msg = "This function can only be applied to instances of IPair"; + if (!(argumentPair instanceof IPair<?, ?>)) { + final String msg = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); } - IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; + final IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapLeft(func); }; @@ -127,15 +127,15 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp @Override default <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> - fmapRight(Function<OldRight, NewRight> func) { + fmapRight(final Function<OldRight, NewRight> func) { return argumentPair -> { - if(!(argumentPair instanceof IPair<?, ?>)) { - String msg = "This function can only be applied to instances of IPair"; + if (!(argumentPair instanceof IPair<?, ?>)) { + final String msg = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); } - IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; + final IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapRight(func); }; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java b/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java index 166fe3f..ff374e8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java @@ -1,18 +1,18 @@ package bjc.utils.data; -import bjc.utils.funcdata.bst.TreeLinearizationMethod; -import bjc.utils.functypes.ListFlattener; - import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import bjc.utils.funcdata.bst.TreeLinearizationMethod; +import bjc.utils.functypes.ListFlattener; + /** * A node in a homogeneous tree with a unlimited amount of children. * * @author ben - * + * * @param <ContainedType> * The type of data contained in the tree nodes. * @@ -28,7 +28,7 @@ public interface ITree<ContainedType> { /** * Prepend a child to this node. - * + * * @param child * The child to prepend to this node. */ @@ -39,21 +39,21 @@ public interface ITree<ContainedType> { * * @param <NewType> * The intermediate type being folded. - * + * * @param <ReturnedType> * The type that is the end result. - * + * * @param leafTransform * The function to use to convert leaf values. - * + * * @param nodeCollapser * The function to use to convert internal nodes and * their children. - * + * * @param resultTransformer * The function to use to convert a state to the returned * version. - * + * * @return The final transformed state. */ <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, @@ -74,13 +74,13 @@ public interface ITree<ContainedType> { * * @param mapper * The function to use to map values into trees. - * + * * @return A tree, with some nodes expanded into trees. */ - default ITree<ContainedType> flatMapTree(Function<ContainedType, ITree<ContainedType>> mapper) { + default ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { return topDownTransform(dat -> TopDownTransformResult.PUSHDOWN, node -> { if (node.getChildrenCount() > 0) { - ITree<ContainedType> parent = node.transformHead(mapper); + final ITree<ContainedType> parent = node.transformHead(mapper); node.doForChildren(parent::addChild); @@ -96,10 +96,10 @@ public interface ITree<ContainedType> { * * @param childNo * The number of the child to get. - * + * * @return The specified child of this tree. */ - default ITree<ContainedType> getChild(int childNo) { + default ITree<ContainedType> getChild(final int childNo) { return transformChild(childNo, child -> child); } @@ -124,13 +124,13 @@ public interface ITree<ContainedType> { * * @param <MappedType> * The type of the new tree. - * + * * @param leafTransformer * The function to use to transform leaf tokens. - * + * * @param operatorTransformer * The function to use to transform internal tokens. - * + * * @return The tree, with the nodes changed. */ <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, @@ -141,7 +141,7 @@ public interface ITree<ContainedType> { * * @param nodePicker * The predicate to use to pick nodes to transform. - * + * * @param transformer * The function to use to transform picked nodes. */ @@ -152,10 +152,10 @@ public interface ITree<ContainedType> { * * @param transformPicker * The function to use to pick how to progress. - * + * * @param transformer * The function used to transform picked subtrees. - * + * * @return The tree with the transform applied to picked subtrees. */ ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, @@ -166,13 +166,13 @@ public interface ITree<ContainedType> { * * @param <TransformedType> * The type of the transformed value. - * + * * @param childNo * The number of the child to transform. - * + * * @param transformer * The function to use to transform the value. - * + * * @return The transformed value. * * @throws IllegalArgumentException @@ -187,10 +187,10 @@ public interface ITree<ContainedType> { * * @param <TransformedType> * The type of the transformed value. - * + * * @param transformer * The function to use to transform the value. - * + * * @return The transformed value. */ <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer); @@ -200,13 +200,13 @@ public interface ITree<ContainedType> { * * @param <MappedType> * The type of the new tree. - * + * * @param transformer * The function to use to transform tokens. - * + * * @return A tree with the token types transformed. */ - default <MappedType> ITree<MappedType> transformTree(Function<ContainedType, MappedType> transformer) { + default <MappedType> ITree<MappedType> transformTree(final Function<ContainedType, MappedType> transformer) { return rebuildTree(transformer, transformer); } @@ -215,7 +215,7 @@ public interface ITree<ContainedType> { * * @param linearizationMethod * The way to traverse the tree. - * + * * @param action * The action to perform on each tree node. */ @@ -223,10 +223,10 @@ public interface ITree<ContainedType> { /** * Find the farthest to right child that satisfies the given predicate. - * + * * @param childPred * The predicate to satisfy. - * + * * @return The index of the right-most child that satisfies the * predicate, or -1 if one doesn't exist. */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java b/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java index 77e13cf..a8c8d70 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java @@ -32,12 +32,12 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * @param value * The value to hold */ - public Identity(ContainedType value) { + public Identity(final ContainedType value) { heldValue = value; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { return binder.apply(heldValue); } @@ -46,40 +46,35 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { final int prime = 31; int result = 1; - result = prime * result + ((heldValue == null) ? 0 : heldValue.hashCode()); + result = prime * result + (heldValue == null ? 0 : heldValue.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Identity)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Identity)) return false; - Identity<?> other = (Identity<?>) obj; + final Identity<?> other = (Identity<?>) obj; if (heldValue == null) { - if (other.heldValue != null) - return false; - } else if (!heldValue.equals(other.heldValue)) - return false; + if (other.heldValue != null) return false; + } else if (!heldValue.equals(other.heldValue)) return false; return true; } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return (val) -> { return new Identity<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { return new Identity<>(mapper.apply(heldValue)); } @@ -89,32 +84,32 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { heldValue = transformer.apply(heldValue); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValue); } /** * Create a new identity container. - * + * * @param val * The contained value. - * + * * @return A new identity container. */ - public static <ContainedType> Identity<ContainedType> id(ContainedType val) { + public static <ContainedType> Identity<ContainedType> id(final ContainedType val) { return new Identity<>(val); } /** * Create a new empty identity container. - * + * * @return A new empty identity container. */ public static <ContainedType> Identity<ContainedType> id() { diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java index 719b11f..ca41b62 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java @@ -1,13 +1,13 @@ package bjc.utils.data; -import bjc.utils.data.internals.BoundLazy; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; +import bjc.utils.data.internals.BoundLazy; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * A holder that holds a means to create a value, but doesn't actually compute * the value until it's needed @@ -31,7 +31,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * @param value * The seed value to use */ - public Lazy(ContainedType value) { + public Lazy(final ContainedType value) { heldValue = value; valueMaterialized = true; @@ -43,27 +43,26 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * @param supp * The source of a value to use */ - public Lazy(Supplier<ContainedType> supp) { + public Lazy(final Supplier<ContainedType> supp) { valueSupplier = new SingleSupplier<>(supp); valueMaterialized = false; } - private Lazy(Supplier<ContainedType> supp, IList<UnaryOperator<ContainedType>> pendingActions) { + private Lazy(final Supplier<ContainedType> supp, final IList<UnaryOperator<ContainedType>> pendingActions) { valueSupplier = supp; actions = pendingActions; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); - Supplier<ContainedType> supplier = () -> { - if (valueMaterialized) - return heldValue; + final Supplier<ContainedType> supplier = () -> { + if (valueMaterialized) return heldValue; return valueSupplier.get(); }; @@ -74,15 +73,15 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return val -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + final IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); @@ -103,22 +102,21 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { if (valueMaterialized) { if (actions.isEmpty()) return String.format("value[v='%s']", heldValue); - else - return String.format("value[v='%s'] (has pending transforms)", heldValue); + else return String.format("value[v='%s'] (has pending transforms)", heldValue); } return "(unmaterialized)"; } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { actions.add(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { if (!valueMaterialized) { heldValue = valueSupplier.get(); @@ -139,68 +137,58 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { final int prime = 31; int result = 1; - result = prime * result + ((actions == null) ? 0 : actions.hashCode()); - result = prime * result + ((heldValue == null) ? 0 : heldValue.hashCode()); + result = prime * result + (actions == null ? 0 : actions.hashCode()); + result = prime * result + (heldValue == null ? 0 : heldValue.hashCode()); result = prime * result + (valueMaterialized ? 1231 : 1237); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Lazy<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Lazy<?>)) return false; - Lazy<?> other = (Lazy<?>) obj; + final Lazy<?> other = (Lazy<?>) obj; - if (valueMaterialized != other.valueMaterialized) - return false; + if (valueMaterialized != other.valueMaterialized) return false; if (valueMaterialized) { if (heldValue == null) { - if (other.heldValue != null) - return false; - } else if (!heldValue.equals(other.heldValue)) - return false; - } else { - return false; - } + if (other.heldValue != null) return false; + } else if (!heldValue.equals(other.heldValue)) return false; + } else return false; if (actions == null) { - if (other.actions != null) - return false; - } else if (actions.getSize() > 0 || other.actions.getSize() > 0) - return false; + if (other.actions != null) return false; + } else if (actions.getSize() > 0 || other.actions.getSize() > 0) return false; return true; } /** * Create a new lazy container with an already present value. - * + * * @param val * The value for the lazy container. - * + * * @return A new lazy container holding that value. */ - public static <ContainedType> Lazy<ContainedType> lazy(ContainedType val) { + public static <ContainedType> Lazy<ContainedType> lazy(final ContainedType val) { return new Lazy<>(val); } /** * Create a new lazy container with a suspended value. - * + * * @param supp * The suspended value for the lazy container. - * + * * @return A new lazy container that will un-suspend the value when * necessary. */ - public static <ContainedType> Lazy<ContainedType> lazy(Supplier<ContainedType> supp) { + public static <ContainedType> Lazy<ContainedType> lazy(final Supplier<ContainedType> supp) { return new Lazy<>(supp); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java index 70768be..5cb85f3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java @@ -1,12 +1,12 @@ package bjc.utils.data; -import bjc.utils.data.internals.BoundLazyPair; -import bjc.utils.data.internals.HalfBoundLazyPair; - import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; +import bjc.utils.data.internals.BoundLazyPair; +import bjc.utils.data.internals.HalfBoundLazyPair; + /** * A lazy implementation of a pair * @@ -36,7 +36,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> * @param rightVal * The value for the right side of the pair */ - public LazyPair(LeftType leftVal, RightType rightVal) { + public LazyPair(final LeftType leftVal, final RightType rightVal) { leftValue = leftVal; rightValue = rightVal; @@ -52,7 +52,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> * @param rightSupp * The source for a value on the right side of the pair */ - public LazyPair(Supplier<LeftType> leftSupp, Supplier<RightType> rightSupp) { + public LazyPair(final Supplier<LeftType> leftSupp, final Supplier<RightType> rightSupp) { // Use single suppliers to catch double-instantiation bugs leftSupplier = new SingleSupplier<>(leftSupp); rightSupplier = new SingleSupplier<>(rightSupp); @@ -63,16 +63,15 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { + final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { return new BoundLazyPair<>(leftSupplier, rightSupplier, binder); } @Override public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - Supplier<LeftType> leftSupp = () -> { - if (leftMaterialized) - return leftValue; + final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + final Supplier<LeftType> leftSupp = () -> { + if (leftMaterialized) return leftValue; return leftSupplier.get(); }; @@ -82,10 +81,9 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( - Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - Supplier<RightType> rightSupp = () -> { - if (rightMaterialized) - return rightValue; + final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { + final Supplier<RightType> rightSupp = () -> { + if (rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -95,13 +93,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { + final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); - CombinedRight right = rightCombiner.apply(rightVal, otherRight); + final CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); + final CombinedRight right = rightCombiner.apply(rightVal, otherRight); return new LazyPair<>(left, right); }); @@ -131,17 +129,15 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { - Supplier<NewLeft> leftSupp = () -> { - if (leftMaterialized) - return mapper.apply(leftValue); + public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { + final Supplier<NewLeft> leftSupp = () -> { + if (leftMaterialized) return mapper.apply(leftValue); return mapper.apply(leftSupplier.get()); }; - Supplier<RightType> rightSupp = () -> { - if (rightMaterialized) - return rightValue; + final Supplier<RightType> rightSupp = () -> { + if (rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -150,17 +146,15 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { - Supplier<LeftType> leftSupp = () -> { - if (leftMaterialized) - return leftValue; + public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { + final Supplier<LeftType> leftSupp = () -> { + if (leftMaterialized) return leftValue; return leftSupplier.get(); }; - Supplier<NewRight> rightSupp = () -> { - if (rightMaterialized) - return mapper.apply(rightValue); + final Supplier<NewRight> rightSupp = () -> { + if (rightMaterialized) return mapper.apply(rightValue); return mapper.apply(rightSupplier.get()); }; @@ -169,7 +163,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { + public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { if (!leftMaterialized) { leftValue = leftSupplier.get(); @@ -211,48 +205,35 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> int result = 1; result = prime * result + (leftMaterialized ? 1231 : 1237); - result = prime * result + ((leftValue == null) ? 0 : leftValue.hashCode()); + result = prime * result + (leftValue == null ? 0 : leftValue.hashCode()); result = prime * result + (rightMaterialized ? 1231 : 1237); - result = prime * result + ((rightValue == null) ? 0 : rightValue.hashCode()); + result = prime * result + (rightValue == null ? 0 : rightValue.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof LazyPair<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof LazyPair<?, ?>)) return false; - LazyPair<?, ?> other = (LazyPair<?, ?>) obj; + final LazyPair<?, ?> other = (LazyPair<?, ?>) obj; - if (leftMaterialized != other.leftMaterialized) - return false; + if (leftMaterialized != other.leftMaterialized) return false; if (leftMaterialized) { if (leftValue == null) { - if (other.leftValue != null) - return false; - } else if (!leftValue.equals(other.leftValue)) - return false; - } else { - return false; - } + if (other.leftValue != null) return false; + } else if (!leftValue.equals(other.leftValue)) return false; + } else return false; - if (rightMaterialized != other.rightMaterialized) - return false; + if (rightMaterialized != other.rightMaterialized) return false; if (rightMaterialized) { if (rightValue == null) { - if (other.rightValue != null) - return false; - } else if (!rightValue.equals(other.rightValue)) - return false; - } else { - return false; - } + if (other.rightValue != null) return false; + } else if (!rightValue.equals(other.rightValue)) return false; + } else return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java index 8807312..142057c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java @@ -1,12 +1,12 @@ package bjc.utils.data; +import java.util.function.Function; +import java.util.function.UnaryOperator; + import bjc.utils.data.internals.BoundListHolder; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; -import java.util.function.Function; -import java.util.function.UnaryOperator; - /** * A holder that represents a set of non-deterministic computations * @@ -25,50 +25,50 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { * The possible values for the computation */ @SafeVarargs - public ListHolder(ContainedType... values) { + public ListHolder(final ContainedType... values) { heldValues = new FunctionalList<>(); if (values != null) { - for (ContainedType containedValue : values) { + for (final ContainedType containedValue : values) { heldValues.add(containedValue); } } } - private ListHolder(IList<ContainedType> toHold) { + private ListHolder(final IList<ContainedType> toHold) { heldValues = toHold; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - IList<IHolder<BoundType>> boundValues = heldValues.map(binder); + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IList<IHolder<BoundType>> boundValues = heldValues.map(binder); return new BoundListHolder<>(boundValues); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return val -> { return new ListHolder<>(new FunctionalList<>(func.apply(val))); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - IList<MappedType> mappedValues = heldValues.map(mapper); + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + final IList<MappedType> mappedValues = heldValues.map(mapper); return new ListHolder<>(mappedValues); } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { heldValues = heldValues.map(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValues.randItem()); } @@ -82,27 +82,22 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { final int prime = 31; int result = 1; - result = prime * result + ((heldValues == null) ? 0 : heldValues.hashCode()); + result = prime * result + (heldValues == null ? 0 : heldValues.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof ListHolder<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof ListHolder<?>)) return false; - ListHolder<?> other = (ListHolder<?>) obj; + final ListHolder<?> other = (ListHolder<?>) obj; if (heldValues == null) { - if (other.heldValues != null) - return false; - } else if (!heldValues.equals(other.heldValues)) - return false; + if (other.heldValues != null) return false; + } else if (!heldValues.equals(other.heldValues)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java index 718ab6e..37e0cde 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java @@ -20,35 +20,33 @@ public class Option<ContainedType> implements IHolder<ContainedType> { * @param seed * The initial value for the optional */ - public Option(ContainedType seed) { + public Option(final ContainedType seed) { held = seed; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - if (held == null) - return new Option<>(null); + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + if (held == null) return new Option<>(null); return binder.apply(held); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return val -> { return new Option<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - if (held == null) - return new Option<>(null); + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + if (held == null) return new Option<>(null); return new Option<>(mapper.apply(held)); } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { if (held != null) { held = transformer.apply(held); } @@ -57,9 +55,8 @@ public class Option<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { - if (held == null) - return null; + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + if (held == null) return null; return unwrapper.apply(held); } @@ -74,27 +71,22 @@ public class Option<ContainedType> implements IHolder<ContainedType> { final int prime = 31; int result = 1; - result = prime * result + ((held == null) ? 0 : held.hashCode()); + result = prime * result + (held == null ? 0 : held.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Option<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Option<?>)) return false; - Option<?> other = (Option<?>) obj; + final Option<?> other = (Option<?>) obj; if (held == null) { - if (other.held != null) - return false; - } else if (!held.equals(other.held)) - return false; + if (other.held != null) return false; + } else if (!held.equals(other.held)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java index 2fc3106..e6796ba 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java @@ -35,71 +35,65 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { * @param right * The value of the right side */ - public Pair(LeftType left, RightType right) { + public Pair(final LeftType left, final RightType right) { leftValue = left; rightValue = right; } @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if (binder == null) - throw new NullPointerException("Binder must not be null."); + final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { + if (binder == null) throw new NullPointerException("Binder must not be null."); return binder.apply(leftValue, rightValue); } @Override public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if (leftBinder == null) - throw new NullPointerException("Binder must not be null"); + final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + if (leftBinder == null) throw new NullPointerException("Binder must not be null"); return leftBinder.apply(leftValue); } @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( - Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if (rightBinder == null) - throw new NullPointerException("Binder must not be null"); + final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { + if (rightBinder == null) throw new NullPointerException("Binder must not be null"); return rightBinder.apply(rightValue); } @Override public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { + final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { - CombinedLeft left = leftCombiner.apply(leftValue, otherLeft); - CombinedRight right = rightCombiner.apply(rightValue, otherRight); + final CombinedLeft left = leftCombiner.apply(leftValue, otherLeft); + final CombinedRight right = rightCombiner.apply(rightValue, otherRight); return new Pair<>(left, right); }); } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { - if (mapper == null) - throw new NullPointerException("Mapper must not be null"); + public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(mapper.apply(leftValue), rightValue); } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { - if (mapper == null) - throw new NullPointerException("Mapper must not be null"); + public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(leftValue, mapper.apply(rightValue)); } @Override - public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { - if (merger == null) - throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { + if (merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftValue, rightValue); } @@ -114,34 +108,27 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { final int prime = 31; int result = 1; - result = prime * result + ((leftValue == null) ? 0 : leftValue.hashCode()); - result = prime * result + ((rightValue == null) ? 0 : rightValue.hashCode()); + result = prime * result + (leftValue == null ? 0 : leftValue.hashCode()); + result = prime * result + (rightValue == null ? 0 : rightValue.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Pair<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Pair<?, ?>)) return false; - Pair<?, ?> other = (Pair<?, ?>) obj; + final Pair<?, ?> other = (Pair<?, ?>) obj; if (leftValue == null) { - if (other.leftValue != null) - return false; - } else if (!leftValue.equals(other.leftValue)) - return false; + if (other.leftValue != null) return false; + } else if (!leftValue.equals(other.leftValue)) return false; if (rightValue == null) { - if (other.rightValue != null) - return false; - } else if (!rightValue.equals(other.rightValue)) - return false; + if (other.rightValue != null) return false; + } else if (!rightValue.equals(other.rightValue)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java index 0ddb324..4069c3f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java @@ -4,24 +4,24 @@ import java.util.Iterator; /** * An iterator that will only ever yield one item. - * + * * @author EVE * * @param <T> * The type of the item. */ public class SingleIterator<T> implements Iterator<T> { - private T itm; + private final T itm; private boolean yielded; /** * Create a iterator that yields a single item. - * + * * @param item * The item to yield. */ - public SingleIterator(T item) { + public SingleIterator(final T item) { itm = item; yielded = false; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java index fde5111..c675ebf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java @@ -15,11 +15,11 @@ import java.util.function.Supplier; public class SingleSupplier<T> implements Supplier<T> { private static long nextID = 0; - private Supplier<T> source; + private final Supplier<T> source; private boolean gotten; - private long id; + private final long id; /* * This is bad practice, but I want to know where the single @@ -33,7 +33,7 @@ public class SingleSupplier<T> implements Supplier<T> { * @param supp * The supplier to give a single value from */ - public SingleSupplier(Supplier<T> supp) { + public SingleSupplier(final Supplier<T> supp) { source = supp; gotten = false; @@ -44,10 +44,10 @@ public class SingleSupplier<T> implements Supplier<T> { @Override public T get() { if (gotten == true) { - String msg = String.format( + final String msg = String.format( "Attempted to retrieve value more than once from single supplier #%d", id); - IllegalStateException isex = new IllegalStateException(msg); + final IllegalStateException isex = new IllegalStateException(msg); isex.initCause(instSite); @@ -58,7 +58,7 @@ public class SingleSupplier<T> implements Supplier<T> { try { throw new IllegalStateException("Previous instantiation here."); - } catch (IllegalStateException isex) { + } catch (final IllegalStateException isex) { instSite = isex; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Toggle.java b/BJC-Utils2/src/main/java/bjc/utils/data/Toggle.java index 8ebc4d8..1e10dae 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Toggle.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Toggle.java @@ -2,7 +2,7 @@ package bjc.utils.data; /** * A stateful holder that swaps between two values of the same type. - * + * * @author EVE * * @param <E> @@ -12,21 +12,21 @@ public interface Toggle<E> { /** * Retrieve the currently-aligned value of this toggle, and swap the * alignment. - * + * * @return The previously-aligned value. */ E get(); /** * Retrieve the currently-aligned value without altering the alignment. - * + * * @return The currently-aligned value. */ E peek(); /** * Change the alignment of the toggle. - * + * * @param isLeft * Whether the toggle should be left-aligned or not. */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java index 14548a3..014458b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java @@ -1,5 +1,7 @@ package bjc.utils.data; +import static bjc.utils.data.TopDownTransformResult.RTRANSFORM; + import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; @@ -8,34 +10,31 @@ import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; -import static bjc.utils.data.TopDownTransformResult.RTRANSFORM; - - /* * FIXME something is broken in here. fix it. */ @SuppressWarnings("javadoc") public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<ContainedType>> { - private Function<ContainedType, TopDownTransformResult> picker; - private BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transform; + private final Function<ContainedType, TopDownTransformResult> picker; + private final BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transform; private ITree<ContainedType> preParent; private ITree<ContainedType> postParent; - private Deque<ITree<ContainedType>> preChildren; - private Deque<ITree<ContainedType>> postChildren; + private final Deque<ITree<ContainedType>> preChildren; + private final Deque<ITree<ContainedType>> postChildren; private TopDownTransformIterator<ContainedType> curChild; private boolean done; private boolean initial; - private Deque<Iterator<ITree<ContainedType>>> toYield; - private Iterator<ITree<ContainedType>> curYield; + private final Deque<Iterator<ITree<ContainedType>>> toYield; + private Iterator<ITree<ContainedType>> curYield; - public TopDownTransformIterator(Function<ContainedType, TopDownTransformResult> pickr, - BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transfrm, - ITree<ContainedType> tree) { + public TopDownTransformIterator(final Function<ContainedType, TopDownTransformResult> pickr, + final BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transfrm, + final ITree<ContainedType> tree) { preParent = tree; preChildren = new LinkedList<>(); @@ -49,8 +48,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C initial = true; } - public void addYield(Iterator<ITree<ContainedType>> src) { - if(curYield != null) { + public void addYield(final Iterator<ITree<ContainedType>> src) { + if (curYield != null) { toYield.push(curYield); } @@ -62,55 +61,52 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C return !done; } - public ITree<ContainedType> flushYields(ITree<ContainedType> val) { - if(curYield != null) { + public ITree<ContainedType> flushYields(final ITree<ContainedType> val) { + if (curYield != null) { toYield.add(new SingleIterator<>(val)); - if(curYield.hasNext()) + if (curYield.hasNext()) return curYield.next(); else { - while(toYield.size() != 0 && !curYield.hasNext()) { + while (toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if(toYield.size() == 0 && !curYield.hasNext()) { + if (toYield.size() == 0 && !curYield.hasNext()) { curYield = null; return val; - } else - return curYield.next(); + } else return curYield.next(); } - } else - return val; + } else return val; } @Override public ITree<ContainedType> next() { - if(done) throw new NoSuchElementException(); + if (done) throw new NoSuchElementException(); - if(curYield != null) { - if(curYield.hasNext()) + if (curYield != null) { + if (curYield.hasNext()) return curYield.next(); else { - while(toYield.size() != 0 && !curYield.hasNext()) { + while (toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if(toYield.size() == 0 && !curYield.hasNext()) { + if (toYield.size() == 0 && !curYield.hasNext()) { curYield = null; - } else - return curYield.next(); + } else return curYield.next(); } } - if(initial) { - TopDownTransformResult res = picker.apply(preParent.getHead()); + if (initial) { + final TopDownTransformResult res = picker.apply(preParent.getHead()); - switch(res) { + switch (res) { case PASSTHROUGH: postParent = new Tree<>(preParent.getHead()); - if(preParent.getChildrenCount() != 0) { - for(int i = 0; i < preParent.getChildrenCount(); i++) { + if (preParent.getChildrenCount() != 0) { + for (int i = 0; i < preParent.getChildrenCount(); i++) { preChildren.add(preParent.getChild(i)); } @@ -130,8 +126,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C preParent = transform.apply(preParent, this::addYield); return flushYields(preParent); case PUSHDOWN: - if(preParent.getChildrenCount() != 0) { - for(int i = 0; i < preParent.getChildrenCount(); i++) { + if (preParent.getChildrenCount() != 0) { + for (int i = 0; i < preParent.getChildrenCount(); i++) { preChildren.add(preParent.getChild(i)); } @@ -143,12 +139,12 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C this::addYield)); } case PULLUP: - ITree<ContainedType> intRes = transform.apply(preParent, this::addYield); + final ITree<ContainedType> intRes = transform.apply(preParent, this::addYield); postParent = new Tree<>(intRes.getHead()); - if(intRes.getChildrenCount() != 0) { - for(int i = 0; i < intRes.getChildrenCount(); i++) { + if (intRes.getChildrenCount() != 0) { + for (int i = 0; i < intRes.getChildrenCount(); i++) { preChildren.add(intRes.getChild(i)); } @@ -162,16 +158,16 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C throw new IllegalArgumentException("Unknown result type " + res); } - if(res != RTRANSFORM) { + if (res != RTRANSFORM) { initial = false; } } - if(curChild == null || !curChild.hasNext()) { - if(preChildren.size() != 0) { + if (curChild == null || !curChild.hasNext()) { + if (preChildren.size() != 0) { curChild = new TopDownTransformIterator<>(picker, transform, preChildren.pop()); - ITree<ContainedType> res = curChild.next(); + final ITree<ContainedType> res = curChild.next(); System.out.println("\t\tTRACE: adding node " + res + " to children"); postChildren.add(res); @@ -179,12 +175,12 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } else { ITree<ContainedType> res = null; - if(postParent == null) { + if (postParent == null) { res = new Tree<>(preParent.getHead()); System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for(ITree<ContainedType> child : postChildren) { + for (final ITree<ContainedType> child : postChildren) { res.addChild(child); } @@ -194,7 +190,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C res = postParent; System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for(ITree<ContainedType> child : postChildren) { + for (final ITree<ContainedType> child : postChildren) { res.addChild(child); } } @@ -203,7 +199,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C return flushYields(res); } } else { - ITree<ContainedType> res = curChild.next(); + final ITree<ContainedType> res = curChild.next(); System.out.println("\t\tTRACE: adding node " + res + " to children"); postChildren.add(res); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TransformIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/TransformIterator.java index a0987af..50f28b1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TransformIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TransformIterator.java @@ -5,30 +5,30 @@ import java.util.function.Function; /** * An iterator that transforms values from one type to another. - * + * * @author EVE * * @param <S> * The source iterator type. - * + * * @param <D> * The destination iterator type. */ public class TransformIterator<S, D> implements Iterator<D> { - private Iterator<S> source; + private final Iterator<S> source; - private Function<S, D> transform; + private final Function<S, D> transform; /** * Create a new transform iterator. - * + * * @param source * The source iterator to use. - * + * * @param transform * The transform to apply. */ - public TransformIterator(Iterator<S> source, Function<S, D> transform) { + public TransformIterator(final Iterator<S> source, final Function<S, D> transform) { this.source = source; this.transform = transform; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java index 0dc96eb..a52f699 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java @@ -1,15 +1,15 @@ package bjc.utils.data; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.bst.TreeLinearizationMethod; -import bjc.utils.functypes.ListFlattener; - import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.bst.TreeLinearizationMethod; +import bjc.utils.functypes.ListFlattener; + /** * A node in a homogeneous tree. * @@ -33,7 +33,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * @param leaf * The data to store as a leaf node. */ - public Tree(ContainedType leaf) { + public Tree(final ContainedType leaf) { data = leaf; hasChildren = false; @@ -46,11 +46,11 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * * @param leaf * The data to hold in this node. - * + * * @param childrn * A list of children for this node. */ - public Tree(ContainedType leaf, IList<ITree<ContainedType>> childrn) { + public Tree(final ContainedType leaf, final IList<ITree<ContainedType>> childrn) { this(leaf); hasChildren = true; @@ -65,12 +65,12 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * * @param leaf * The data to hold in this node. - * + * * @param childrn * A list of children for this node. */ @SafeVarargs - public Tree(ContainedType leaf, ITree<ContainedType>... childrn) { + public Tree(final ContainedType leaf, final ITree<ContainedType>... childrn) { this(leaf); hasChildren = true; @@ -79,7 +79,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { children = new FunctionalList<>(); - for (ITree<ContainedType> child : childrn) { + for (final ITree<ContainedType> child : childrn) { children.add(child); childCount++; @@ -87,7 +87,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public void addChild(ITree<ContainedType> child) { + public void addChild(final ITree<ContainedType> child) { if (hasChildren == false) { hasChildren = true; @@ -100,7 +100,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public void prependChild(ITree<ContainedType> child) { + public void prependChild(final ITree<ContainedType> child) { if (hasChildren == false) { hasChildren = true; @@ -113,7 +113,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public void doForChildren(Consumer<ITree<ContainedType>> action) { + public void doForChildren(final Consumer<ITree<ContainedType>> action) { if (childCount > 0) { children.forEach(action); } @@ -125,14 +125,12 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public int revFind(Predicate<ITree<ContainedType>> childPred) { - if (childCount == 0) { + public int revFind(final Predicate<ITree<ContainedType>> childPred) { + if (childCount == 0) return -1; - } else { + else { for (int i = childCount - 1; i >= 0; i--) { - if (childPred.test(getChild(i))) { - return i; - } + if (childPred.test(getChild(i))) return i; } } @@ -140,12 +138,12 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action) { + public void traverse(final TreeLinearizationMethod linearizationMethod, final Consumer<ContainedType> action) { if (hasChildren) { switch (linearizationMethod) { case INORDER: if (childCount != 2) { - String msg = "Can only do in-order traversal for binary trees."; + final String msg = "Can only do in-order traversal for binary trees."; throw new IllegalArgumentException(msg); } @@ -176,18 +174,19 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, - Function<ContainedType, ListFlattener<NewType>> nodeCollapser, - Function<NewType, ReturnedType> resultTransformer) { + public <NewType, ReturnedType> ReturnedType collapse(final Function<ContainedType, NewType> leafTransform, + final Function<ContainedType, ListFlattener<NewType>> nodeCollapser, + final Function<NewType, ReturnedType> resultTransformer) { return resultTransformer.apply(internalCollapse(leafTransform, nodeCollapser)); } @Override - public ITree<ContainedType> flatMapTree(Function<ContainedType, ITree<ContainedType>> mapper) { + public ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { if (hasChildren) { - ITree<ContainedType> flatMappedData = mapper.apply(data); + final ITree<ContainedType> flatMappedData = mapper.apply(data); - IList<ITree<ContainedType>> mappedChildren = children.map(child -> child.flatMapTree(mapper)); + final IList<ITree<ContainedType>> mappedChildren = children + .map(child -> child.flatMapTree(mapper)); mappedChildren.forEach(child -> flatMappedData.addChild(child)); @@ -197,13 +196,13 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return mapper.apply(data); } - protected <NewType> NewType internalCollapse(Function<ContainedType, NewType> leafTransform, - Function<ContainedType, ListFlattener<NewType>> nodeCollapser) { + protected <NewType> NewType internalCollapse(final Function<ContainedType, NewType> leafTransform, + final Function<ContainedType, ListFlattener<NewType>> nodeCollapser) { if (hasChildren) { - Function<IList<NewType>, NewType> nodeTransformer = nodeCollapser.apply(data); + final Function<IList<NewType>, NewType> nodeTransformer = nodeCollapser.apply(data); - IList<NewType> collapsedChildren = children.map(child -> { - NewType collapsed = child.collapse(leafTransform, nodeCollapser, + final IList<NewType> collapsedChildren = children.map(child -> { + final NewType collapsed = child.collapse(leafTransform, nodeCollapser, subTreeVal -> subTreeVal); return collapsed; @@ -215,7 +214,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return leafTransform.apply(data); } - protected void internalToString(StringBuilder builder, int indentLevel, boolean initial) { + protected void internalToString(final StringBuilder builder, final int indentLevel, final boolean initial) { for (int i = 0; i < indentLevel; i++) { builder.append(">\t"); } @@ -229,7 +228,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach(child -> { if (child instanceof Tree<?>) { - Tree<ContainedType> kid = (Tree<ContainedType>) child; + final Tree<ContainedType> kid = (Tree<ContainedType>) child; kid.internalToString(builder, indentLevel + 1, false); } else { @@ -244,10 +243,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, - Function<ContainedType, MappedType> operatorTransformer) { + public <MappedType> ITree<MappedType> rebuildTree(final Function<ContainedType, MappedType> leafTransformer, + final Function<ContainedType, MappedType> operatorTransformer) { if (hasChildren) { - IList<ITree<MappedType>> mappedChildren = children.map(child -> { + final IList<ITree<MappedType>> mappedChildren = children.map(child -> { return child.rebuildTree(leafTransformer, operatorTransformer); }); @@ -258,7 +257,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public void selectiveTransform(Predicate<ContainedType> nodePicker, UnaryOperator<ContainedType> transformer) { + public void selectiveTransform(final Predicate<ContainedType> nodePicker, + final UnaryOperator<ContainedType> transformer) { if (hasChildren) { children.forEach(child -> child.selectiveTransform(nodePicker, transformer)); } else { @@ -267,9 +267,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, - UnaryOperator<ITree<ContainedType>> transformer) { - TopDownTransformResult transformResult = transformPicker.apply(data); + public ITree<ContainedType> topDownTransform( + final Function<ContainedType, TopDownTransformResult> transformPicker, + final UnaryOperator<ITree<ContainedType>> transformer) { + final TopDownTransformResult transformResult = transformPicker.apply(data); switch (transformResult) { case PASSTHROUGH: @@ -277,7 +278,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach(child -> { - ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); + final ITree<ContainedType> kid = child.topDownTransform(transformPicker, + transformer); result.addChild(kid); }); @@ -295,7 +297,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach(child -> { - ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); + final ITree<ContainedType> kid = child.topDownTransform(transformPicker, + transformer); result.addChild(kid); }); @@ -303,40 +306,41 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return transformer.apply(result); case PULLUP: - ITree<ContainedType> intermediateResult = transformer.apply(this); + final ITree<ContainedType> intermediateResult = transformer.apply(this); result = new Tree<>(intermediateResult.getHead()); intermediateResult.doForChildren(child -> { - ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); + final ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); result.addChild(kid); }); return result; default: - String msg = String.format("Recieved unknown transform result %s", transformResult); + final String msg = String.format("Recieved unknown transform result %s", transformResult); throw new IllegalArgumentException(msg); } } @Override - public <TransformedType> TransformedType transformChild(int childNo, - Function<ITree<ContainedType>, TransformedType> transformer) { + public <TransformedType> TransformedType transformChild(final int childNo, + final Function<ITree<ContainedType>, TransformedType> transformer) { if (childNo < 0 || childNo > childCount - 1) { - String msg = String.format("Child index #%d is invalid", childNo); + final String msg = String.format("Child index #%d is invalid", childNo); throw new IllegalArgumentException(msg); } - ITree<ContainedType> selectedKid = children.getByIndex(childNo); + final ITree<ContainedType> selectedKid = children.getByIndex(childNo); return transformer.apply(selectedKid); } @Override - public <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer) { + public <TransformedType> TransformedType transformHead( + final Function<ContainedType, TransformedType> transformer) { return transformer.apply(data); } @@ -346,15 +350,15 @@ public class Tree<ContainedType> implements ITree<ContainedType> { int result = 1; result = prime * result + childCount; - result = prime * result + ((children == null) ? 0 : children.hashCode()); - result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + (children == null ? 0 : children.hashCode()); + result = prime * result + (data == null ? 0 : data.hashCode()); return result; } @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); internalToString(builder, 1, true); @@ -364,30 +368,22 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Tree<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Tree<?>)) return false; - Tree<?> other = (Tree<?>) obj; + final Tree<?> other = (Tree<?>) obj; if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; + if (other.data != null) return false; + } else if (!data.equals(other.data)) return false; - if (childCount != other.childCount) - return false; + if (childCount != other.childCount) return false; if (children == null) { - if (other.children != null) - return false; - } else if (!children.equals(other.children)) - return false; + if (other.children != null) return false; + } else if (!children.equals(other.children)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ValueToggle.java b/BJC-Utils2/src/main/java/bjc/utils/data/ValueToggle.java index 5b5cb83..9193896 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ValueToggle.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ValueToggle.java @@ -2,9 +2,9 @@ package bjc.utils.data; /** * A simple implementation of {@link Toggle}. - * + * * @author EVE - * + * * @param <E> * The type of value to toggle between. */ @@ -12,20 +12,20 @@ public class ValueToggle<E> implements Toggle<E> { private final E lft; private final E rght; - private BooleanToggle alignment; + private final BooleanToggle alignment; /** * Create a new toggle. - * + * * All toggles start right-aligned. - * + * * @param left * The value when the toggle is left-aligned. - * + * * @param right * The value when the toggle is right-aligned. */ - public ValueToggle(E left, E right) { + public ValueToggle(final E left, final E right) { lft = left; rght = right; @@ -35,24 +35,20 @@ public class ValueToggle<E> implements Toggle<E> { @Override public E get() { - if(alignment.get()) { + if (alignment.get()) return lft; - } else { - return rght; - } + else return rght; } @Override public E peek() { - if(alignment.peek()) { + if (alignment.peek()) return lft; - } else { - return rght; - } + else return rght; } @Override - public void set(boolean isLeft) { + public void set(final boolean isLeft) { alignment.set(isLeft); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java index cc1c0c0..e5f1b95 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java @@ -1,14 +1,14 @@ package bjc.utils.data.internals; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + import bjc.utils.data.IHolder; import bjc.utils.data.Lazy; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; - /* * Implements a lazy holder that has been bound */ @@ -17,12 +17,12 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont /* * The old value */ - private Supplier<IHolder<OldType>> oldSupplier; + private final Supplier<IHolder<OldType>> oldSupplier; /* * The function to use to transform the old value into a new value */ - private Function<OldType, IHolder<BoundContainedType>> binder; + private final Function<OldType, IHolder<BoundContainedType>> binder; /* * The bound value being held @@ -37,30 +37,31 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont /* * Transformations currently pending on the bound value */ - private IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); + private final IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); /* * Create a new bound lazy value */ - public BoundLazy(Supplier<IHolder<OldType>> supp, Function<OldType, IHolder<BoundContainedType>> binder) { + public BoundLazy(final Supplier<IHolder<OldType>> supp, + final Function<OldType, IHolder<BoundContainedType>> binder) { oldSupplier = supp; this.binder = binder; } @Override - public <BoundType> IHolder<BoundType> bind(Function<BoundContainedType, IHolder<BoundType>> bindr) { + public <BoundType> IHolder<BoundType> bind(final Function<BoundContainedType, IHolder<BoundType>> bindr) { if (bindr == null) throw new NullPointerException("Binder must not be null"); /* * Prepare a list of pending actions */ - IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); + final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); /* * Create the new supplier of a value */ - Supplier<IHolder<BoundContainedType>> typeSupplier = () -> { + final Supplier<IHolder<BoundContainedType>> typeSupplier = () -> { IHolder<BoundContainedType> oldHolder = boundHolder; /* @@ -83,7 +84,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public <NewType> Function<BoundContainedType, IHolder<NewType>> lift( - Function<BoundContainedType, NewType> func) { + final Function<BoundContainedType, NewType> func) { if (func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { @@ -92,15 +93,15 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont } @Override - public <MappedType> IHolder<MappedType> map(Function<BoundContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(final Function<BoundContainedType, MappedType> mapper) { if (mapper == null) throw new NullPointerException("Mapper must not be null"); // Prepare a list of pending actions - IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); + final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); // Prepare the new supplier - Supplier<MappedType> typeSupplier = () -> { + final Supplier<MappedType> typeSupplier = () -> { IHolder<BoundContainedType> oldHolder = boundHolder; // Bound the value if it hasn't been bound @@ -124,7 +125,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont } @Override - public IHolder<BoundContainedType> transform(UnaryOperator<BoundContainedType> transformer) { + public IHolder<BoundContainedType> transform(final UnaryOperator<BoundContainedType> transformer) { if (transformer == null) throw new NullPointerException("Transformer must not be null"); actions.add(transformer); @@ -133,7 +134,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<BoundContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<BoundContainedType, UnwrappedType> unwrapper) { if (unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); if (!holderBound) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java index de290a6..9333e15 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java @@ -1,14 +1,14 @@ package bjc.utils.data.internals; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; import bjc.utils.data.Identity; import bjc.utils.data.LazyPair; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; - /* * Implements a lazy pair that has been bound */ @@ -17,16 +17,16 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai /* * The supplier of the left value */ - private Supplier<OldLeft> leftSupplier; + private final Supplier<OldLeft> leftSupplier; /* * The supplier of the right value */ - private Supplier<OldRight> rightSupplier; + private final Supplier<OldRight> rightSupplier; /* * The binder to transform values */ - private BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> binder; + private final BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> binder; /* * The bound pair @@ -38,8 +38,8 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai */ private boolean pairBound; - public BoundLazyPair(Supplier<OldLeft> leftSupp, Supplier<OldRight> rightSupp, - BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> bindr) { + public BoundLazyPair(final Supplier<OldLeft> leftSupp, final Supplier<OldRight> rightSupp, + final BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> bindr) { leftSupplier = leftSupp; rightSupplier = rightSupp; binder = bindr; @@ -47,14 +47,14 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { - if(bindr == null) throw new NullPointerException("Binder must not be null"); + final BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { + if (bindr == null) throw new NullPointerException("Binder must not be null"); - IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); - IHolder<Boolean> newPairMade = new Identity<>(pairBound); + final IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); + final IHolder<Boolean> newPairMade = new Identity<>(pairBound); - Supplier<NewLeft> leftSupp = () -> { - if(!newPairMade.getValue()) { + final Supplier<NewLeft> leftSupp = () -> { + if (!newPairMade.getValue()) { newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); @@ -63,8 +63,8 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai return newPair.unwrap((pair) -> pair.getLeft()); }; - Supplier<NewRight> rightSupp = () -> { - if(!newPairMade.getValue()) { + final Supplier<NewRight> rightSupp = () -> { + if (!newPairMade.getValue()) { newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); @@ -78,13 +78,13 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft( - Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { - if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); + final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { + if (leftBinder == null) throw new NullPointerException("Left binder must not be null"); - Supplier<NewLeft> leftSupp = () -> { + final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -96,13 +96,13 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundRight> IPair<NewLeft, BoundRight> bindRight( - Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { - if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); + final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { + if (rightBinder == null) throw new NullPointerException("Right binder must not be null"); - Supplier<NewRight> rightSupp = () -> { + final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -114,14 +114,14 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { - if(otherPair == null) + final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { + if (otherPair == null) throw new NullPointerException("Other pair must not be null"); - else if(leftCombiner == null) + else if (leftCombiner == null) throw new NullPointerException("Left combiner must not be null"); - else if(rightCombiner == null) throw new NullPointerException("Right combiner must not be null"); + else if (rightCombiner == null) throw new NullPointerException("Right combiner must not be null"); return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { @@ -132,12 +132,12 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(Function<NewLeft, NewLeftType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); - Supplier<NewLeftType> leftSupp = () -> { - if(!pairBound) { - NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); + final Supplier<NewLeftType> leftSupp = () -> { + if (!pairBound) { + final NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return mapper.apply(leftVal); } @@ -145,8 +145,8 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai return mapper.apply(boundPair.getLeft()); }; - Supplier<NewRight> rightSupp = () -> { - if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); + final Supplier<NewRight> rightSupp = () -> { + if (!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return boundPair.getRight(); }; @@ -155,18 +155,19 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight(Function<NewRight, NewRightType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); - Supplier<NewLeft> leftSupp = () -> { - if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); + final Supplier<NewLeft> leftSupp = () -> { + if (!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return boundPair.getLeft(); }; - Supplier<NewRightType> rightSupp = () -> { - if(!pairBound) { - NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); + final Supplier<NewRightType> rightSupp = () -> { + if (!pairBound) { + final NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()) + .getRight(); return mapper.apply(rightVal); } @@ -178,10 +179,10 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <MergedType> MergedType merge(BiFunction<NewLeft, NewRight, MergedType> merger) { - if(merger == null) throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { + if (merger == null) throw new NullPointerException("Merger must not be null"); - if(!pairBound) { + if (!pairBound) { boundPair = binder.apply(leftSupplier.get(), rightSupplier.get()); pairBound = true; @@ -192,7 +193,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public String toString() { - if(pairBound) return boundPair.toString(); + if (pairBound) return boundPair.toString(); return "(un-materialized)"; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java index c838ce7..65a6f3d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java @@ -1,28 +1,28 @@ package bjc.utils.data.internals; +import java.util.function.Function; +import java.util.function.UnaryOperator; + import bjc.utils.data.IHolder; import bjc.utils.data.ListHolder; import bjc.utils.funcdata.IList; -import java.util.function.Function; -import java.util.function.UnaryOperator; - /* * Holds a list, converted into a holder */ @SuppressWarnings("javadoc") public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { - private IList<IHolder<ContainedType>> heldHolders; + private final IList<IHolder<ContainedType>> heldHolders; - public BoundListHolder(IList<IHolder<ContainedType>> toHold) { + public BoundListHolder(final IList<IHolder<ContainedType>> toHold) { heldHolders = toHold; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - if(binder == null) throw new NullPointerException("Binder must not be null"); + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + if (binder == null) throw new NullPointerException("Binder must not be null"); - IList<IHolder<BoundType>> boundHolders = heldHolders.map((containedHolder) -> { + final IList<IHolder<BoundType>> boundHolders = heldHolders.map((containedHolder) -> { return containedHolder.bind(binder); }); @@ -30,8 +30,8 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { - if(func == null) throw new NullPointerException("Function to lift must not be null"); + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { + if (func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { return new ListHolder<>(func.apply(val)); @@ -39,10 +39,10 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + if (mapper == null) throw new NullPointerException("Mapper must not be null"); - IList<IHolder<MappedType>> mappedHolders = heldHolders.map((containedHolder) -> { + final IList<IHolder<MappedType>> mappedHolders = heldHolders.map((containedHolder) -> { return containedHolder.map(mapper); }); @@ -50,8 +50,8 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { - if(transformer == null) throw new NullPointerException("Transformer must not be null"); + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { + if (transformer == null) throw new NullPointerException("Transformer must not be null"); heldHolders.forEach((containedHolder) -> { containedHolder.transform(transformer); @@ -61,8 +61,8 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { - if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + if (unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); return heldHolders.randItem().unwrap(unwrapper); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java index 35df1c3..a603a7f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java @@ -1,39 +1,40 @@ package bjc.utils.data.internals; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; import bjc.utils.data.Identity; import bjc.utils.data.LazyPair; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; - /* * A lazy pair, with only one side bound */ @SuppressWarnings("javadoc") public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewLeft, NewRight> { - private Supplier<OldType> oldSupplier; + private final Supplier<OldType> oldSupplier; - private Function<OldType, IPair<NewLeft, NewRight>> binder; + private final Function<OldType, IPair<NewLeft, NewRight>> binder; private IPair<NewLeft, NewRight> boundPair; private boolean pairBound; - public HalfBoundLazyPair(Supplier<OldType> oldSupp, Function<OldType, IPair<NewLeft, NewRight>> bindr) { + public HalfBoundLazyPair(final Supplier<OldType> oldSupp, + final Function<OldType, IPair<NewLeft, NewRight>> bindr) { oldSupplier = oldSupp; binder = bindr; } @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { - IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); - IHolder<Boolean> newPairMade = new Identity<>(pairBound); + final BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { + final IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); + final IHolder<Boolean> newPairMade = new Identity<>(pairBound); - Supplier<NewLeft> leftSupp = () -> { - if(!newPairMade.getValue()) { + final Supplier<NewLeft> leftSupp = () -> { + if (!newPairMade.getValue()) { newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } @@ -41,8 +42,8 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL return newPair.unwrap((pair) -> pair.getLeft()); }; - Supplier<NewRight> rightSupp = () -> { - if(!newPairMade.getValue()) { + final Supplier<NewRight> rightSupp = () -> { + if (!newPairMade.getValue()) { newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } @@ -55,11 +56,11 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft( - Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { - Supplier<NewLeft> leftSupp = () -> { + final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { + final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -71,11 +72,11 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <BoundRight> IPair<NewLeft, BoundRight> bindRight( - Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { - Supplier<NewRight> rightSupp = () -> { + final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { + final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -87,9 +88,9 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { + final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { return new LazyPair<>(leftCombiner.apply(leftVal, otherLeft), @@ -99,17 +100,17 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(Function<NewLeft, NewLeftType> mapper) { - Supplier<NewLeftType> leftSupp = () -> { - if(pairBound) return mapper.apply(boundPair.getLeft()); + public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { + final Supplier<NewLeftType> leftSupp = () -> { + if (pairBound) return mapper.apply(boundPair.getLeft()); - NewLeft leftVal = binder.apply(oldSupplier.get()).getLeft(); + final NewLeft leftVal = binder.apply(oldSupplier.get()).getLeft(); return mapper.apply(leftVal); }; - Supplier<NewRight> rightSupp = () -> { - if(pairBound) return boundPair.getRight(); + final Supplier<NewRight> rightSupp = () -> { + if (pairBound) return boundPair.getRight(); return binder.apply(oldSupplier.get()).getRight(); }; @@ -118,17 +119,17 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight(Function<NewRight, NewRightType> mapper) { - Supplier<NewLeft> leftSupp = () -> { - if(pairBound) return boundPair.getLeft(); + public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { + final Supplier<NewLeft> leftSupp = () -> { + if (pairBound) return boundPair.getLeft(); return binder.apply(oldSupplier.get()).getLeft(); }; - Supplier<NewRightType> rightSupp = () -> { - if(pairBound) return mapper.apply(boundPair.getRight()); + final Supplier<NewRightType> rightSupp = () -> { + if (pairBound) return mapper.apply(boundPair.getRight()); - NewRight rightVal = binder.apply(oldSupplier.get()).getRight(); + final NewRight rightVal = binder.apply(oldSupplier.get()).getRight(); return mapper.apply(rightVal); }; @@ -137,8 +138,8 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <MergedType> MergedType merge(BiFunction<NewLeft, NewRight, MergedType> merger) { - if(!pairBound) { + public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { + if (!pairBound) { boundPair = binder.apply(oldSupplier.get()); pairBound = true; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedLazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedLazy.java index de161e5..d2e2b98 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedLazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedLazy.java @@ -1,28 +1,28 @@ package bjc.utils.data.internals; -import bjc.utils.data.IHolder; -import bjc.utils.data.Lazy; - import java.util.function.Function; import java.util.function.UnaryOperator; +import bjc.utils.data.IHolder; +import bjc.utils.data.Lazy; + @SuppressWarnings("javadoc") public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { - private IHolder<IHolder<ContainedType>> held; + private final IHolder<IHolder<ContainedType>> held; - public WrappedLazy(IHolder<ContainedType> wrappedHolder) { + public WrappedLazy(final IHolder<ContainedType> wrappedHolder) { held = new Lazy<>(wrappedHolder); } // This has an extra parameter, because otherwise it erases to the same // as the public one - private WrappedLazy(IHolder<IHolder<ContainedType>> wrappedHolder, boolean dummy) { + private WrappedLazy(final IHolder<IHolder<ContainedType>> wrappedHolder, final boolean dummy) { held = wrappedHolder; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { return containedHolder.bind(binder); }); @@ -30,15 +30,15 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return (val) -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + final IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { return containedHolder.map(mapper); }); @@ -46,7 +46,7 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { held.transform((containedHolder) -> { return containedHolder.transform(transformer); }); @@ -55,7 +55,7 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return held.unwrap((containedHolder) -> { return containedHolder.unwrap(unwrapper); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java index e98332c..da53ab8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java @@ -1,28 +1,28 @@ package bjc.utils.data.internals; -import bjc.utils.data.IHolder; -import bjc.utils.data.Option; - import java.util.function.Function; import java.util.function.UnaryOperator; +import bjc.utils.data.IHolder; +import bjc.utils.data.Option; + @SuppressWarnings("javadoc") public class WrappedOption<ContainedType> implements IHolder<ContainedType> { - private IHolder<IHolder<ContainedType>> held; + private final IHolder<IHolder<ContainedType>> held; - public WrappedOption(IHolder<ContainedType> seedValue) { + public WrappedOption(final IHolder<ContainedType> seedValue) { held = new Option<>(seedValue); } - private WrappedOption(IHolder<IHolder<ContainedType>> toHold, boolean dummy) { + private WrappedOption(final IHolder<IHolder<ContainedType>> toHold, final boolean dummy) { held = toHold; } @Override - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { - IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { return containedHolder.bind((containedValue) -> { - if(containedValue == null) return new Option<>(null); + if (containedValue == null) return new Option<>(null); return binder.apply(containedValue); }); @@ -32,17 +32,17 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { return (val) -> { return new Option<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { - IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + final IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { return containedHolder.map((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) return null; return mapper.apply(containedValue); }); @@ -52,10 +52,10 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { held.transform((containedHolder) -> { return containedHolder.transform((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) return null; return transformer.apply(containedValue); }); @@ -65,10 +65,10 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return held.unwrap((containedHolder) -> { return containedHolder.unwrap((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) return null; return unwrapper.apply(containedValue); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/AbbrevMap.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/AbbrevMap.java index 433f672..75c3c1b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/AbbrevMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/AbbrevMap.java @@ -1,21 +1,21 @@ package bjc.utils.esodata; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IMap; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IMap; /** * Represents a mapping from a set of strings to a mapping of all unambiguous * prefixes of their respective strings. - * + * * This works the same as Ruby's Abbrev. - * + * * @author EVE * */ @@ -23,7 +23,7 @@ public class AbbrevMap { /* * All of the words we have abbreviations for. */ - private Set<String> wrds; + private final Set<String> wrds; /* * Maps abbreviations to their strings. @@ -42,11 +42,11 @@ public class AbbrevMap { /** * Create a new abbreviation map. - * + * * @param words * The initial set of words to put in the map. */ - public AbbrevMap(String... words) { + public AbbrevMap(final String... words) { wrds = new HashSet<>(Arrays.asList(words)); recalculate(); @@ -62,7 +62,7 @@ public class AbbrevMap { seen = new HashSet<>(); - for (String word : wrds) { + for (final String word : wrds) { /* * A word always abbreviates to itself. */ @@ -74,14 +74,14 @@ public class AbbrevMap { /** * Adds words to the abbreviation map. - * + * * @param words * The words to add to the abbreviation map. */ - public void addWords(String... words) { + public void addWords(final String... words) { wrds.addAll(Arrays.asList(words)); - for (String word : words) { + for (final String word : words) { /* * A word always abbreviates to itself. */ @@ -94,18 +94,17 @@ public class AbbrevMap { /* * Actually add abbreviations of a word. */ - private void intAddWord(String word) { + private void intAddWord(final String word) { /* * Skip blank words. */ - if (word.equals("")) - return; + if (word.equals("")) return; /* * Handle each possible abbreviation. */ for (int i = word.length(); i > 0; i--) { - String subword = word.substring(0, i); + final String subword = word.substring(0, i); if (seen.contains(subword)) { /* @@ -113,7 +112,7 @@ public class AbbrevMap { * whole word. */ if (abbrevMap.containsKey(subword) && !wrds.contains(subword)) { - String oldword = abbrevMap.remove(subword); + final String oldword = abbrevMap.remove(subword); ambMap.put(subword, oldword); ambMap.put(subword, word); @@ -130,17 +129,17 @@ public class AbbrevMap { /** * Removes words from the abbreviation map. - * + * * NOTE: There may be inconsistent behavior. Use * {@link AbbrevMap#recalculate()} to fix it if it occurs. - * + * * @param words * The words to remove. */ - public void removeWords(String... words) { + public void removeWords(final String... words) { wrds.removeAll(Arrays.asList(words)); - for (String word : words) { + for (final String word : words) { intRemoveWord(word); } } @@ -148,30 +147,29 @@ public class AbbrevMap { /* * Actually remove a word. */ - private void intRemoveWord(String word) { + private void intRemoveWord(final String word) { /* * Skip blank words. */ - if (word.equals("")) - return; + if (word.equals("")) return; /* * Handle each possible abbreviation. */ for (int i = word.length(); i > 0; i--) { - String subword = word.substring(0, i); + final String subword = word.substring(0, i); - if (abbrevMap.containsKey(subword)) + if (abbrevMap.containsKey(subword)) { abbrevMap.remove(subword); - else { + } else { ambMap.remove(subword, word); - Set<String> possWords = ambMap.get(subword); + final Set<String> possWords = ambMap.get(subword); if (possWords.size() == 0) { seen.remove(subword); } else if (possWords.size() == 1) { - String newWord = possWords.iterator().next(); + final String newWord = possWords.iterator().next(); abbrevMap.put(subword, newWord); ambMap.remove(subword, newWord); @@ -183,17 +181,16 @@ public class AbbrevMap { /** * Convert an abbreviation into all the strings it could abbreviate * into. - * + * * @param abbrev * The abbreviation to convert. - * + * * @return All the expansions for the provided abbreviation. */ - public String[] deabbrev(String abbrev) { + public String[] deabbrev(final String abbrev) { if (abbrevMap.containsKey(abbrev)) return new String[] { abbrevMap.get(abbrev) }; - else - return ambMap.get(abbrev).toArray(new String[0]); + else return ambMap.get(abbrev).toArray(new String[0]); } @Override @@ -201,34 +198,29 @@ public class AbbrevMap { final int prime = 31; int result = 1; - result = prime * result + ((wrds == null) ? 0 : wrds.hashCode()); + result = prime * result + (wrds == null ? 0 : wrds.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof AbbrevMap)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof AbbrevMap)) return false; - AbbrevMap other = (AbbrevMap) obj; + final AbbrevMap other = (AbbrevMap) obj; if (wrds == null) { - if (other.wrds != null) - return false; - } else if (!wrds.equals(other.wrds)) - return false; + if (other.wrds != null) return false; + } else if (!wrds.equals(other.wrds)) return false; return true; } @Override public String toString() { - String fmt = "AbbrevMap [wrds=%s, abbrevMap=%s, seen=%s, ambMap=%s]"; + final String fmt = "AbbrevMap [wrds=%s, abbrevMap=%s, seen=%s, ambMap=%s]"; return String.format(fmt, wrds, abbrevMap, seen, ambMap); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java index 52e3172..17b70f5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java @@ -59,11 +59,10 @@ public interface Directory<K, V> { * @return The new sub-directory, or null if one by that name already
* exists.
*/
- default Directory<K, V> newSubdirectory(K key) {
- if (hasSubdirectory(key))
- return null;
+ default Directory<K, V> newSubdirectory(final K key) {
+ if (hasSubdirectory(key)) return null;
- Directory<K, V> dir = new SimpleDirectory<>();
+ final Directory<K, V> dir = new SimpleDirectory<>();
putSubdirectory(key, dir);
diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java index 8df7aa9..0faaabf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java @@ -42,7 +42,7 @@ public class DoubleTape<T> implements Tape<T> { * Whether or not to auto-extend the tape to the right w/ * nulls. */ - public DoubleTape(boolean autoExtnd) { + public DoubleTape(final boolean autoExtnd) { front = new SingleTape<>(autoExtnd); back = new SingleTape<>(autoExtnd); } @@ -64,7 +64,7 @@ public class DoubleTape<T> implements Tape<T> { * The new value for the tape item. */ @Override - public void item(T itm) { + public void item(final T itm) { front.item(itm); } @@ -85,7 +85,7 @@ public class DoubleTape<T> implements Tape<T> { * The item to add. */ @Override - public void insertBefore(T itm) { + public void insertBefore(final T itm) { front.insertBefore(itm); back.insertAfter(null); } @@ -94,7 +94,7 @@ public class DoubleTape<T> implements Tape<T> { * Insert an element after the current item. */ @Override - public void insertAfter(T itm) { + public void insertAfter(final T itm) { front.insertAfter(itm); back.insertBefore(itm); } @@ -156,8 +156,8 @@ public class DoubleTape<T> implements Tape<T> { * @return True if the cursor was moved left. */ @Override - public boolean left(int amt) { - boolean succ = front.left(amt); + public boolean left(final int amt) { + final boolean succ = front.left(amt); if (succ) { back.right(amt); @@ -189,8 +189,8 @@ public class DoubleTape<T> implements Tape<T> { * @return Whether the cursor was moved right. */ @Override - public boolean right(int amt) { - boolean succ = front.right(amt); + public boolean right(final int amt) { + final boolean succ = front.right(amt); if (succ) { back.left(amt); @@ -206,7 +206,7 @@ public class DoubleTape<T> implements Tape<T> { * active. */ public void flip() { - Tape<T> tmp = front; + final Tape<T> tmp = front; front = back; @@ -222,33 +222,26 @@ public class DoubleTape<T> implements Tape<T> { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((back == null) ? 0 : back.hashCode()); - result = prime * result + ((front == null) ? 0 : front.hashCode()); + result = prime * result + (back == null ? 0 : back.hashCode()); + result = prime * result + (front == null ? 0 : front.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof DoubleTape<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof DoubleTape<?>)) return false; - DoubleTape<?> other = (DoubleTape<?>) obj; + final DoubleTape<?> other = (DoubleTape<?>) obj; if (back == null) { - if (other.back != null) - return false; - } else if (!back.equals(other.back)) - return false; + if (other.back != null) return false; + } else if (!back.equals(other.back)) return false; if (front == null) { - if (other.front != null) - return false; - } else if (!front.equals(other.front)) - return false; + if (other.front != null) return false; + } else if (!front.equals(other.front)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/PushdownMap.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/PushdownMap.java index bf72f29..a631704 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/PushdownMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/PushdownMap.java @@ -1,17 +1,17 @@ package bjc.utils.esodata; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.IMap; - import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.IMap; + /** * A variant of a map where inserting a duplicate key shadows the existing value * instead of replacing it. - * + * * @author EVE * * @param <KeyType> @@ -20,7 +20,7 @@ import java.util.function.Function; * The values in the map. */ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { - private IMap<KeyType, Stack<ValueType>> backing; + private final IMap<KeyType, Stack<ValueType>> backing; /** * Create a new empty stack-based map. @@ -29,7 +29,7 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> backing = new FunctionalMap<>(); } - private PushdownMap(IMap<KeyType, Stack<ValueType>> back) { + private PushdownMap(final IMap<KeyType, Stack<ValueType>> back) { backing = back; } @@ -39,7 +39,7 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> } @Override - public boolean containsKey(KeyType key) { + public boolean containsKey(final KeyType key) { return backing.containsKey(key); } @@ -49,22 +49,22 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> } @Override - public void forEach(BiConsumer<KeyType, ValueType> action) { + public void forEach(final BiConsumer<KeyType, ValueType> action) { backing.forEach((key, stk) -> action.accept(key, stk.top())); } @Override - public void forEachKey(Consumer<KeyType> action) { + public void forEachKey(final Consumer<KeyType> action) { backing.forEachKey(action); } @Override - public void forEachValue(Consumer<ValueType> action) { + public void forEachValue(final Consumer<ValueType> action) { backing.forEachValue(stk -> action.accept(stk.top())); } @Override - public ValueType get(KeyType key) { + public ValueType get(final KeyType key) { return backing.get(key).top(); } @@ -79,22 +79,22 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> } @Override - public <V2> IMap<KeyType, V2> transform(Function<ValueType, V2> transformer) { + public <V2> IMap<KeyType, V2> transform(final Function<ValueType, V2> transformer) { throw new UnsupportedOperationException("Cannot transform pushdown maps."); } @Override - public ValueType put(KeyType key, ValueType val) { + public ValueType put(final KeyType key, final ValueType val) { if (backing.containsKey(key)) { - Stack<ValueType> stk = backing.get(key); + final Stack<ValueType> stk = backing.get(key); - ValueType vl = stk.top(); + final ValueType vl = stk.top(); stk.push(val); return vl; } else { - Stack<ValueType> stk = new SimpleStack<>(); + final Stack<ValueType> stk = new SimpleStack<>(); stk.push(val); @@ -103,14 +103,12 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> } @Override - public ValueType remove(KeyType key) { - Stack<ValueType> stk = backing.get(key); + public ValueType remove(final KeyType key) { + final Stack<ValueType> stk = backing.get(key); - if (stk.size() > 1) { + if (stk.size() > 1) return stk.pop(); - } else { - return backing.remove(key).top(); - } + else return backing.remove(key).top(); } @Override @@ -123,27 +121,22 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> final int prime = 31; int result = 1; - result = prime * result + ((backing == null) ? 0 : backing.hashCode()); + result = prime * result + (backing == null ? 0 : backing.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof PushdownMap<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof PushdownMap<?, ?>)) return false; - PushdownMap<?, ?> other = (PushdownMap<?, ?>) obj; + final PushdownMap<?, ?> other = (PushdownMap<?, ?>) obj; if (backing == null) { - if (other.backing != null) - return false; - } else if (!backing.equals(other.backing)) - return false; + if (other.backing != null) return false; + } else if (!backing.equals(other.backing)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java index ebb9d8c..850598a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java @@ -11,7 +11,7 @@ import java.util.LinkedList; * @author Ben Culkin */ public class QueueStack<T> extends Stack<T> { - private Deque<T> backing; + private final Deque<T> backing; /** * Create a new empty stack queue. @@ -22,22 +22,20 @@ public class QueueStack<T> extends Stack<T> { } @Override - public void push(T elm) { + public void push(final T elm) { backing.add(elm); } @Override public T pop() { - if (backing.isEmpty()) - throw new StackUnderflowException(); + if (backing.isEmpty()) throw new StackUnderflowException(); return backing.remove(); } @Override public T top() { - if (backing.isEmpty()) - throw new StackUnderflowException(); + if (backing.isEmpty()) throw new StackUnderflowException(); return backing.peek(); } @@ -68,27 +66,22 @@ public class QueueStack<T> extends Stack<T> { final int prime = 31; int result = 1; - result = prime * result + ((backing == null) ? 0 : backing.hashCode()); + result = prime * result + (backing == null ? 0 : backing.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof QueueStack<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof QueueStack<?>)) return false; - QueueStack<?> other = (QueueStack<?>) obj; + final QueueStack<?> other = (QueueStack<?>) obj; if (backing == null) { - if (other.backing != null) - return false; - } else if (!backing.equals(other.backing)) - return false; + if (other.backing != null) return false; + } else if (!backing.equals(other.backing)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java index bab64f5..69fd019 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java @@ -16,9 +16,9 @@ import bjc.utils.funcdata.IMap; * The value type of the directory. */ public class SimpleDirectory<K, V> implements Directory<K, V> { - private IMap<K, Directory<K, V>> children; + private final IMap<K, Directory<K, V>> children; - private IMap<K, V> data; + private final IMap<K, V> data; /** * Create a new directory. @@ -29,32 +29,32 @@ public class SimpleDirectory<K, V> implements Directory<K, V> { } @Override - public Directory<K, V> getSubdirectory(K key) { + public Directory<K, V> getSubdirectory(final K key) { return children.get(key); } @Override - public boolean hasSubdirectory(K key) { + public boolean hasSubdirectory(final K key) { return children.containsKey(key); } @Override - public Directory<K, V> putSubdirectory(K key, Directory<K, V> val) { + public Directory<K, V> putSubdirectory(final K key, final Directory<K, V> val) { return children.put(key, val); } @Override - public boolean containsKey(K key) { + public boolean containsKey(final K key) { return data.containsKey(key); } @Override - public V getKey(K key) { + public V getKey(final K key) { return data.get(key); } @Override - public V putKey(K key, V val) { + public V putKey(final K key, final V val) { return data.put(key, val); } @@ -63,34 +63,27 @@ public class SimpleDirectory<K, V> implements Directory<K, V> { final int prime = 31; int result = 1; - result = prime * result + ((children == null) ? 0 : children.hashCode()); - result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + (children == null ? 0 : children.hashCode()); + result = prime * result + (data == null ? 0 : data.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof SimpleDirectory<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof SimpleDirectory<?, ?>)) return false; - SimpleDirectory<?, ?> other = (SimpleDirectory<?, ?>) obj; + final SimpleDirectory<?, ?> other = (SimpleDirectory<?, ?>) obj; if (children == null) { - if (other.children != null) - return false; - } else if (!children.equals(other.children)) - return false; + if (other.children != null) return false; + } else if (!children.equals(other.children)) return false; if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; + if (other.data != null) return false; + } else if (!data.equals(other.data)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java index 0e109aa..fdb3300 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java @@ -11,7 +11,7 @@ import java.util.LinkedList; * @author Ben Culkin */ public class SimpleStack<T> extends Stack<T> { - private Deque<T> backing; + private final Deque<T> backing; /** * Create a new empty stack. @@ -22,22 +22,20 @@ public class SimpleStack<T> extends Stack<T> { } @Override - public void push(T elm) { + public void push(final T elm) { backing.push(elm); } @Override public T pop() { - if (backing.isEmpty()) - throw new StackUnderflowException(); + if (backing.isEmpty()) throw new StackUnderflowException(); return backing.pop(); } @Override public T top() { - if (backing.isEmpty()) - throw new StackUnderflowException(); + if (backing.isEmpty()) throw new StackUnderflowException(); return backing.peek(); } @@ -52,6 +50,7 @@ public class SimpleStack<T> extends Stack<T> { return backing.size() == 0; } + @Override @SuppressWarnings("unchecked") public T[] toArray() { return (T[]) backing.toArray(); @@ -62,27 +61,22 @@ public class SimpleStack<T> extends Stack<T> { final int prime = 31; int result = 1; - result = prime * result + ((backing == null) ? 0 : backing.hashCode()); + result = prime * result + (backing == null ? 0 : backing.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof SimpleStack<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof SimpleStack<?>)) return false; - SimpleStack<?> other = (SimpleStack<?>) obj; + final SimpleStack<?> other = (SimpleStack<?>) obj; if (backing == null) { - if (other.backing != null) - return false; - } else if (!backing.equals(other.backing)) - return false; + if (other.backing != null) return false; + } else if (!backing.equals(other.backing)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java index 253c15f..a3e5462 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java @@ -16,7 +16,7 @@ import java.util.ArrayList; * * @param <T> * The element type of the tape. - * + * * @author bjculkin */ public class SingleTape<T> implements Tape<T> { @@ -40,7 +40,7 @@ public class SingleTape<T> implements Tape<T> { * Whether or not to auto-extend the tape to the right w/ * nulls. */ - public SingleTape(boolean autoExtnd) { + public SingleTape(final boolean autoExtnd) { autoExtend = autoExtnd; backing = new ArrayList<>(); @@ -63,7 +63,7 @@ public class SingleTape<T> implements Tape<T> { * The new value for the tape item. */ @Override - public void item(T itm) { + public void item(final T itm) { backing.set(pos, itm); } @@ -84,7 +84,7 @@ public class SingleTape<T> implements Tape<T> { * The item to add. */ @Override - public void insertBefore(T itm) { + public void insertBefore(final T itm) { backing.add(pos, itm); } @@ -92,7 +92,7 @@ public class SingleTape<T> implements Tape<T> { * Insert an element after the current item. */ @Override - public void insertAfter(T itm) { + public void insertAfter(final T itm) { if (pos == backing.size() - 1) { backing.add(itm); } else { @@ -110,7 +110,7 @@ public class SingleTape<T> implements Tape<T> { */ @Override public T remove() { - T res = backing.remove(pos); + final T res = backing.remove(pos); if (pos != 0) { pos -= 1; } @@ -157,9 +157,8 @@ public class SingleTape<T> implements Tape<T> { * @return True if the cursor was moved left. */ @Override - public boolean left(int amt) { - if (pos - amt < 0) - return false; + public boolean left(final int amt) { + if (pos - amt < 0) return false; pos -= amt; return true; @@ -188,14 +187,13 @@ public class SingleTape<T> implements Tape<T> { * @return Whether the cursor was moved right. */ @Override - public boolean right(int amt) { + public boolean right(final int amt) { if (pos + amt >= backing.size() - 1) { if (autoExtend) { while (pos + amt >= backing.size() - 1) { backing.add(null); } - } else - return false; + } else return false; } pos += amt; @@ -212,27 +210,22 @@ public class SingleTape<T> implements Tape<T> { final int prime = 31; int result = 1; - result = prime * result + ((backing == null) ? 0 : backing.hashCode()); + result = prime * result + (backing == null ? 0 : backing.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof SingleTape<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof SingleTape<?>)) return false; - SingleTape<?> other = (SingleTape<?>) obj; + final SingleTape<?> other = (SingleTape<?>) obj; if (backing == null) { - if (other.backing != null) - return false; - } else if (!backing.equals(other.backing)) - return false; + if (other.backing != null) return false; + } else if (!backing.equals(other.backing)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java index 6fc4766..7c8c757 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java @@ -11,9 +11,9 @@ import java.util.stream.Stream; * @author Ben Culkin */ class SpaghettiStack<T> extends Stack<T> { - private Stack<T> backing; + private final Stack<T> backing; - private Stack<T> parent; + private final Stack<T> parent; /** * Create a new empty spaghetti stack, off of the specified parent. @@ -21,29 +21,27 @@ class SpaghettiStack<T> extends Stack<T> { * @param par * The parent stack */ - public SpaghettiStack(Stack<T> par) { + public SpaghettiStack(final Stack<T> par) { backing = new SimpleStack<>(); parent = par; } @Override - public void push(T elm) { + public void push(final T elm) { backing.push(elm); } @Override public T pop() { - if (backing.empty()) - return parent.pop(); + if (backing.empty()) return parent.pop(); return backing.pop(); } @Override public T top() { - if (backing.empty()) - return parent.top(); + if (backing.empty()) return parent.top(); return backing.top(); } @@ -69,34 +67,27 @@ class SpaghettiStack<T> extends Stack<T> { final int prime = 31; int result = 1; - result = prime * result + ((backing == null) ? 0 : backing.hashCode()); - result = prime * result + ((parent == null) ? 0 : parent.hashCode()); + result = prime * result + (backing == null ? 0 : backing.hashCode()); + result = prime * result + (parent == null ? 0 : parent.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof SpaghettiStack<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof SpaghettiStack<?>)) return false; - SpaghettiStack<?> other = (SpaghettiStack<?>) obj; + final SpaghettiStack<?> other = (SpaghettiStack<?>) obj; if (backing == null) { - if (other.backing != null) - return false; - } else if (!backing.equals(other.backing)) - return false; + if (other.backing != null) return false; + } else if (!backing.equals(other.backing)) return false; if (parent == null) { - if (other.parent != null) - return false; - } else if (!parent.equals(other.parent)) - return false; + if (other.parent != null) return false; + } else if (!parent.equals(other.parent)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java index 217c671..9d74e9a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java @@ -17,21 +17,26 @@ import java.util.function.Consumer; * thrown. Check the size of the stack if you want to avoid this. * <p> * </p> - * + * * @param <T> * The datatype stored in the stack. - * + * * @author Ben Culkin */ public abstract class Stack<T> { /** * The exception thrown when attempting to access an element from the * stack that isn't there. - * + * * @author EVE * */ public static class StackUnderflowException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1423867176204571539L; } /** @@ -52,7 +57,7 @@ public abstract class Stack<T> { /** * Retrieve the top element of this stack without removing it from the * stack. - * + * * @return The top element of this stack. */ public abstract T top(); @@ -90,7 +95,7 @@ public abstract class Stack<T> { * @param n * The number of items to drop. */ - public void drop(int n) { + public void drop(final int n) { for (int i = 0; i < n; i++) { pop(); } @@ -109,8 +114,8 @@ public abstract class Stack<T> { * @param n * The number of items below the top to delete. */ - public void nip(int n) { - T elm = pop(); + public void nip(final int n) { + final T elm = pop(); drop(n); @@ -132,15 +137,15 @@ public abstract class Stack<T> { * @param m * The number of times to duplicate items. */ - public void multidup(int n, int m) { - List<T> lst = new ArrayList<>(n); + public void multidup(final int n, final int m) { + final List<T> lst = new ArrayList<>(n); for (int i = n; i > 0; i--) { lst.set(i - 1, pop()); } for (int i = 0; i < m; i++) { - for (T elm : lst) { + for (final T elm : lst) { push(elm); } } @@ -152,7 +157,7 @@ public abstract class Stack<T> { * @param n * The number of items to duplicate. */ - public void dup(int n) { + public void dup(final int n) { multidup(n, 2); } @@ -171,22 +176,22 @@ public abstract class Stack<T> { * @param m * The number of times to duplicate items. */ - public void multiover(int n, int m) { - List<T> lst = new ArrayList<>(n); + public void multiover(final int n, final int m) { + final List<T> lst = new ArrayList<>(n); - T elm = pop(); + final T elm = pop(); for (int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for (T nelm : lst) { + for (final T nelm : lst) { push(nelm); } push(elm); for (int i = 1; i < m; i++) { - for (T nelm : lst) { + for (final T nelm : lst) { push(nelm); } } @@ -198,7 +203,7 @@ public abstract class Stack<T> { * @param n * The number of items to duplicate. */ - public void over(int n) { + public void over(final int n) { multiover(n, 2); } @@ -213,9 +218,9 @@ public abstract class Stack<T> { * Duplicate the third item in the stack. */ public void pick() { - T z = pop(); - T y = pop(); - T x = pop(); + final T z = pop(); + final T y = pop(); + final T x = pop(); push(x); push(y); @@ -227,8 +232,8 @@ public abstract class Stack<T> { * Swap the top two items on the stack. */ public void swap() { - T y = pop(); - T x = pop(); + final T y = pop(); + final T x = pop(); push(y); push(x); @@ -238,8 +243,8 @@ public abstract class Stack<T> { * Duplicate the second item below the first item. */ public void deepdup() { - T y = pop(); - T x = pop(); + final T y = pop(); + final T x = pop(); push(x); push(x); @@ -250,9 +255,9 @@ public abstract class Stack<T> { * Swap the second and third items in the stack. */ public void deepswap() { - T z = pop(); - T y = pop(); - T x = pop(); + final T z = pop(); + final T y = pop(); + final T x = pop(); push(y); push(x); @@ -263,9 +268,9 @@ public abstract class Stack<T> { * Rotate the top three items on the stack */ public void rot() { - T z = pop(); - T y = pop(); - T x = pop(); + final T z = pop(); + final T y = pop(); + final T x = pop(); push(y); push(z); @@ -276,9 +281,9 @@ public abstract class Stack<T> { * Inversely rotate the top three items on the stack */ public void invrot() { - T z = pop(); - T y = pop(); - T x = pop(); + final T z = pop(); + final T y = pop(); + final T x = pop(); push(z); push(x); @@ -296,8 +301,8 @@ public abstract class Stack<T> { * @param cons * The action to hide the elements from */ - public void dip(int n, Consumer<Stack<T>> cons) { - List<T> elms = new ArrayList<>(n); + public void dip(final int n, final Consumer<Stack<T>> cons) { + final List<T> elms = new ArrayList<>(n); for (int i = n; i > 0; i--) { elms.set(i - 1, pop()); @@ -305,7 +310,7 @@ public abstract class Stack<T> { cons.accept(this); - for (T elm : elms) { + for (final T elm : elms) { push(elm); } } @@ -316,7 +321,7 @@ public abstract class Stack<T> { * @param cons * The action to hide the top from */ - public void dip(Consumer<Stack<T>> cons) { + public void dip(final Consumer<Stack<T>> cons) { dip(1, cons); } @@ -329,7 +334,7 @@ public abstract class Stack<T> { * @param cons * The action to execute. */ - public void keep(int n, Consumer<Stack<T>> cons) { + public void keep(final int n, final Consumer<Stack<T>> cons) { dup(n); dip(n, cons); } @@ -342,15 +347,15 @@ public abstract class Stack<T> { * @param conses * The actions to execute. */ - public void multicleave(int n, List<Consumer<Stack<T>>> conses) { - List<T> elms = new ArrayList<>(n); + public void multicleave(final int n, final List<Consumer<Stack<T>>> conses) { + final List<T> elms = new ArrayList<>(n); for (int i = n; i > 0; i--) { elms.set(i - 1, pop()); } - for (Consumer<Stack<T>> cons : conses) { - for (T elm : elms) { + for (final Consumer<Stack<T>> cons : conses) { + for (final T elm : elms) { push(elm); } @@ -364,7 +369,7 @@ public abstract class Stack<T> { * @param conses * The actions to execute. */ - public void cleave(List<Consumer<Stack<T>>> conses) { + public void cleave(final List<Consumer<Stack<T>>> conses) { multicleave(1, conses); } @@ -376,11 +381,11 @@ public abstract class Stack<T> { * @param conses * The actions to execute. */ - public void multispread(int n, List<Consumer<Stack<T>>> conses) { - List<List<T>> nelms = new ArrayList<>(conses.size()); + public void multispread(final int n, final List<Consumer<Stack<T>>> conses) { + final List<List<T>> nelms = new ArrayList<>(conses.size()); for (int i = conses.size(); i > 0; i--) { - List<T> elms = new ArrayList<>(n); + final List<T> elms = new ArrayList<>(n); for (int j = n; j > 0; j--) { elms.set(j, pop()); @@ -390,8 +395,8 @@ public abstract class Stack<T> { } int i = 0; - for (List<T> elms : nelms) { - for (T elm : elms) { + for (final List<T> elms : nelms) { + for (final T elm : elms) { push(elm); } @@ -406,7 +411,7 @@ public abstract class Stack<T> { * @param conses * The actions to execute. */ - public void spread(List<Consumer<Stack<T>>> conses) { + public void spread(final List<Consumer<Stack<T>>> conses) { multispread(1, conses); } @@ -420,8 +425,8 @@ public abstract class Stack<T> { * @param cons * The action to execute. */ - public void multiapply(int n, int m, Consumer<Stack<T>> cons) { - List<Consumer<Stack<T>>> conses = new ArrayList<>(m); + public void multiapply(final int n, final int m, final Consumer<Stack<T>> cons) { + final List<Consumer<Stack<T>>> conses = new ArrayList<>(m); for (int i = 0; i < m; i++) { conses.add(cons); @@ -438,7 +443,7 @@ public abstract class Stack<T> { * @param cons * The action to execute. */ - public void apply(int n, Consumer<Stack<T>> cons) { + public void apply(final int n, final Consumer<Stack<T>> cons) { multiapply(1, n, cons); } @@ -447,7 +452,7 @@ public abstract class Stack<T> { */ /** * Get an array representing this stack. - * + * * @return The stack as an array. */ public abstract T[] toArray(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java index f53f6f7..5f4c3a5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java @@ -9,7 +9,7 @@ package bjc.utils.esodata; * * @param <T> * The element type of the tape. - * + * * @author bjculkin */ public interface Tape<T> { @@ -45,8 +45,9 @@ public interface Tape<T> { /** * Insert an element after the current item. - * - * @param itm The item to insert. + * + * @param itm + * The item to insert. */ void insertAfter(T itm); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java index 10764fe..8b8613f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java @@ -32,12 +32,12 @@ public class TapeChanger<T> implements Tape<T> { * The tapes to put in this tape changer. */ @SafeVarargs - public TapeChanger(Tape<T> current, Tape<T>... others) { + public TapeChanger(final Tape<T> current, final Tape<T>... others) { this(); tapes.insertBefore(current); - for (Tape<T> tp : others) { + for (final Tape<T> tp : others) { tapes.insertAfter(tp); tapes.right(); } @@ -53,8 +53,7 @@ public class TapeChanger<T> implements Tape<T> { */ @Override public T item() { - if (currentTape == null) - return null; + if (currentTape == null) return null; return currentTape.item(); } @@ -66,9 +65,8 @@ public class TapeChanger<T> implements Tape<T> { * The new value for the tape item. */ @Override - public void item(T itm) { - if (currentTape == null) - return; + public void item(final T itm) { + if (currentTape == null) return; currentTape.item(itm); } @@ -80,8 +78,7 @@ public class TapeChanger<T> implements Tape<T> { */ @Override public int size() { - if (currentTape == null) - return 0; + if (currentTape == null) return 0; return currentTape.size(); } @@ -93,9 +90,8 @@ public class TapeChanger<T> implements Tape<T> { * The item to add. */ @Override - public void insertBefore(T itm) { - if (currentTape == null) - return; + public void insertBefore(final T itm) { + if (currentTape == null) return; currentTape.insertBefore(itm); } @@ -104,9 +100,8 @@ public class TapeChanger<T> implements Tape<T> { * Insert an element after the current item. */ @Override - public void insertAfter(T itm) { - if (currentTape == null) - return; + public void insertAfter(final T itm) { + if (currentTape == null) return; currentTape.insertAfter(itm); } @@ -121,8 +116,7 @@ public class TapeChanger<T> implements Tape<T> { */ @Override public T remove() { - if (currentTape == null) - return null; + if (currentTape == null) return null; return currentTape.remove(); } @@ -132,8 +126,7 @@ public class TapeChanger<T> implements Tape<T> { */ @Override public void first() { - if (currentTape == null) - return; + if (currentTape == null) return; currentTape.first(); } @@ -143,8 +136,7 @@ public class TapeChanger<T> implements Tape<T> { */ @Override public void last() { - if (currentTape == null) - return; + if (currentTape == null) return; currentTape.last(); } @@ -173,9 +165,8 @@ public class TapeChanger<T> implements Tape<T> { * @return True if the cursor was moved left. */ @Override - public boolean left(int amt) { - if (currentTape == null) - return false; + public boolean left(final int amt) { + if (currentTape == null) return false; return currentTape.left(amt); } @@ -203,9 +194,8 @@ public class TapeChanger<T> implements Tape<T> { * @return Whether the cursor was moved right. */ @Override - public boolean right(int amt) { - if (currentTape == null) - return false; + public boolean right(final int amt) { + if (currentTape == null) return false; return currentTape.right(amt); } @@ -219,8 +209,7 @@ public class TapeChanger<T> implements Tape<T> { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) - return; + if (currentTape == null) return; if (currentTape.isDoubleSided()) { ((DoubleTape<T>) currentTape).flip(); @@ -229,8 +218,7 @@ public class TapeChanger<T> implements Tape<T> { @Override public boolean isDoubleSided() { - if (currentTape == null) - return false; + if (currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -253,7 +241,7 @@ public class TapeChanger<T> implements Tape<T> { * @return Whether or not the next tape was loaded. */ public boolean nextTape() { - boolean succ = tapes.right(); + final boolean succ = tapes.right(); if (succ) { currentTape = tapes.item(); @@ -271,7 +259,7 @@ public class TapeChanger<T> implements Tape<T> { * @return Whether or not the previous tape was loaded. */ public boolean prevTape() { - boolean succ = tapes.left(); + final boolean succ = tapes.left(); if (succ) { currentTape = tapes.item(); @@ -290,7 +278,7 @@ public class TapeChanger<T> implements Tape<T> { * @param tp * The tape to insert and load. */ - public void insertTape(Tape<T> tp) { + public void insertTape(final Tape<T> tp) { tapes.insertAfter(tp); tapes.right(); @@ -307,10 +295,9 @@ public class TapeChanger<T> implements Tape<T> { * @return The removed tape. */ public Tape<T> removeTape() { - if (currentTape == null) - return null; + if (currentTape == null) return null; - Tape<T> tp = tapes.remove(); + final Tape<T> tp = tapes.remove(); currentTape = tapes.item(); return tp; @@ -338,33 +325,26 @@ public class TapeChanger<T> implements Tape<T> { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((currentTape == null) ? 0 : currentTape.hashCode()); - result = prime * result + ((tapes == null) ? 0 : tapes.hashCode()); + result = prime * result + (currentTape == null ? 0 : currentTape.hashCode()); + result = prime * result + (tapes == null ? 0 : tapes.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof TapeChanger<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof TapeChanger<?>)) return false; - TapeChanger<?> other = (TapeChanger<?>) obj; + final TapeChanger<?> other = (TapeChanger<?>) obj; if (currentTape == null) { - if (other.currentTape != null) - return false; - } else if (!currentTape.equals(other.currentTape)) - return false; + if (other.currentTape != null) return false; + } else if (!currentTape.equals(other.currentTape)) return false; if (tapes == null) { - if (other.tapes != null) - return false; - } else if (!tapes.equals(other.tapes)) - return false; + if (other.tapes != null) return false; + } else if (!tapes.equals(other.tapes)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java index 85bea49..4a5add6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java @@ -16,8 +16,8 @@ import java.util.Map; * The element type of the tapes. */ public class TapeLibrary<T> implements Tape<T> { - private Map<String, Tape<T>> tapes; - private Tape<T> currentTape; + private final Map<String, Tape<T>> tapes; + private Tape<T> currentTape; /** * Create a new empty tape library. @@ -33,8 +33,7 @@ public class TapeLibrary<T> implements Tape<T> { */ @Override public T item() { - if (currentTape == null) - return null; + if (currentTape == null) return null; return currentTape.item(); } @@ -46,9 +45,8 @@ public class TapeLibrary<T> implements Tape<T> { * The new value for the tape item. */ @Override - public void item(T itm) { - if (currentTape == null) - return; + public void item(final T itm) { + if (currentTape == null) return; currentTape.item(itm); } @@ -60,8 +58,7 @@ public class TapeLibrary<T> implements Tape<T> { */ @Override public int size() { - if (currentTape == null) - return 0; + if (currentTape == null) return 0; return currentTape.size(); } @@ -73,9 +70,8 @@ public class TapeLibrary<T> implements Tape<T> { * The item to add. */ @Override - public void insertBefore(T itm) { - if (currentTape == null) - return; + public void insertBefore(final T itm) { + if (currentTape == null) return; currentTape.insertBefore(itm); } @@ -84,9 +80,8 @@ public class TapeLibrary<T> implements Tape<T> { * Insert an element after the current item. */ @Override - public void insertAfter(T itm) { - if (currentTape == null) - return; + public void insertAfter(final T itm) { + if (currentTape == null) return; currentTape.insertAfter(itm); } @@ -101,8 +96,7 @@ public class TapeLibrary<T> implements Tape<T> { */ @Override public T remove() { - if (currentTape == null) - return null; + if (currentTape == null) return null; return currentTape.remove(); } @@ -112,8 +106,7 @@ public class TapeLibrary<T> implements Tape<T> { */ @Override public void first() { - if (currentTape == null) - return; + if (currentTape == null) return; currentTape.first(); } @@ -123,8 +116,7 @@ public class TapeLibrary<T> implements Tape<T> { */ @Override public void last() { - if (currentTape == null) - return; + if (currentTape == null) return; currentTape.last(); } @@ -153,9 +145,8 @@ public class TapeLibrary<T> implements Tape<T> { * @return True if the cursor was moved left. */ @Override - public boolean left(int amt) { - if (currentTape == null) - return false; + public boolean left(final int amt) { + if (currentTape == null) return false; return currentTape.left(amt); } @@ -183,9 +174,8 @@ public class TapeLibrary<T> implements Tape<T> { * @return Whether the cursor was moved right. */ @Override - public boolean right(int amt) { - if (currentTape == null) - return false; + public boolean right(final int amt) { + if (currentTape == null) return false; return currentTape.right(amt); } @@ -199,8 +189,7 @@ public class TapeLibrary<T> implements Tape<T> { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) - return; + if (currentTape == null) return; if (currentTape.isDoubleSided()) { ((DoubleTape<T>) currentTape).flip(); @@ -209,8 +198,7 @@ public class TapeLibrary<T> implements Tape<T> { @Override public boolean isDoubleSided() { - if (currentTape == null) - return false; + if (currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -235,7 +223,7 @@ public class TapeLibrary<T> implements Tape<T> { * * @return Whether or not the next tape was loaded. */ - public boolean switchTape(String label) { + public boolean switchTape(final String label) { if (tapes.containsKey(label)) { currentTape = tapes.get(label); return true; @@ -252,14 +240,14 @@ public class TapeLibrary<T> implements Tape<T> { * The specified tape is loaded. * * Adding a duplicate tape will overwrite any existing types. - * + * * @param label * The label of the tape to add. * * @param tp * The tape to insert and load. */ - public void insertTape(String label, Tape<T> tp) { + public void insertTape(final String label, final Tape<T> tp) { tapes.put(label, tp); currentTape = tp; @@ -275,7 +263,7 @@ public class TapeLibrary<T> implements Tape<T> { * * @return The removed tape. */ - public Tape<T> removeTape(String label) { + public Tape<T> removeTape(final String label) { return tapes.remove(label); } @@ -305,7 +293,7 @@ public class TapeLibrary<T> implements Tape<T> { * * @return Whether or not a tape of that name exists */ - public boolean hasTape(String label) { + public boolean hasTape(final String label) { return tapes.containsKey(label); } @@ -314,34 +302,27 @@ public class TapeLibrary<T> implements Tape<T> { final int prime = 31; int result = 1; - result = prime * result + ((currentTape == null) ? 0 : currentTape.hashCode()); - result = prime * result + ((tapes == null) ? 0 : tapes.hashCode()); + result = prime * result + (currentTape == null ? 0 : currentTape.hashCode()); + result = prime * result + (tapes == null ? 0 : tapes.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof TapeLibrary<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof TapeLibrary<?>)) return false; - TapeLibrary<?> other = (TapeLibrary<?>) obj; + final TapeLibrary<?> other = (TapeLibrary<?>) obj; if (currentTape == null) { - if (other.currentTape != null) - return false; - } else if (!currentTape.equals(other.currentTape)) - return false; + if (other.currentTape != null) return false; + } else if (!currentTape.equals(other.currentTape)) return false; if (tapes == null) { - if (other.tapes != null) - return false; - } else if (!tapes.equals(other.tapes)) - return false; + if (other.tapes != null) return false; + } else if (!tapes.equals(other.tapes)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java index a0d9096..ffb639f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java @@ -16,9 +16,9 @@ import bjc.utils.funcdata.IMap; * The value type of the directory. */ public class UnifiedDirectory<K, V> implements Directory<K, V> { - private IMap<K, Directory<K, V>> children; + private final IMap<K, Directory<K, V>> children; - private IMap<K, V> data; + private final IMap<K, V> data; /** * Create a new directory. @@ -29,19 +29,19 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { } @Override - public Directory<K, V> getSubdirectory(K key) { + public Directory<K, V> getSubdirectory(final K key) { return children.get(key); } @Override - public boolean hasSubdirectory(K key) { + public boolean hasSubdirectory(final K key) { return children.containsKey(key); } @Override - public Directory<K, V> putSubdirectory(K key, Directory<K, V> val) { + public Directory<K, V> putSubdirectory(final K key, final Directory<K, V> val) { if (data.containsKey(key)) { - String msg = String.format("Key %s is already used for data", key); + final String msg = String.format("Key %s is already used for data", key); throw new IllegalArgumentException(msg); } @@ -50,19 +50,19 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { } @Override - public boolean containsKey(K key) { + public boolean containsKey(final K key) { return data.containsKey(key); } @Override - public V getKey(K key) { + public V getKey(final K key) { return data.get(key); } @Override - public V putKey(K key, V val) { + public V putKey(final K key, final V val) { if (children.containsKey(key)) { - String msg = String.format("Key %s is already used for sub-directories.", key); + final String msg = String.format("Key %s is already used for sub-directories.", key); throw new IllegalArgumentException(msg); } @@ -74,33 +74,26 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((children == null) ? 0 : children.hashCode()); - result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + (children == null ? 0 : children.hashCode()); + result = prime * result + (data == null ? 0 : data.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof UnifiedDirectory<?, ?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof UnifiedDirectory<?, ?>)) return false; - UnifiedDirectory<?, ?> other = (UnifiedDirectory<?, ?>) obj; + final UnifiedDirectory<?, ?> other = (UnifiedDirectory<?, ?>) obj; if (children == null) { - if (other.children != null) - return false; - } else if (!children.equals(other.children)) - return false; + if (other.children != null) return false; + } else if (!children.equals(other.children)) return false; if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; + if (other.data != null) return false; + } else if (!data.equals(other.data)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java index c60d95c..6f5a68a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java @@ -25,7 +25,7 @@ public class FileNotChosenException extends IOException { * @param cause * The cause of why the exception was thrown */ - public FileNotChosenException(String cause) { + public FileNotChosenException(final String cause) { super(cause); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java index 088b7eb..1ad339d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java @@ -25,7 +25,7 @@ public class PragmaFormatException extends InputMismatchException { * @param message * The message to explain why the exception was thrown */ - public PragmaFormatException(String message) { + public PragmaFormatException(final String message) { super(message); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java index ad399cb..6fc9113 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java @@ -18,7 +18,7 @@ public class UnknownPragmaException extends InputMismatchException { * @param cause * The cause for throwing this exception */ - public UnknownPragmaException(String cause) { + public UnknownPragmaException(final String cause) { super(cause); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java index caa487c..909c5e9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java @@ -1,17 +1,17 @@ package bjc.utils.funcdata; -import bjc.utils.funcutils.ListUtils; - import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; +import bjc.utils.funcutils.ListUtils; + class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { - private IMap<KeyType, ValueType> delegate; + private final IMap<KeyType, ValueType> delegate; - private IMap<KeyType, ValueType> store; + private final IMap<KeyType, ValueType> store; - public ExtendedMap(IMap<KeyType, ValueType> delegate, IMap<KeyType, ValueType> store) { + public ExtendedMap(final IMap<KeyType, ValueType> delegate, final IMap<KeyType, ValueType> store) { this.delegate = delegate; this.store = store; } @@ -22,9 +22,8 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { } @Override - public boolean containsKey(KeyType key) { - if (store.containsKey(key)) - return true; + public boolean containsKey(final KeyType key) { + if (store.containsKey(key)) return true; return delegate.containsKey(key); } @@ -35,30 +34,29 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { } @Override - public void forEach(BiConsumer<KeyType, ValueType> action) { + public void forEach(final BiConsumer<KeyType, ValueType> action) { store.forEach(action); delegate.forEach(action); } @Override - public void forEachKey(Consumer<KeyType> action) { + public void forEachKey(final Consumer<KeyType> action) { store.forEachKey(action); delegate.forEachKey(action); } @Override - public void forEachValue(Consumer<ValueType> action) { + public void forEachValue(final Consumer<ValueType> action) { store.forEachValue(action); delegate.forEachValue(action); } @Override - public ValueType get(KeyType key) { - if (store.containsKey(key)) - return store.get(key); + public ValueType get(final KeyType key) { + if (store.containsKey(key)) return store.get(key); return delegate.get(key); } @@ -74,19 +72,18 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { } @Override - public <MappedValue> IMap<KeyType, MappedValue> transform(Function<ValueType, MappedValue> transformer) { + public <MappedValue> IMap<KeyType, MappedValue> transform(final Function<ValueType, MappedValue> transformer) { return new TransformedValueMap<>(this, transformer); } @Override - public ValueType put(KeyType key, ValueType val) { + public ValueType put(final KeyType key, final ValueType val) { return store.put(key, val); } @Override - public ValueType remove(KeyType key) { - if (!store.containsKey(key)) - return delegate.remove(key); + public ValueType remove(final KeyType key) { + if (!store.containsKey(key)) return delegate.remove(key); return store.remove(key); } @@ -100,32 +97,25 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((delegate == null) ? 0 : delegate.hashCode()); - result = prime * result + ((store == null) ? 0 : store.hashCode()); + result = prime * result + (delegate == null ? 0 : delegate.hashCode()); + result = prime * result + (store == null ? 0 : store.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof ExtendedMap)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof ExtendedMap)) return false; - ExtendedMap<?, ?> other = (ExtendedMap<?, ?>) obj; + final ExtendedMap<?, ?> other = (ExtendedMap<?, ?>) obj; if (delegate == null) { - if (other.delegate != null) - return false; - } else if (!delegate.equals(other.delegate)) - return false; + if (other.delegate != null) return false; + } else if (!delegate.equals(other.delegate)) return false; if (store == null) { - if (other.store != null) - return false; - } else if (!store.equals(other.store)) - return false; + if (other.store != null) return false; + } else if (!store.equals(other.store)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java index 7627bdf..55ea7ff 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -1,10 +1,5 @@ package bjc.utils.funcdata; -import bjc.utils.data.IHolder; -import bjc.utils.data.IPair; -import bjc.utils.data.Identity; -import bjc.utils.data.Pair; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -17,6 +12,11 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import bjc.utils.data.IHolder; +import bjc.utils.data.IPair; +import bjc.utils.data.Identity; +import bjc.utils.data.Pair; + /** * A wrapper over another list that provides eager functional operations over * it. @@ -33,7 +33,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* * The list used as a backing store */ - private List<E> wrapped; + private final List<E> wrapped; /** * Create a new empty functional list. @@ -51,10 +51,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * The items to put into this functional list. */ @SafeVarargs - public FunctionalList(E... items) { + public FunctionalList(final E... items) { wrapped = new ArrayList<>(items.length); - for (E item : items) { + for (final E item : items) { wrapped.add(item); } } @@ -65,7 +65,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * @param size * The size of the backing list . */ - private FunctionalList(int size) { + private FunctionalList(final int size) { wrapped = new ArrayList<>(size); } @@ -77,24 +77,22 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * @param backing * The list to use as a backing list. */ - public FunctionalList(List<E> backing) { - if (backing == null) - throw new NullPointerException("Backing list must be non-null"); + public FunctionalList(final List<E> backing) { + if (backing == null) throw new NullPointerException("Backing list must be non-null"); wrapped = backing; } @Override - public boolean add(E item) { + public boolean add(final E item) { return wrapped.add(item); } @Override - public boolean allMatch(Predicate<E> predicate) { - if (predicate == null) - throw new NullPointerException("Predicate must be non-null"); + public boolean allMatch(final Predicate<E> predicate) { + if (predicate == null) throw new NullPointerException("Predicate must be non-null"); - for (E item : wrapped) { + for (final E item : wrapped) { if (!predicate.test(item)) // We've found a non-matching item return false; @@ -105,11 +103,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public boolean anyMatch(Predicate<E> predicate) { - if (predicate == null) - throw new NullPointerException("Predicate must be not null"); + public boolean anyMatch(final Predicate<E> predicate) { + if (predicate == null) throw new NullPointerException("Predicate must be not null"); - for (E item : wrapped) { + for (final E item : wrapped) { if (predicate.test(item)) // We've found a matching item return true; @@ -128,9 +125,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { */ @Override public IList<E> clone() { - IList<E> cloned = new FunctionalList<>(); + final IList<E> cloned = new FunctionalList<>(); - for (E element : wrapped) { + for (final E element : wrapped) { cloned.add(element); } @@ -138,22 +135,21 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T, F> IList<F> combineWith(IList<T> rightList, BiFunction<E, T, F> itemCombiner) { + public <T, F> IList<F> combineWith(final IList<T> rightList, final BiFunction<E, T, F> itemCombiner) { if (rightList == null) throw new NullPointerException("Target combine list must not be null"); - else if (itemCombiner == null) - throw new NullPointerException("Combiner must not be null"); + else if (itemCombiner == null) throw new NullPointerException("Combiner must not be null"); - IList<F> returned = new FunctionalList<>(); + final IList<F> returned = new FunctionalList<>(); // Get the iterator for the other list - Iterator<T> rightIterator = rightList.toIterable().iterator(); + final Iterator<T> rightIterator = rightList.toIterable().iterator(); - for (Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() + for (final Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() && rightIterator.hasNext();) { // Add the transformed items to the result list - E leftVal = leftIterator.next(); - T rightVal = rightIterator.next(); + final E leftVal = leftIterator.next(); + final T rightVal = rightIterator.next(); returned.add(itemCombiner.apply(leftVal, rightVal)); } @@ -162,7 +158,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public boolean contains(E item) { + public boolean contains(final E item) { // Check if any items in the list match the provided item return this.anyMatch(item::equals); } @@ -176,17 +172,15 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T> IList<T> flatMap(Function<E, IList<T>> expander) { - if (expander == null) - throw new NullPointerException("Expander must not be null"); + public <T> IList<T> flatMap(final Function<E, IList<T>> expander) { + if (expander == null) throw new NullPointerException("Expander must not be null"); - IList<T> returned = new FunctionalList<>(this.wrapped.size()); + final IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { - IList<T> expandedElement = expander.apply(element); + final IList<T> expandedElement = expander.apply(element); - if (expandedElement == null) - throw new NullPointerException("Expander returned null list"); + if (expandedElement == null) throw new NullPointerException("Expander returned null list"); // Add each element to the returned list expandedElement.forEach(returned::add); @@ -196,21 +190,19 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public void forEach(Consumer<? super E> action) { - if (action == null) - throw new NullPointerException("Action is null"); + public void forEach(final Consumer<? super E> action) { + if (action == null) throw new NullPointerException("Action is null"); wrapped.forEach(action); } @Override - public void forEachIndexed(BiConsumer<Integer, E> indexedAction) { - if (indexedAction == null) - throw new NullPointerException("Action must not be null"); + public void forEachIndexed(final BiConsumer<Integer, E> indexedAction) { + if (indexedAction == null) throw new NullPointerException("Action must not be null"); // This is held b/c ref'd variables must be final/effectively // final - IHolder<Integer> currentIndex = new Identity<>(0); + final IHolder<Integer> currentIndex = new Identity<>(0); wrapped.forEach((element) -> { // Call the action with the index and the value @@ -222,7 +214,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public E getByIndex(int index) { + public E getByIndex(final int index) { return wrapped.get(index); } @@ -236,11 +228,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public IList<E> getMatching(Predicate<E> predicate) { - if (predicate == null) - throw new NullPointerException("Predicate must not be null"); + public IList<E> getMatching(final Predicate<E> predicate) { + if (predicate == null) throw new NullPointerException("Predicate must not be null"); - IList<E> returned = new FunctionalList<>(); + final IList<E> returned = new FunctionalList<>(); wrapped.forEach((element) -> { if (predicate.test(element)) { @@ -266,16 +257,15 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* * Check if a partition has room for another item */ - private Boolean isPartitionFull(int numberPerPartition, IHolder<IList<E>> currentPartition) { + private Boolean isPartitionFull(final int numberPerPartition, final IHolder<IList<E>> currentPartition) { return currentPartition.unwrap((partition) -> partition.getSize() >= numberPerPartition); } @Override - public <T> IList<T> map(Function<E, T> elementTransformer) { - if (elementTransformer == null) - throw new NullPointerException("Transformer must be not null"); + public <T> IList<T> map(final Function<E, T> elementTransformer) { + if (elementTransformer == null) throw new NullPointerException("Transformer must be not null"); - IList<T> returned = new FunctionalList<>(this.wrapped.size()); + final IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { // Add the transformed item to the result @@ -286,23 +276,23 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T> IList<IPair<E, T>> pairWith(IList<T> rightList) { + public <T> IList<IPair<E, T>> pairWith(final IList<T> rightList) { return combineWith(rightList, Pair<E, T>::new); } @Override - public IList<IList<E>> partition(int numberPerPartition) { + public IList<IList<E>> partition(final int numberPerPartition) { if (numberPerPartition < 1 || numberPerPartition > wrapped.size()) { - String fmt = "%s is an invalid partition size. Must be between 1 and %d"; - String msg = String.format(fmt, numberPerPartition, wrapped.size()); + final String fmt = "%s is an invalid partition size. Must be between 1 and %d"; + final String msg = String.format(fmt, numberPerPartition, wrapped.size()); throw new IllegalArgumentException(msg); } - IList<IList<E>> returned = new FunctionalList<>(); + final IList<IList<E>> returned = new FunctionalList<>(); // The current partition being filled - IHolder<IList<E>> currentPartition = new Identity<>(new FunctionalList<>()); + final IHolder<IList<E>> currentPartition = new Identity<>(new FunctionalList<>()); this.forEach(element -> { if (isPartitionFull(numberPerPartition, currentPartition)) { @@ -321,30 +311,28 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public void prepend(E item) { + public void prepend(final E item) { wrapped.add(0, item); } @Override - public E randItem(Function<Integer, Integer> rnd) { - if (rnd == null) - throw new NullPointerException("Random source must not be null"); + public E randItem(final Function<Integer, Integer> rnd) { + if (rnd == null) throw new NullPointerException("Random source must not be null"); - int randomIndex = rnd.apply(wrapped.size()); + final int randomIndex = rnd.apply(wrapped.size()); return wrapped.get(randomIndex); } @Override - public <T, F> F reduceAux(T initialValue, BiFunction<E, T, T> stateAccumulator, - Function<T, F> resultTransformer) { + public <T, F> F reduceAux(final T initialValue, final BiFunction<E, T, T> stateAccumulator, + final Function<T, F> resultTransformer) { if (stateAccumulator == null) throw new NullPointerException("Accumulator must not be null"); - else if (resultTransformer == null) - throw new NullPointerException("Transformer must not be null"); + else if (resultTransformer == null) throw new NullPointerException("Transformer must not be null"); // The current collapsed list - IHolder<T> currentState = new Identity<>(initialValue); + final IHolder<T> currentState = new Identity<>(initialValue); wrapped.forEach(element -> { // Accumulate a new value into the state @@ -356,15 +344,14 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public boolean removeIf(Predicate<E> removePredicate) { - if (removePredicate == null) - throw new NullPointerException("Predicate must be non-null"); + public boolean removeIf(final Predicate<E> removePredicate) { + if (removePredicate == null) throw new NullPointerException("Predicate must be non-null"); return wrapped.removeIf(removePredicate); } @Override - public void removeMatching(E desiredElement) { + public void removeMatching(final E desiredElement) { removeIf(element -> element.equals(desiredElement)); } @@ -374,9 +361,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public E search(E searchKey, Comparator<E> comparator) { + public E search(final E searchKey, final Comparator<E> comparator) { // Search our internal list - int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); + final int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); if (foundIndex >= 0) // We found a matching element return wrapped.get(foundIndex); @@ -386,7 +373,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public void sort(Comparator<E> comparator) { + public void sort(final Comparator<E> comparator) { // sb.deleteCharAt(sb.length() - 2); Collections.sort(wrapped, comparator); } @@ -397,7 +384,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public E[] toArray(E[] arrType) { + public E[] toArray(final E[] arrType) { return wrapped.toArray(arrType); } @@ -408,20 +395,18 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public String toString() { - int lSize = getSize(); + final int lSize = getSize(); - if (lSize == 0) - return "()"; + if (lSize == 0) return "()"; - StringBuilder sb = new StringBuilder("("); - Iterator<E> itr = toIterable().iterator(); - E itm = itr.next(); + final StringBuilder sb = new StringBuilder("("); + final Iterator<E> itr = toIterable().iterator(); + final E itm = itr.next(); int i = 0; - if (lSize == 1) - return "(" + itm + ")"; + if (lSize == 1) return "(" + itm + ")"; - for (E item : toIterable()) { + for (final E item : toIterable()) { sb.append(item.toString()); if (i < lSize - 1) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java index 62c39af..c4f0ff1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java @@ -1,13 +1,13 @@ package bjc.utils.funcdata; -import bjc.utils.data.IPair; - import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; +import bjc.utils.data.IPair; + /** * Basic implementation of {@link IMap} * @@ -35,10 +35,10 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * The entries to put into the map */ @SafeVarargs - public FunctionalMap(IPair<KeyType, ValueType>... entries) { + public FunctionalMap(final IPair<KeyType, ValueType>... entries) { this(); - for (IPair<KeyType, ValueType> entry : entries) { + for (final IPair<KeyType, ValueType> entry : entries) { entry.doWith((key, val) -> { wrappedMap.put(key, val); }); @@ -51,9 +51,8 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * @param wrap * The map to wrap */ - public FunctionalMap(Map<KeyType, ValueType> wrap) { - if (wrap == null) - throw new NullPointerException("Map to wrap must not be null"); + public FunctionalMap(final Map<KeyType, ValueType> wrap) { + if (wrap == null) throw new NullPointerException("Map to wrap must not be null"); wrappedMap = wrap; } @@ -64,7 +63,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp } @Override - public boolean containsKey(KeyType key) { + public boolean containsKey(final KeyType key) { return wrappedMap.containsKey(key); } @@ -74,27 +73,26 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp } @Override - public void forEach(BiConsumer<KeyType, ValueType> action) { + public void forEach(final BiConsumer<KeyType, ValueType> action) { wrappedMap.forEach(action); } @Override - public void forEachKey(Consumer<KeyType> action) { + public void forEachKey(final Consumer<KeyType> action) { wrappedMap.keySet().forEach(action); } @Override - public void forEachValue(Consumer<ValueType> action) { + public void forEachValue(final Consumer<ValueType> action) { wrappedMap.values().forEach(action); } @Override - public ValueType get(KeyType key) { - if (key == null) - throw new NullPointerException("Key must not be null"); + public ValueType get(final KeyType key) { + if (key == null) throw new NullPointerException("Key must not be null"); if (!wrappedMap.containsKey(key)) { - String msg = String.format("Key %s is not present in the map", key); + final String msg = String.format("Key %s is not present in the map", key); throw new IllegalArgumentException(msg); } @@ -109,7 +107,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public IList<KeyType> keyList() { - FunctionalList<KeyType> keys = new FunctionalList<>(); + final FunctionalList<KeyType> keys = new FunctionalList<>(); wrappedMap.keySet().forEach(key -> { keys.add(key); @@ -119,23 +117,21 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp } @Override - public <MappedValue> IMap<KeyType, MappedValue> transform(Function<ValueType, MappedValue> transformer) { - if (transformer == null) - throw new NullPointerException("Transformer must not be null"); + public <MappedValue> IMap<KeyType, MappedValue> transform(final Function<ValueType, MappedValue> transformer) { + if (transformer == null) throw new NullPointerException("Transformer must not be null"); return new TransformedValueMap<>(this, transformer); } @Override - public ValueType put(KeyType key, ValueType val) { - if (key == null) - throw new NullPointerException("Key must not be null"); + public ValueType put(final KeyType key, final ValueType val) { + if (key == null) throw new NullPointerException("Key must not be null"); return wrappedMap.put(key, val); } @Override - public ValueType remove(KeyType key) { + public ValueType remove(final KeyType key) { return wrappedMap.remove(key); } @@ -146,7 +142,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public IList<ValueType> valueList() { - FunctionalList<ValueType> values = new FunctionalList<>(); + final FunctionalList<ValueType> values = new FunctionalList<>(); wrappedMap.values().forEach(value -> { values.add(value); @@ -159,26 +155,21 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((wrappedMap == null) ? 0 : wrappedMap.hashCode()); + result = prime * result + (wrappedMap == null ? 0 : wrappedMap.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof FunctionalMap)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof FunctionalMap)) return false; - FunctionalMap<?, ?> other = (FunctionalMap<?, ?>) obj; + final FunctionalMap<?, ?> other = (FunctionalMap<?, ?>) obj; if (wrappedMap == null) { - if (other.wrappedMap != null) - return false; - } else if (!wrappedMap.equals(other.wrappedMap)) - return false; + if (other.wrappedMap != null) return false; + } else if (!wrappedMap.equals(other.wrappedMap)) return false; return true; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java index 4723bcd..e068b46 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -18,9 +18,8 @@ public class FunctionalStringTokenizer { * The string to create a tokenizer from. * @return A new tokenizer that splits the provided string on spaces. */ - public static FunctionalStringTokenizer fromString(String strang) { - if (strang == null) - throw new NullPointerException("String to tokenize must be non-null"); + public static FunctionalStringTokenizer fromString(final String strang) { + if (strang == null) throw new NullPointerException("String to tokenize must be non-null"); return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); } @@ -28,7 +27,7 @@ public class FunctionalStringTokenizer { /* * The string tokenizer being driven */ - private StringTokenizer input; + private final StringTokenizer input; /** * Create a functional string tokenizer from a given string @@ -36,9 +35,8 @@ public class FunctionalStringTokenizer { * @param inp * The string to tokenize */ - public FunctionalStringTokenizer(String inp) { - if (inp == null) - throw new NullPointerException("String to tokenize must be non-null"); + public FunctionalStringTokenizer(final String inp) { + if (inp == null) throw new NullPointerException("String to tokenize must be non-null"); this.input = new StringTokenizer(inp); } @@ -52,11 +50,10 @@ public class FunctionalStringTokenizer { * @param seperators * The set of separating tokens to use for splitting */ - public FunctionalStringTokenizer(String input, String seperators) { + public FunctionalStringTokenizer(final String input, final String seperators) { if (input == null) throw new NullPointerException("String to tokenize must not be null"); - else if (seperators == null) - throw new NullPointerException("Tokens to split on must not be null"); + else if (seperators == null) throw new NullPointerException("Tokens to split on must not be null"); this.input = new StringTokenizer(input, seperators); } @@ -67,9 +64,8 @@ public class FunctionalStringTokenizer { * @param toWrap * The non-functional string tokenizer to wrap */ - public FunctionalStringTokenizer(StringTokenizer toWrap) { - if (toWrap == null) - throw new NullPointerException("Wrapped tokenizer must not be null"); + public FunctionalStringTokenizer(final StringTokenizer toWrap) { + if (toWrap == null) throw new NullPointerException("Wrapped tokenizer must not be null"); this.input = toWrap; } @@ -80,9 +76,8 @@ public class FunctionalStringTokenizer { * @param action * The action to execute for each token */ - public void forEachToken(Consumer<String> action) { - if (action == null) - throw new NullPointerException("Action must not be null"); + public void forEachToken(final Consumer<String> action) { + if (action == null) throw new NullPointerException("Action must not be null"); while (input.hasMoreTokens()) { action.accept(input.nextToken()); @@ -128,7 +123,7 @@ public class FunctionalStringTokenizer { * @return This tokenizer, converted into a list of strings */ public IList<String> toList() { - return toList((String element) -> element); + return toList((final String element) -> element); } /** @@ -142,15 +137,14 @@ public class FunctionalStringTokenizer { * The function to use to convert tokens. * @return A list containing all of the converted tokens. */ - public <E> IList<E> toList(Function<String, E> transformer) { - if (transformer == null) - throw new NullPointerException("Transformer must not be null"); + public <E> IList<E> toList(final Function<String, E> transformer) { + if (transformer == null) throw new NullPointerException("Transformer must not be null"); - IList<E> returned = new FunctionalList<>(); + final IList<E> returned = new FunctionalList<>(); // Add each token to the list after transforming it forEachToken(token -> { - E transformedToken = transformer.apply(token); + final E transformedToken = transformer.apply(token); returned.add(transformedToken); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java index d92d564..de48d6f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java @@ -1,7 +1,5 @@ package bjc.utils.funcdata; -import bjc.utils.data.IPair; - import java.util.Comparator; import java.util.Iterator; import java.util.function.BiConsumer; @@ -11,6 +9,8 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; +import bjc.utils.data.IPair; + /** * A wrapper over another list that provides functional operations over it. * @@ -37,7 +37,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * @return True if every item was successfully added to the list, false * otherwise */ - default boolean addAll(IList<ContainedType> items) { + default boolean addAll(final IList<ContainedType> items) { return items.map(this::add).anyMatch(bl -> bl == false); } @@ -46,16 +46,16 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * * @param items * The array of items to add. - * + * * @return True if every item was successfully added to the list, false * otherwise. */ @SuppressWarnings("unchecked") - default boolean addAll(ContainedType... items) { + default boolean addAll(final ContainedType... items) { boolean succ = true; - for(ContainedType item : items) { - boolean addSucc = add(item); + for (final ContainedType item : items) { + final boolean addSucc = add(item); succ = succ ? addSucc : false; } @@ -96,10 +96,10 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * @return The reduced list */ default <StateType, ReducedType> ReducedType collect( - Collector<ContainedType, StateType, ReducedType> collector) { - BiConsumer<StateType, ContainedType> accumulator = collector.accumulator(); + final Collector<ContainedType, StateType, ReducedType> collector) { + final BiConsumer<StateType, ContainedType> accumulator = collector.accumulator(); - StateType initial = collector.supplier().get(); + final StateType initial = collector.supplier().get(); return reduceAux(initial, (value, state) -> { accumulator.accept(state, value); @@ -266,8 +266,8 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * The items to prepend to the list. */ @SuppressWarnings("unchecked") - default void prependAll(ContainedType... items) { - for(ContainedType item : items) { + default void prependAll(final ContainedType... items) { + for (final ContainedType item : items) { prepend(item); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java index e58409e..0ee7375 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java @@ -11,7 +11,7 @@ import java.util.function.Function; * * @param <KeyType> * The type of this map's keys. - * + * * @param <ValueType> * The type of this map's values. */ @@ -30,7 +30,7 @@ public interface IMap<KeyType, ValueType> { * @param action * The action to perform on each key in the map. */ - default void forEachKey(Consumer<KeyType> action) { + default void forEachKey(final Consumer<KeyType> action) { forEach((key, val) -> action.accept(key)); } @@ -40,7 +40,7 @@ public interface IMap<KeyType, ValueType> { * @param action * The action to perform on each value in the map. */ - default void forEachValue(Consumer<ValueType> action) { + default void forEachValue(final Consumer<ValueType> action) { forEach((key, val) -> action.accept(val)); } @@ -49,7 +49,7 @@ public interface IMap<KeyType, ValueType> { * * @param key * The key to check. - * + * * @return Whether or not the map contains the key. */ boolean containsKey(KeyType key); @@ -59,7 +59,7 @@ public interface IMap<KeyType, ValueType> { * * @param key * The key to look for a value under. - * + * * @return The value of the key. */ ValueType get(KeyType key); @@ -70,17 +70,17 @@ public interface IMap<KeyType, ValueType> { * * @param key * The key to attempt to retrieve. - * + * * @param defaultValue * The value to return if the key doesn't exist. - * + * * @return The value associated with the key, or the default value if * the key doesn't exist. */ - default ValueType getOrDefault(KeyType key, ValueType defaultValue) { + default ValueType getOrDefault(final KeyType key, final ValueType defaultValue) { try { return get(key); - } catch (IllegalArgumentException iaex) { + } catch (final IllegalArgumentException iaex) { /* * We don't care about this, because it indicates a key * is missing. @@ -94,10 +94,10 @@ public interface IMap<KeyType, ValueType> { * * @param key * The key to put the value under. - * + * * @param val * The value to add. - * + * * @return The previous value of the key in the map, or null if the key * wasn't in the map. However, note that it may also return null * if the key was set to null. @@ -133,13 +133,13 @@ public interface IMap<KeyType, ValueType> { * * @param <V2> * The new type of returned values. - * + * * @param transformer * The function to use to transform values. - * + * * @return The map where each value will be transformed after lookup. */ - default <V2> IMap<KeyType, V2> transform(Function<ValueType, V2> transformer) { + default <V2> IMap<KeyType, V2> transform(final Function<ValueType, V2> transformer) { return new TransformedValueMap<>(this, transformer); } @@ -156,7 +156,7 @@ public interface IMap<KeyType, ValueType> { * * @param key * The key to remove from the map. - * + * * @return The previous value for the key in the map, or null if the key * wasn't in the class. NOTE: Just because you received null, * doesn't mean the map wasn't changed. It may mean that someone @@ -177,9 +177,9 @@ public interface IMap<KeyType, ValueType> { * @return A list of values in this map. */ default IList<ValueType> valueList() { - IList<ValueType> returns = new FunctionalList<>(); + final IList<ValueType> returns = new FunctionalList<>(); - for (KeyType key : keyList()) { + for (final KeyType key : keyList()) { returns.add(get(key)); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java index f52a286..c322743 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java @@ -4,10 +4,11 @@ import java.util.List; /** * A list that logs when items are inserted into it. - * + * * @author bjculkin * - * @param <T> The type of item in the list. + * @param <T> + * The type of item in the list. */ public class SentryList<T> extends FunctionalList<T> { /** @@ -19,19 +20,19 @@ public class SentryList<T> extends FunctionalList<T> { /** * Create a new sentry list backed by an existing list. - * + * * @param backing * The backing list. */ - public SentryList(List<T> backing) { + public SentryList(final List<T> backing) { super(backing); } @Override - public boolean add(T item) { - boolean val = super.add(item); + public boolean add(final T item) { + final boolean val = super.add(item); - if(val) { + if (val) { System.out.println("Added item (" + item + ") to list"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java index 43bd4d0..0ca1fdc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java @@ -17,10 +17,11 @@ import java.util.function.Function; * The type of the transformed values */ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldKey, NewValue> { - private IMap<OldKey, OldValue> backing; - private Function<OldValue, NewValue> transformer; + private final IMap<OldKey, OldValue> backing; + private final Function<OldValue, NewValue> transformer; - public TransformedValueMap(IMap<OldKey, OldValue> backingMap, Function<OldValue, NewValue> transform) { + public TransformedValueMap(final IMap<OldKey, OldValue> backingMap, + final Function<OldValue, NewValue> transform) { backing = backingMap; transformer = transform; } @@ -31,7 +32,7 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK } @Override - public boolean containsKey(OldKey key) { + public boolean containsKey(final OldKey key) { return backing.containsKey(key); } @@ -41,26 +42,26 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK } @Override - public void forEach(BiConsumer<OldKey, NewValue> action) { + public void forEach(final BiConsumer<OldKey, NewValue> action) { backing.forEach((key, value) -> { action.accept(key, transformer.apply(value)); }); } @Override - public void forEachKey(Consumer<OldKey> action) { + public void forEachKey(final Consumer<OldKey> action) { backing.forEachKey(action); } @Override - public void forEachValue(Consumer<NewValue> action) { + public void forEachValue(final Consumer<NewValue> action) { backing.forEachValue(value -> { action.accept(transformer.apply(value)); }); } @Override - public NewValue get(OldKey key) { + public NewValue get(final OldKey key) { return transformer.apply(backing.get(key)); } @@ -75,17 +76,17 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK } @Override - public <MappedValue> IMap<OldKey, MappedValue> transform(Function<NewValue, MappedValue> transform) { + public <MappedValue> IMap<OldKey, MappedValue> transform(final Function<NewValue, MappedValue> transform) { return new TransformedValueMap<>(this, transform); } @Override - public NewValue put(OldKey key, NewValue value) { + public NewValue put(final OldKey key, final NewValue value) { throw new UnsupportedOperationException("Can't add items to transformed map"); } @Override - public NewValue remove(OldKey key) { + public NewValue remove(final OldKey key) { return transformer.apply(backing.remove(key)); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java index e85ae34..8acd477 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java @@ -1,13 +1,13 @@ package bjc.utils.funcdata.bst; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * A binary search tree, with some mild support for functional traversal. * @@ -20,7 +20,7 @@ public class BinarySearchTree<T> { /* * The comparator for use in ordering items */ - private Comparator<T> comparator; + private final Comparator<T> comparator; /* * The current count of elements in the tree @@ -38,9 +38,8 @@ public class BinarySearchTree<T> { * @param cmp * The thing to use for comparing elements */ - public BinarySearchTree(Comparator<T> cmp) { - if (cmp == null) - throw new NullPointerException("Comparator must not be null"); + public BinarySearchTree(final Comparator<T> cmp) { + if (cmp == null) throw new NullPointerException("Comparator must not be null"); elementCount = 0; comparator = cmp; @@ -52,7 +51,7 @@ public class BinarySearchTree<T> { * @param element * The data to add to the binary search tree. */ - public void addNode(T element) { + public void addNode(final T element) { elementCount++; if (root == null) { @@ -73,7 +72,7 @@ public class BinarySearchTree<T> { * The distance from the pivot * @return Whether the adjusted pivot is with the list */ - private boolean adjustedPivotInBounds(IList<T> elements, int pivot, int pivotAdjustment) { + private boolean adjustedPivotInBounds(final IList<T> elements, final int pivot, final int pivotAdjustment) { return pivot - pivotAdjustment >= 0 && pivot + pivotAdjustment < elements.getSize(); } @@ -83,7 +82,7 @@ public class BinarySearchTree<T> { * Takes O(N) time, but also O(N) space. */ public void balance() { - IList<T> elements = new FunctionalList<>(); + final IList<T> elements = new FunctionalList<>(); // Add each element to the list in sorted order root.forEach(TreeLinearizationMethod.INORDER, element -> elements.add(element)); @@ -92,7 +91,7 @@ public class BinarySearchTree<T> { root = null; // Set up the pivot and adjustment for readding elements - int pivot = elements.getSize() / 2; + final int pivot = elements.getSize() / 2; int pivotAdjustment = 0; // Add elements until there aren't any left @@ -129,7 +128,7 @@ public class BinarySearchTree<T> { * @param element * The node to delete */ - public void deleteNode(T element) { + public void deleteNode(final T element) { elementCount--; root.delete(element, comparator); @@ -151,7 +150,7 @@ public class BinarySearchTree<T> { * The node to check the presence of for the tree. * @return Whether or not the node is in the tree. */ - public boolean isInTree(T element) { + public boolean isInTree(final T element) { return root.contains(element, comparator); } @@ -163,11 +162,10 @@ public class BinarySearchTree<T> { * @param traversalPredicate * The function to use until it fails */ - public void traverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + public void traverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { if (linearizationMethod == null) throw new NullPointerException("Linearization method must not be null"); - else if (traversalPredicate == null) - throw new NullPointerException("Predicate must not be nulls"); + else if (traversalPredicate == null) throw new NullPointerException("Predicate must not be nulls"); root.forEach(linearizationMethod, traversalPredicate); } @@ -176,7 +174,7 @@ public class BinarySearchTree<T> { * Remove all soft-deleted nodes from the tree. */ public void trim() { - List<T> nodes = new ArrayList<>(elementCount); + final List<T> nodes = new ArrayList<>(elementCount); // Add all non-soft deleted nodes to the tree in insertion order traverse(TreeLinearizationMethod.PREORDER, node -> { @@ -201,28 +199,22 @@ public class BinarySearchTree<T> { final int prime = 31; int result = 1; result = prime * result + elementCount; - result = prime * result + ((root == null) ? 0 : root.hashCode()); + result = prime * result + (root == null ? 0 : root.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof BinarySearchTree<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof BinarySearchTree<?>)) return false; - BinarySearchTree<?> other = (BinarySearchTree<?>) obj; + final BinarySearchTree<?> other = (BinarySearchTree<?>) obj; - if (elementCount != other.elementCount) - return false; + if (elementCount != other.elementCount) return false; if (root == null) { - if (other.root != null) - return false; - } else if (!root.equals(other.root)) - return false; + if (other.root != null) return false; + } else if (!root.equals(other.root)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java index fe30dad..8c4f3f0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java @@ -30,25 +30,24 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * @param element * The data for the leaf to hold. */ - public BinarySearchTreeLeaf(T element) { + public BinarySearchTreeLeaf(final T element) { data = element; } @Override - public void add(T element, Comparator<T> comparator) { + public void add(final T element, final Comparator<T> comparator) { throw new IllegalArgumentException("Can't add to a leaf."); } @Override - public <E> E collapse(Function<T, E> leafTransformer, BiFunction<E, E, E> branchCollapser) { - if (leafTransformer == null) - throw new NullPointerException("Transformer must not be null"); + public <E> E collapse(final Function<T, E> leafTransformer, final BiFunction<E, E, E> branchCollapser) { + if (leafTransformer == null) throw new NullPointerException("Transformer must not be null"); return leafTransformer.apply(data); } @Override - public boolean contains(T element, Comparator<T> comparator) { + public boolean contains(final T element, final Comparator<T> comparator) { return this.data.equals(element); } @@ -58,16 +57,15 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } @Override - public void delete(T element, Comparator<T> comparator) { + public void delete(final T element, final Comparator<T> comparator) { if (data.equals(element)) { isDeleted = true; } } @Override - public boolean directedWalk(DirectedWalkFunction<T> treeWalker) { - if (treeWalker == null) - throw new NullPointerException("Tree walker must not be null"); + public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { + if (treeWalker == null) throw new NullPointerException("Tree walker must not be null"); switch (treeWalker.walk(data)) { case SUCCESS: @@ -82,9 +80,9 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } @Override - public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { - if (traversalPredicate == null) - throw new NullPointerException("Predicate must not be null"); + public boolean forEach(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { + if (traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); return traversalPredicate.test(data); } @@ -98,29 +96,23 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + (data == null ? 0 : data.hashCode()); result = prime * result + (isDeleted ? 1231 : 1237); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof BinarySearchTreeLeaf<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof BinarySearchTreeLeaf<?>)) return false; - BinarySearchTreeLeaf<?> other = (BinarySearchTreeLeaf<?>) obj; + final BinarySearchTreeLeaf<?> other = (BinarySearchTreeLeaf<?>) obj; if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (isDeleted != other.isDeleted) - return false; + if (other.data != null) return false; + } else if (!data.equals(other.data)) return false; + if (isDeleted != other.isDeleted) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java index 527f221..9f45c17 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java @@ -1,15 +1,15 @@ package bjc.utils.funcdata.bst; -import java.util.Comparator; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; - import static bjc.utils.funcdata.bst.DirectedWalkFunction.DirectedWalkResult.FAILURE; import static bjc.utils.funcdata.bst.DirectedWalkFunction.DirectedWalkResult.LEFT; import static bjc.utils.funcdata.bst.DirectedWalkFunction.DirectedWalkResult.RIGHT; import static bjc.utils.funcdata.bst.DirectedWalkFunction.DirectedWalkResult.SUCCESS; +import java.util.Comparator; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + /** * A binary node in a tree. * @@ -39,16 +39,15 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { * @param rght * The right child of this node. */ - public BinarySearchTreeNode(T element, ITreePart<T> lft, ITreePart<T> rght) { + public BinarySearchTreeNode(final T element, final ITreePart<T> lft, final ITreePart<T> rght) { super(element); this.left = lft; this.right = rght; } @Override - public void add(T element, Comparator<T> comparator) { - if (comparator == null) - throw new NullPointerException("Comparator must not be null"); + public void add(final T element, final Comparator<T> comparator) { + if (comparator == null) throw new NullPointerException("Comparator must not be null"); switch (comparator.compare(data, element)) { case -1: @@ -61,8 +60,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { case 0: if (isDeleted) { isDeleted = false; - } else - throw new IllegalArgumentException("Can't add duplicate values"); + } else throw new IllegalArgumentException("Can't add duplicate values"); break; case 1: if (right == null) { @@ -77,19 +75,20 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public <E> E collapse(Function<T, E> nodeCollapser, BiFunction<E, E, E> branchCollapser) { + public <E> E collapse(final Function<T, E> nodeCollapser, final BiFunction<E, E, E> branchCollapser) { if (nodeCollapser == null || branchCollapser == null) throw new NullPointerException("Collapser must not be null"); - E collapsedNode = nodeCollapser.apply(data); + final E collapsedNode = nodeCollapser.apply(data); if (left != null) { - E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); + final E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); if (right != null) { - E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); + final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); - E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, collapsedRightBranch); + final E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, + collapsedRightBranch); return branchCollapser.apply(collapsedNode, collapsedBranches); } @@ -98,7 +97,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } if (right != null) { - E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); + final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); return branchCollapser.apply(collapsedNode, collapsedRightBranch); } @@ -107,9 +106,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean contains(T element, Comparator<T> comparator) { - if (comparator == null) - throw new NullPointerException("Comparator must not be null"); + public boolean contains(final T element, final Comparator<T> comparator) { + if (comparator == null) throw new NullPointerException("Comparator must not be null"); return directedWalk(currentElement -> { switch (comparator.compare(element, currentElement)) { @@ -126,9 +124,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public void delete(T element, Comparator<T> comparator) { - if (comparator == null) - throw new NullPointerException("Comparator must not be null"); + public void delete(final T element, final Comparator<T> comparator) { + if (comparator == null) throw new NullPointerException("Comparator must not be null"); directedWalk(currentElement -> { switch (comparator.compare(data, element)) { @@ -146,9 +143,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean directedWalk(DirectedWalkFunction<T> treeWalker) { - if (treeWalker == null) - throw new NullPointerException("Walker must not be null"); + public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { + if (treeWalker == null) throw new NullPointerException("Walker must not be null"); switch (treeWalker.walk(data)) { case SUCCESS: @@ -165,11 +161,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + public boolean forEach(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { if (linearizationMethod == null) throw new NullPointerException("Linearization method must not be null"); - else if (traversalPredicate == null) - throw new NullPointerException("Predicate must not be null"); + else if (traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); switch (linearizationMethod) { case PREORDER: @@ -184,48 +180,41 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } } - private boolean inorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) - return false; + private boolean inorderTraverse(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseElement(traversalPredicate)) - return false; + if (!traverseElement(traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) - return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; return true; } - private boolean postorderTraverse(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) - return false; + private boolean postorderTraverse(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) - return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseElement(traversalPredicate)) - return false; + if (!traverseElement(traversalPredicate)) return false; return true; } - private boolean preorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { - if (!traverseElement(traversalPredicate)) - return false; + private boolean preorderTraverse(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { + if (!traverseElement(traversalPredicate)) return false; - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) - return false; + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) - return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; return true; } - private boolean traverseElement(Predicate<T> traversalPredicate) { + private boolean traverseElement(final Predicate<T> traversalPredicate) { boolean nodeSuccesfullyTraversed; if (isDeleted) { @@ -237,8 +226,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return nodeSuccesfullyTraversed; } - private boolean traverseLeftBranch(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + private boolean traverseLeftBranch(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { boolean leftSuccesfullyTraversed; if (left == null) { @@ -250,8 +239,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return leftSuccesfullyTraversed; } - private boolean traverseRightBranch(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + private boolean traverseRightBranch(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { boolean rightSuccesfullyTraversed; if (right == null) { @@ -272,33 +261,26 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + ((left == null) ? 0 : left.hashCode()); - result = prime * result + ((right == null) ? 0 : right.hashCode()); + result = prime * result + (left == null ? 0 : left.hashCode()); + result = prime * result + (right == null ? 0 : right.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (!(obj instanceof BinarySearchTreeNode<?>)) - return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (!super.equals(obj)) return false; + if (!(obj instanceof BinarySearchTreeNode<?>)) return false; - BinarySearchTreeNode<?> other = (BinarySearchTreeNode<?>) obj; + final BinarySearchTreeNode<?> other = (BinarySearchTreeNode<?>) obj; if (left == null) { - if (other.left != null) - return false; - } else if (!left.equals(other.left)) - return false; + if (other.left != null) return false; + } else if (!left.equals(other.left)) return false; if (right == null) { - if (other.right != null) - return false; - } else if (!right.equals(other.right)) - return false; + if (other.right != null) return false; + } else if (!right.equals(other.right)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java index 5380b24..13c1709 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java @@ -15,9 +15,9 @@ import java.util.function.Function; public interface Bifunctor<LeftType, RightType> { /** * Alias for functor mapping. - * + * * @author EVE - * + * * @param <OldLeft> * @param <OldRight> * @param <NewLeft> @@ -30,7 +30,7 @@ public interface Bifunctor<LeftType, RightType> { /** * Alias for left functor mapping. - * + * * @author EVE * * @param <OldLeft> @@ -44,7 +44,7 @@ public interface Bifunctor<LeftType, RightType> { /** * Alias for right functor mapping. - * + * * @author EVE * * @param <OldLeft> @@ -75,12 +75,12 @@ public interface Bifunctor<LeftType, RightType> { * @return A function that maps over both parts of the pair */ public default <OldLeft, OldRight, NewLeft, NewRight> BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimap( - Function<OldLeft, NewLeft> leftFunc, Function<OldRight, NewRight> rightFunc) { - BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimappedFunc = (argPair) -> { - LeftBifunctorMap<OldLeft, OldRight, NewLeft> leftMapper = argPair.fmapLeft(leftFunc); + final Function<OldLeft, NewLeft> leftFunc, final Function<OldRight, NewRight> rightFunc) { + final BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimappedFunc = (argPair) -> { + final LeftBifunctorMap<OldLeft, OldRight, NewLeft> leftMapper = argPair.fmapLeft(leftFunc); - Bifunctor<NewLeft, OldRight> leftMappedFunctor = leftMapper.apply(argPair); - RightBifunctorMap<NewLeft, OldRight, NewRight> rightMapper = leftMappedFunctor + final Bifunctor<NewLeft, OldRight> leftMappedFunctor = leftMapper.apply(argPair); + final RightBifunctorMap<NewLeft, OldRight, NewRight> rightMapper = leftMappedFunctor .fmapRight(rightFunc); return rightMapper.apply(leftMappedFunctor); diff --git a/BJC-Utils2/src/main/java/bjc/utils/functypes/ID.java b/BJC-Utils2/src/main/java/bjc/utils/functypes/ID.java index edaaee5..d3197e2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/functypes/ID.java +++ b/BJC-Utils2/src/main/java/bjc/utils/functypes/ID.java @@ -4,13 +4,14 @@ import java.util.function.UnaryOperator; /**
* Identity function.
+ *
* @author bjculkin
*
*/
public class ID {
/**
* Create an identity function.
- *
+ *
* @return A identity function.
*/
public static <A> UnaryOperator<A> id() {
diff --git a/BJC-Utils2/src/main/java/bjc/utils/functypes/ListFlattener.java b/BJC-Utils2/src/main/java/bjc/utils/functypes/ListFlattener.java index a94e19f..cfa0c8b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/functypes/ListFlattener.java +++ b/BJC-Utils2/src/main/java/bjc/utils/functypes/ListFlattener.java @@ -6,7 +6,7 @@ import bjc.utils.funcdata.IList; /** * A function that flattens a list. - * + * * @author bjculkin * * @param <S> diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java index 9a8cca3..a044bfd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -1,10 +1,10 @@ package bjc.utils.funcutils; +import java.util.stream.Collector; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; -import java.util.stream.Collector; - /** * Utilities for producing implementations of {@link Collector} * @@ -32,8 +32,8 @@ public class CollectorUtils { * @return A collector that functions as mentioned above */ public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> compoundCollect( - Collector<InitialType, AuxType1, FinalType1> first, - Collector<InitialType, AuxType2, FinalType2> second) { + final Collector<InitialType, AuxType1, FinalType1> first, + final Collector<InitialType, AuxType2, FinalType2> second) { return new CompoundCollector<>(first, second); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java index ef259d5..35695bc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -1,10 +1,5 @@ package bjc.utils.funcutils; -import bjc.utils.data.IHolder; -import bjc.utils.data.IPair; -import bjc.utils.data.Identity; -import bjc.utils.data.Pair; - import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; @@ -12,16 +7,21 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; +import bjc.utils.data.IHolder; +import bjc.utils.data.IPair; +import bjc.utils.data.Identity; +import bjc.utils.data.Pair; + final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2> implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> { - private Set<java.util.stream.Collector.Characteristics> characteristicSet; + private final Set<java.util.stream.Collector.Characteristics> characteristicSet; - private Collector<InitialType, AuxType1, FinalType1> first; - private Collector<InitialType, AuxType2, FinalType2> second; + private final Collector<InitialType, AuxType1, FinalType1> first; + private final Collector<InitialType, AuxType2, FinalType2> second; - public CompoundCollector(Collector<InitialType, AuxType1, FinalType1> first, - Collector<InitialType, AuxType2, FinalType2> second) { + public CompoundCollector(final Collector<InitialType, AuxType1, FinalType1> first, + final Collector<InitialType, AuxType2, FinalType2> second) { this.first = first; this.second = second; @@ -31,8 +31,8 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public BiConsumer<IHolder<IPair<AuxType1, AuxType2>>, InitialType> accumulator() { - BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); - BiConsumer<AuxType2, InitialType> secondAccumulator = second.accumulator(); + final BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); + final BiConsumer<AuxType2, InitialType> secondAccumulator = second.accumulator(); return (state, value) -> { state.doWith(statePair -> { @@ -51,8 +51,8 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public BinaryOperator<IHolder<IPair<AuxType1, AuxType2>>> combiner() { - BinaryOperator<AuxType1> firstCombiner = first.combiner(); - BinaryOperator<AuxType2> secondCombiner = second.combiner(); + final BinaryOperator<AuxType1> firstCombiner = first.combiner(); + final BinaryOperator<AuxType2> secondCombiner = second.combiner(); return (leftState, rightState) -> { return leftState.unwrap(leftPair -> { @@ -68,8 +68,8 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final return state -> { return state.unwrap(pair -> { return pair.bind((left, right) -> { - FinalType1 finalLeft = first.finisher().apply(left); - FinalType2 finalRight = second.finisher().apply(right); + final FinalType1 finalLeft = first.finisher().apply(left); + final FinalType2 finalRight = second.finisher().apply(right); return new Pair<>(finalLeft, finalRight); }); @@ -80,8 +80,8 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public Supplier<IHolder<IPair<AuxType1, AuxType2>>> supplier() { return () -> { - AuxType1 initialLeft = first.supplier().get(); - AuxType2 initialRight = second.supplier().get(); + final AuxType1 initialLeft = first.supplier().get(); + final AuxType2 initialRight = second.supplier().get(); return new Identity<>(new Pair<>(initialLeft, initialRight)); }; diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java index cab444d..e4c0bda 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -1,11 +1,11 @@ package bjc.utils.funcutils; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.Random; import java.util.function.Consumer; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * Utility methods on enums * @@ -27,16 +27,16 @@ public class EnumUtils { * @param rnd * The source of randomness to use */ - public static <E extends Enum<E>> void doForValues(Class<E> clasz, int nValues, Consumer<E> action, - Random rnd) { - E[] enumValues = clasz.getEnumConstants(); + public static <E extends Enum<E>> void doForValues(final Class<E> clasz, final int nValues, + final Consumer<E> action, final Random rnd) { + final E[] enumValues = clasz.getEnumConstants(); - IList<E> valueList = new FunctionalList<>(enumValues); + final IList<E> valueList = new FunctionalList<>(enumValues); - int randomValueCount = enumValues.length - nValues; + final int randomValueCount = enumValues.length - nValues; - for(int i = 0; i <= randomValueCount; i++) { - E rDir = valueList.randItem(rnd::nextInt); + for (int i = 0; i <= randomValueCount; i++) { + final E rDir = valueList.randItem(rnd::nextInt); valueList.removeMatching(rDir); } @@ -55,8 +55,8 @@ public class EnumUtils { * The random source to use * @return A random value from the specified enum */ - public static <E extends Enum<E>> E getRandomValue(Class<E> clasz, Random rnd) { - E[] enumValues = clasz.getEnumConstants(); + public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz, final Random rnd) { + final E[] enumValues = clasz.getEnumConstants(); return new FunctionalList<>(enumValues).randItem(rnd::nextInt); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java index 4c9c525..87199b1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -33,8 +33,8 @@ public class FileUtils { * for this with all the buttons and knobs from * walkFileTree */ - public static void traverseDirectory(Path root, BiPredicate<Path, BasicFileAttributes> predicate, - BiPredicate<Path, BasicFileAttributes> action) throws IOException { + public static void traverseDirectory(final Path root, final BiPredicate<Path, BasicFileAttributes> predicate, + final BiPredicate<Path, BasicFileAttributes> action) throws IOException { Files.walkFileTree(root, new FunctionalFileVisitor(predicate, action)); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java index 4c0abaf..0d1a688 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -26,7 +26,7 @@ public class FuncUtils { * @return The function transformed into a unary function returning a * function */ - public static <A, B, C> Function<A, Function<B, C>> curry2(BiFunction<A, B, C> func) { + public static <A, B, C> Function<A, Function<B, C>> curry2(final BiFunction<A, B, C> func) { return arg1 -> arg2 -> { return func.apply(arg1, arg2); }; @@ -40,7 +40,7 @@ public class FuncUtils { * @param cons * The action to perform */ - public static void doTimes(int nTimes, Consumer<Integer> cons) { + public static void doTimes(final int nTimes, final Consumer<Integer> cons) { for (int i = 0; i < nTimes; i++) { cons.accept(i); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java index 8c3e1eb..4310416 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -8,27 +8,25 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.function.BiPredicate; final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { - private BiPredicate<Path, BasicFileAttributes> predicate; - private BiPredicate<Path, BasicFileAttributes> action; + private final BiPredicate<Path, BasicFileAttributes> predicate; + private final BiPredicate<Path, BasicFileAttributes> action; - public FunctionalFileVisitor(BiPredicate<Path, BasicFileAttributes> predicate, - BiPredicate<Path, BasicFileAttributes> action) { + public FunctionalFileVisitor(final BiPredicate<Path, BasicFileAttributes> predicate, + final BiPredicate<Path, BasicFileAttributes> action) { this.predicate = predicate; this.action = action; } @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - if (predicate.test(dir, attrs)) - return FileVisitResult.CONTINUE; + public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { + if (predicate.test(dir, attrs)) return FileVisitResult.CONTINUE; return FileVisitResult.SKIP_SUBTREE; } @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (action.test(file, attrs)) - return FileVisitResult.CONTINUE; + public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { + if (action.test(file, attrs)) return FileVisitResult.CONTINUE; return FileVisitResult.TERMINATE; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java index a65f83a..f3b2254 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -1,11 +1,11 @@ package bjc.utils.funcutils; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.function.Consumer; import java.util.function.Function; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * Implements a single group partitioning pass on a list * @@ -15,18 +15,18 @@ import java.util.function.Function; * The type of element in the list being partitioned */ final class GroupPartIteration<E> implements Consumer<E> { - private IList<IList<E>> returnedList; + private final IList<IList<E>> returnedList; public IList<E> currentPartition; - private IList<E> rejectedItems; + private final IList<E> rejectedItems; - private int numberInCurrentPartition; - private int numberPerPartition; + private int numberInCurrentPartition; + private final int numberPerPartition; - private Function<E, Integer> elementCounter; + private final Function<E, Integer> elementCounter; - public GroupPartIteration(IList<IList<E>> returned, IList<E> rejects, int nPerPart, - Function<E, Integer> eleCount) { + public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, final int nPerPart, + final Function<E, Integer> eleCount) { this.returnedList = returned; this.rejectedItems = rejects; this.numberPerPartition = nPerPart; @@ -37,8 +37,8 @@ final class GroupPartIteration<E> implements Consumer<E> { } @Override - public void accept(E value) { - boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition; + public void accept(final E value) { + final boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition; if (shouldStartPartition) { returnedList.add(currentPartition); @@ -46,9 +46,10 @@ final class GroupPartIteration<E> implements Consumer<E> { currentPartition = new FunctionalList<>(); numberInCurrentPartition = 0; } else { - int currentElementCount = elementCounter.apply(value); + final int currentElementCount = elementCounter.apply(value); - boolean shouldReject = numberInCurrentPartition + currentElementCount >= numberPerPartition; + final boolean shouldReject = numberInCurrentPartition + + currentElementCount >= numberPerPartition; if (shouldReject) { rejectedItems.add(value); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/LambdaLock.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/LambdaLock.java index 23745d8..62c5d32 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/LambdaLock.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/LambdaLock.java @@ -8,13 +8,13 @@ import java.util.function.Supplier; /** * A wrapper around a {@link ReadWriteLock} to ensure that the lock is used * properly. - * + * * @author EVE * */ public class LambdaLock { - private Lock readLock; - private Lock writeLock; + private final Lock readLock; + private final Lock writeLock; /** * Create a new lambda-enabled lock around a new lock. @@ -25,24 +25,24 @@ public class LambdaLock { /** * Create a new lambda-enabled lock. - * + * * @param lck * The lock to wrap. */ - public LambdaLock(ReadWriteLock lck) { + public LambdaLock(final ReadWriteLock lck) { readLock = lck.readLock(); writeLock = lck.writeLock(); } /** * Execute an action with the read lock taken. - * + * * @param supp * The action to call. - * + * * @return The result of the action. */ - public <T> T read(Supplier<T> supp) { + public <T> T read(final Supplier<T> supp) { readLock.lock(); try { @@ -54,13 +54,13 @@ public class LambdaLock { /** * Execute an action with the write lock taken. - * + * * @param supp * The action to call. - * + * * @return The result of the action. */ - public <T> T write(Supplier<T> supp) { + public <T> T write(final Supplier<T> supp) { writeLock.lock(); try { @@ -72,12 +72,12 @@ public class LambdaLock { /** * Execute an action with the read lock taken. - * + * * @param action * The action to call. - * + * */ - public void read(Runnable action) { + public void read(final Runnable action) { readLock.lock(); try { @@ -89,11 +89,11 @@ public class LambdaLock { /** * Execute an action with the write lock taken. - * + * * @param action * The action to call. */ - public void write(Runnable action) { + public void write(final Runnable action) { writeLock.lock(); try { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java index ad0f565..52a2437 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -1,13 +1,13 @@ package bjc.utils.funcutils; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.ArrayList; import java.util.Iterator; import java.util.function.Function; import java.util.function.Supplier; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * Utilities for manipulating FunctionalLists that don't belong in the class * itself @@ -26,8 +26,8 @@ public class ListUtils { * The list of tokens to collapse * @return The collapsed string of tokens */ - public static String collapseTokens(IList<String> input) { - if(input == null) throw new NullPointerException("Input must not be null"); + public static String collapseTokens(final IList<String> input) { + if (input == null) throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); } @@ -42,23 +42,23 @@ public class ListUtils { * The separator to use for separating tokens * @return The collapsed string of tokens */ - public static String collapseTokens(IList<String> input, String seperator) { - if(input == null) + public static String collapseTokens(final IList<String> input, final String seperator) { + if (input == null) throw new NullPointerException("Input must not be null"); - else if(seperator == null) throw new NullPointerException("Seperator must not be null"); + else if (seperator == null) throw new NullPointerException("Seperator must not be null"); - if(input.getSize() < 1) + if (input.getSize() < 1) return ""; - else if(input.getSize() == 1) + else if (input.getSize() == 1) return input.first(); else { - StringBuilder state = new StringBuilder(); + final StringBuilder state = new StringBuilder(); int i = 1; - for(String itm : input.toIterable()) { + for (final String itm : input.toIterable()) { state.append(itm); - if(i != input.getSize()) { + if (i != input.getSize()) { state.append(seperator); } @@ -85,23 +85,24 @@ public class ListUtils { * selected from the specified list without replacement */ - public static <E> IList<E> drawWithoutReplacement(IList<E> list, int number, Function<Integer, Integer> rng) { - IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); + public static <E> IList<E> drawWithoutReplacement(final IList<E> list, final int number, + final Function<Integer, Integer> rng) { + final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); - int total = list.getSize(); + final int total = list.getSize(); - Iterator<E> itr = list.toIterable().iterator(); + final Iterator<E> itr = list.toIterable().iterator(); E element = null; - for(int index = 0; itr.hasNext(); element = itr.next()) { + for (final int index = 0; itr.hasNext(); element = itr.next()) { // n - m - int winningChance = number - selected.getSize(); + final int winningChance = number - selected.getSize(); // N - t - int totalChance = total - (index - 1); + final int totalChance = total - (index - 1); // Probability of selecting the t+1'th element - if(NumberUtils.isProbable(winningChance, totalChance, rng)) { + if (NumberUtils.isProbable(winningChance, totalChance, rng)) { selected.add(element); } } @@ -124,10 +125,11 @@ public class ListUtils { * @return A new list containing the desired number of items randomly * selected from the specified list */ - public static <E> IList<E> drawWithReplacement(IList<E> list, int number, Function<Integer, Integer> rng) { - IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); + public static <E> IList<E> drawWithReplacement(final IList<E> list, final int number, + final Function<Integer, Integer> rng) { + final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); - for(int i = 0; i < number; i++) { + for (int i = 0; i < number; i++) { selected.add(list.randItem(rng)); } @@ -151,15 +153,15 @@ public class ListUtils { * * @return A list partitioned according to the above rules */ - public static <E> IList<IList<E>> groupPartition(IList<E> input, Function<E, Integer> counter, - int partitionSize) { - if(input == null) + public static <E> IList<IList<E>> groupPartition(final IList<E> input, final Function<E, Integer> counter, + final int partitionSize) { + if (input == null) throw new NullPointerException("Input list must not be null"); - else if(counter == null) + else if (counter == null) throw new NullPointerException("Counter must not be null"); - else if(partitionSize < 1 || partitionSize > input.getSize()) { - String fmt = "%d is not a valid partition size. Must be between 1 and %d"; - String msg = String.format(fmt, partitionSize, input.getSize()); + else if (partitionSize < 1 || partitionSize > input.getSize()) { + final String fmt = "%d is not a valid partition size. Must be between 1 and %d"; + final String msg = String.format(fmt, partitionSize, input.getSize()); throw new IllegalArgumentException(msg); } @@ -167,23 +169,23 @@ public class ListUtils { /* * List that holds our results */ - IList<IList<E>> returned = new FunctionalList<>(); + final IList<IList<E>> returned = new FunctionalList<>(); /* * List that holds elements rejected during current pass */ - IList<E> rejected = new FunctionalList<>(); + final IList<E> rejected = new FunctionalList<>(); - GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter); + final GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter); /* * Run up to a certain number of passes */ - for(int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART + for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART && !rejected.isEmpty(); numberOfIterations++) { input.forEach(it); - if(rejected.isEmpty()) // Nothing was rejected, so + if (rejected.isEmpty()) // Nothing was rejected, so // we're // done return returned; @@ -206,11 +208,11 @@ public class ListUtils { * @return A list containing all the elements of the lists */ @SafeVarargs - public static <E> IList<E> mergeLists(IList<E>... lists) { - IList<E> returned = new FunctionalList<>(); + public static <E> IList<E> mergeLists(final IList<E>... lists) { + final IList<E> returned = new FunctionalList<>(); - for(IList<E> list : lists) { - for(E itm : list.toIterable()) { + for (final IList<E> list : lists) { + for (final E itm : list.toIterable()) { returned.add(itm); } } @@ -235,27 +237,28 @@ public class ListUtils { * @throws IllegalArgumentException * if the list couldn't be padded to the desired size */ - public static <E> IList<E> padList(IList<E> list, Function<E, Integer> counter, int size, Supplier<E> padder) { + public static <E> IList<E> padList(final IList<E> list, final Function<E, Integer> counter, final int size, + final Supplier<E> padder) { int count = 0; - IList<E> returned = new FunctionalList<>(); + final IList<E> returned = new FunctionalList<>(); - for(E itm : list.toIterable()) { + for (final E itm : list.toIterable()) { count += counter.apply(itm); returned.add(itm); } - if(count % size != 0) { + if (count % size != 0) { // We need to pad int needed = count % size; int threshold = 0; - while(needed > 0 && threshold <= MAX_NTRIESPART) { - E val = padder.get(); - int newCount = counter.apply(val); + while (needed > 0 && threshold <= MAX_NTRIESPART) { + final E val = padder.get(); + final int newCount = counter.apply(val); - if(newCount <= needed) { + if (newCount <= needed) { returned.add(val); threshold = 0; @@ -266,7 +269,7 @@ public class ListUtils { } } - if(threshold > MAX_NTRIESPART) + if (threshold > MAX_NTRIESPART) throw new IllegalArgumentException("Heuristic (more than " + MAX_NTRIESPART + " iterations of attempting to pad) detected unpaddable list "); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java index 8a14d7d..770d3a5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java @@ -18,15 +18,15 @@ public class NumberUtils { * The power to do the falling factorial for * @return The falling factorial of the number to the power */ - public static int fallingFactorial(int value, int power) { - if(power == 0) + public static int fallingFactorial(final int value, final int power) { + if (power == 0) return 1; - else if(power == 1) + else if (power == 1) return value; else { int result = 1; - for(int currentSub = 0; currentSub < power + 1; currentSub++) { + for (int currentSub = 0; currentSub < power + 1; currentSub++) { result *= value - currentSub; } @@ -45,25 +45,25 @@ public class NumberUtils { * The function to use to generate a random possibility * @return Whether or not a random possibility was a winning one */ - public static boolean isProbable(int winning, int total, Function<Integer, Integer> rng) { + public static boolean isProbable(final int winning, final int total, final Function<Integer, Integer> rng) { return rng.apply(total) < winning; } /** * Check if a number is in an inclusive range. - * + * * @param min * The minimum value of the range. - * + * * @param max * The maximum value of the range. - * + * * @param i * The number to check. - * + * * @return Whether the number is in the range. */ - public static boolean between(int min, int max, int i) { - return (i >= min) && (i <= max); + public static boolean between(final int min, final int max, final int i) { + return i >= min && i <= max; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java index d5eaadf..6e24e50 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -1,9 +1,9 @@ package bjc.utils.funcutils; -import com.ibm.icu.text.BreakIterator; - import java.util.Deque; +import com.ibm.icu.text.BreakIterator; + /** * Utility methods for operations on strings * @@ -16,25 +16,25 @@ public class StringUtils { * expression * * @param input - * The string to check + * The string to check * @param rRegex - * The regex to see if the string only contains matches of - * @return Whether or not the string consists only of multiple matches of - * the provided regex + * The regex to see if the string only contains matches + * of + * @return Whether or not the string consists only of multiple matches + * of the provided regex */ - public static boolean containsOnly(String input, String rRegex) { + public static boolean containsOnly(final String input, final String rRegex) { if (input == null) throw new NullPointerException("Input must not be null"); - else if (rRegex == null) - throw new NullPointerException("Regex must not be null"); + else if (rRegex == null) throw new NullPointerException("Regex must not be null"); /* * This regular expression is fairly simple. * * First, we match the beginning of the string. Then, we start a - * non-capturing group whose contents are the passed in regex. That - * group is then matched one or more times and the pattern matches to - * the end of the string + * non-capturing group whose contents are the passed in regex. + * That group is then matched one or more times and the pattern + * matches to the end of the string */ return input.matches("\\A(?:" + rRegex + ")+\\Z"); } @@ -43,51 +43,51 @@ public class StringUtils { * Indent the string being built in a StringBuilder n levels * * @param builder - * The builder to indent in + * The builder to indent in * @param levels - * The number of levels to indent + * The number of levels to indent */ - public static void indentNLevels(StringBuilder builder, int levels) { + public static void indentNLevels(final StringBuilder builder, final int levels) { for (int i = 0; i < levels; i++) { builder.append("\t"); } } /** - * Print out a deque with a special case for easily showing a deque is empty + * Print out a deque with a special case for easily showing a deque is + * empty * * @param <ContainedType> - * The type in the deque + * The type in the deque * @param queue - * The deque to print - * @return A string version of the deque, with allowance for an empty deque + * The deque to print + * @return A string version of the deque, with allowance for an empty + * deque */ - public static <ContainedType> String printDeque(Deque<ContainedType> queue) { + public static <ContainedType> String printDeque(final Deque<ContainedType> queue) { return queue.isEmpty() ? "(none)" : queue.toString(); } /** * Converts a sequence to an English list. - * + * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * @param join - * The string to use for separating the last element from the - * rest. + * The string to use for separating the last element from + * the rest. * @param comma - * The string to use as a comma - * + * The string to use as a comma + * * @return The sequence as an English list. */ - public static String toEnglishList(Object[] objects, String join, String comma) { - if (objects == null) { - throw new NullPointerException("Sequence must not be null"); - } + public static String toEnglishList(final Object[] objects, final String join, final String comma) { + if (objects == null) throw new NullPointerException("Sequence must not be null"); - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); - String joiner = join; - String coma = comma; + final String joiner = join; + final String coma = comma; switch (objects.length) { case 0: @@ -119,9 +119,9 @@ public class StringUtils { } /* * Uncomment this to remove serial commas. - * + * * int lc = sb.length() - 1; - * + * * sb.delete(lc - coma.length(), lc); */ sb.append(joiner + " "); @@ -133,47 +133,45 @@ public class StringUtils { /** * Converts a sequence to an English list. - * + * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * @param join - * The string to use for separating the last element from the - * rest. - * + * The string to use for separating the last element from + * the rest. + * * @return The sequence as an English list. */ - public static String toEnglishList(Object[] objects, String join) { + public static String toEnglishList(final Object[] objects, final String join) { return toEnglishList(objects, join, ","); } /** * Converts a sequence to an English list. - * + * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * @param and - * Whether to use 'and' or 'or'. - * + * Whether to use 'and' or 'or'. + * * @return The sequence as an English list. */ - public static String toEnglishList(Object[] objects, boolean and) { - if (and) { + public static String toEnglishList(final Object[] objects, final boolean and) { + if (and) return toEnglishList(objects, "and"); - } else { - return toEnglishList(objects, "or"); - } + else return toEnglishList(objects, "or"); } /** * Count the number of graphemes in a string. - * + * * @param value - * The string to check. - * + * The string to check. + * * @return The number of graphemes in the string. */ - public static int graphemeCount(String value) { - BreakIterator it = BreakIterator.getCharacterInstance(); + public static int graphemeCount(final String value) { + final BreakIterator it = BreakIterator.getCharacterInstance(); it.setText(value); int count = 0; diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TriConsumer.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TriConsumer.java index c161ed7..f30386c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TriConsumer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TriConsumer.java @@ -2,9 +2,9 @@ package bjc.utils.funcutils; /** * Consumer that takes three arguments. - * + * * @author EVE - * + * * @param <A> * Type of the first argument. * @param <B> @@ -17,13 +17,13 @@ package bjc.utils.funcutils; public interface TriConsumer<A, B, C> { /** * Perform the action. - * + * * @param a * The first parameter. - * + * * @param b * The second parameter. - * + * * @param c * The third parameter. */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java index 4153e7d..3de08d6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -28,8 +28,8 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * The cases to add for this rule. */ @SafeVarargs - public final void addCases(E rule, IList<E>... cases) { - for(IList<E> currentCase : cases) { + public final void addCases(final E rule, final IList<E>... cases) { + for (final IList<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -43,10 +43,10 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * The cases to add for this rule. */ @SafeVarargs - public final void makeRule(E rule, IList<E>... cases) { + public final void makeRule(final E rule, final IList<E>... cases) { super.addRule(rule); - for(IList<E> currentCase : cases) { + for (final IList<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -59,8 +59,8 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * @param cases * The cases to add for this rule. */ - public void makeRule(E rule, IList<IList<E>> cases) { - if(cases == null) throw new NullPointerException("Cases must not be null"); + public void makeRule(final E rule, final IList<IList<E>> cases) { + if (cases == null) throw new NullPointerException("Cases must not be null"); super.addRule(rule); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java index 66ee993..7777ad8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -1,5 +1,11 @@ package bjc.utils.gen; +import java.util.Random; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + import bjc.utils.data.IPair; import bjc.utils.data.Pair; import bjc.utils.funcdata.FunctionalList; @@ -7,12 +13,6 @@ import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; -import java.util.Random; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.function.Supplier; - /** * A random grammar, where certain rules will come up more often than others. * @@ -74,7 +74,7 @@ public class WeightedGrammar<E> { * @param source * The source of randomness to use */ - public WeightedGrammar(Random source) { + public WeightedGrammar(final Random source) { this(); if (source == null) throw new NullPointerException("Source of randomness must be non-null"); @@ -84,28 +84,29 @@ public class WeightedGrammar<E> { /** * Configure the action to perform on special tokens. - * + * * @param marker * The marker to find special tokens. - * + * * @param action * The action to take on those tokens. */ - public void configureSpecial(Predicate<E> marker, BiFunction<E, WeightedGrammar<E>, IList<E>> action) { + public void configureSpecial(final Predicate<E> marker, + final BiFunction<E, WeightedGrammar<E>, IList<E>> action) { specialMarker = marker; specialAction = action; } /** * Adds a special rule to the grammar. - * + * * @param ruleName * The name of the special rule. - * + * * @param cse * The case for the rule. */ - public void addSpecialRule(E ruleName, Supplier<IList<E>> cse) { + public void addSpecialRule(final E ruleName, final Supplier<IList<E>> cse) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); else if (cse == null) throw new NullPointerException("Case must not be null"); @@ -123,7 +124,7 @@ public class WeightedGrammar<E> { * @param cse * The case being added. */ - public void addCase(E ruleName, int probability, IList<E> cse) { + public void addCase(final E ruleName, final int probability, final IList<E> cse) { if (ruleName == null) throw new NullPointerException("Rule name must be not null"); else if (cse == null) throw new NullPointerException("Case body must not be null"); @@ -140,7 +141,7 @@ public class WeightedGrammar<E> { * The alias of the subgrammar * @return Whether the alias was succesfully created */ - public boolean addGrammarAlias(E name, E alias) { + public boolean addGrammarAlias(final E name, final E alias) { if (name == null) throw new NullPointerException("Subgrammar name must not be null"); else if (alias == null) throw new NullPointerException("Subgrammar alias must not be null"); @@ -162,7 +163,7 @@ public class WeightedGrammar<E> { * The name of the rule to add. * @return Whether or not the rule was successfully added. */ - public boolean addRule(E name) { + public boolean addRule(final E name) { if (rng == null) { rng = new Random(); } @@ -181,7 +182,7 @@ public class WeightedGrammar<E> { * The set of cases for the rule. * @return Whether or not the rule was succesfully added. */ - public boolean addRule(E name, WeightedRandom<IList<E>> cases) { + public boolean addRule(final E name, final WeightedRandom<IList<E>> cases) { if (name == null) throw new NullPointerException("Name must not be null"); else if (cases == null) throw new NullPointerException("Cases must not be null"); @@ -201,7 +202,7 @@ public class WeightedGrammar<E> { * The subgrammar to add. * @return Whether or not the subgrammar was succesfully added. */ - public boolean addSubgrammar(E name, WeightedGrammar<E> subgrammar) { + public boolean addSubgrammar(final E name, final WeightedGrammar<E> subgrammar) { if (name == null) throw new NullPointerException("Subgrammar name must not be null"); else if (subgrammar == null) throw new NullPointerException("Subgrammar must not be null"); @@ -218,7 +219,7 @@ public class WeightedGrammar<E> { * @param name * The name of the rule to remove. */ - public void deleteRule(E name) { + public void deleteRule(final E name) { if (name == null) throw new NullPointerException("Rule name must not be null"); rules.remove(name); @@ -230,7 +231,7 @@ public class WeightedGrammar<E> { * @param name * The name of the subgrammar to remove. */ - public void deleteSubgrammar(E name) { + public void deleteSubgrammar(final E name) { if (name == null) throw new NullPointerException("Rule name must not be null"); subgrammars.remove(name); @@ -245,12 +246,12 @@ public class WeightedGrammar<E> { * The rule to test. * @return A set of sentences generated by the specified rule. */ - public IList<IList<E>> generateDebugValues(E ruleName) { + public IList<IList<E>> generateDebugValues(final E ruleName) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); - IList<IList<E>> returnedList = new FunctionalList<>(); + final IList<IList<E>> returnedList = new FunctionalList<>(); - WeightedRandom<IList<E>> ruleGenerator = rules.get(ruleName); + final WeightedRandom<IList<E>> ruleGenerator = rules.get(ruleName); for (int i = 0; i < 10; i++) { returnedList.add(ruleGenerator.generateValue()); @@ -267,25 +268,26 @@ public class WeightedGrammar<E> { * * @param initRules * The initial rule to start with. - * + * * @param tokenTransformer * The function to transform grammar output into * something. - * + * * @param spacer * The spacer element to add in between output tokens. - * + * * @return A randomly generated sentence from the specified initial * rule. */ - public <T> IList<T> generateGenericValues(E initRules, Function<E, T> tokenTransformer, T spacer) { + public <T> IList<T> generateGenericValues(final E initRules, final Function<E, T> tokenTransformer, + final T spacer) { if (initRules == null) throw new NullPointerException("Initial rule must not be null"); else if (tokenTransformer == null) throw new NullPointerException("Transformer must not be null"); else if (spacer == null) throw new NullPointerException("Spacer must not be null"); - IList<T> returnedList = new FunctionalList<>(); + final IList<T> returnedList = new FunctionalList<>(); IList<E> genRules = new FunctionalList<>(initRules); @@ -295,39 +297,39 @@ public class WeightedGrammar<E> { } } - for (E initRule : genRules.toIterable()) { + for (final E initRule : genRules.toIterable()) { if (specialRules.containsKey(initRule)) { - for (E rulePart : specialRules.get(initRule).get().toIterable()) { - Iterable<T> generatedRuleParts = generateGenericValues(rulePart, + for (final E rulePart : specialRules.get(initRule).get().toIterable()) { + final Iterable<T> generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (T generatedRulePart : generatedRuleParts) { + for (final T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } } } else if (subgrammars.containsKey(initRule)) { - Iterable<T> ruleParts = subgrammars.get(initRule) + final Iterable<T> ruleParts = subgrammars.get(initRule) .generateGenericValues(initRule, tokenTransformer, spacer).toIterable(); - for (T rulePart : ruleParts) { + for (final T rulePart : ruleParts) { returnedList.add(rulePart); returnedList.add(spacer); } } else if (rules.containsKey(initRule)) { - Iterable<E> ruleParts = rules.get(initRule).generateValue().toIterable(); + final Iterable<E> ruleParts = rules.get(initRule).generateValue().toIterable(); - for (E rulePart : ruleParts) { - Iterable<T> generatedRuleParts = generateGenericValues(rulePart, + for (final E rulePart : ruleParts) { + final Iterable<T> generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (T generatedRulePart : generatedRuleParts) { + for (final T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } } } else { - T transformedToken = tokenTransformer.apply(initRule); + final T transformedToken = tokenTransformer.apply(initRule); if (transformedToken == null) throw new NullPointerException("Transformer created null token"); @@ -350,8 +352,8 @@ public class WeightedGrammar<E> { * @return A list of random grammar elements generated by the specified * rule. */ - public IList<E> generateListValues(E initRule, E spacer) { - IList<E> retList = generateGenericValues(initRule, strang -> strang, spacer); + public IList<E> generateListValues(final E initRule, final E spacer) { + final IList<E> retList = generateGenericValues(initRule, strang -> strang, spacer); return retList; } @@ -380,7 +382,7 @@ public class WeightedGrammar<E> { * @return The set of all rule names in this grammar */ public IList<E> getRuleNames() { - IList<E> ruleNames = new FunctionalList<>(); + final IList<E> ruleNames = new FunctionalList<>(); ruleNames.addAll(rules.keyList()); ruleNames.addAll(specialRules.keyList()); @@ -395,7 +397,7 @@ public class WeightedGrammar<E> { * The name of the subgrammar to get. * @return The subgrammar with the specified name. */ - public WeightedGrammar<E> getSubgrammar(E name) { + public WeightedGrammar<E> getSubgrammar(final E name) { if (name == null) throw new NullPointerException("Subgrammar name must not be null"); return subgrammars.get(name); @@ -412,13 +414,13 @@ public class WeightedGrammar<E> { /** * Check if this grammar has a given rule. - * + * * @param ruleName * The rule to check for. - * + * * @return Whether or not the grammar has a rule by that name. */ - public boolean hasRule(E ruleName) { + public boolean hasRule(final E ruleName) { return rules.containsKey(ruleName) || specialRules.containsKey(ruleName); } @@ -434,7 +436,8 @@ public class WeightedGrammar<E> { * @param numberOfTimes * The number of times to prefix the token */ - public void multiPrefixRule(E ruleName, E prefixToken, int additionalProbability, int numberOfTimes) { + public void multiPrefixRule(final E ruleName, final E prefixToken, final int additionalProbability, + final int numberOfTimes) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); else if (prefixToken == null) @@ -442,18 +445,18 @@ public class WeightedGrammar<E> { else if (numberOfTimes < 1) throw new IllegalArgumentException("Number of times to prefix must be positive."); - WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<IList<E>> rule = rules.get(ruleName); - IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach((pair) -> { - IList<IList<E>> newRule = new FunctionalList<>(); + final IList<IList<E>> newRule = new FunctionalList<>(); for (int i = 1; i <= numberOfTimes; i++) { - IList<E> newCase = pair.merge((left, right) -> { - IList<E> returnVal = new FunctionalList<>(); + final IList<E> newCase = pair.merge((left, right) -> { + final IList<E> returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for (final E val : right.toIterable()) { returnVal.add(val); } @@ -468,7 +471,7 @@ public class WeightedGrammar<E> { } newRule.forEach((list) -> { - Integer currentProb = pair.merge((left, right) -> left); + final Integer currentProb = pair.merge((left, right) -> left); newResults.add(new Pair<>(currentProb + additionalProbability, list)); }); @@ -492,20 +495,20 @@ public class WeightedGrammar<E> { * @param prefixToken * The token to prefix to the rule */ - public void prefixRule(E ruleName, E prefixToken, int additionalProbability) { + public void prefixRule(final E ruleName, final E prefixToken, final int additionalProbability) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); else if (prefixToken == null) throw new NullPointerException("Prefix token must not be null"); - WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<IList<E>> rule = rules.get(ruleName); - IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach((pair) -> { - IList<E> newCase = pair.merge((left, right) -> { - IList<E> returnVal = new FunctionalList<>(); + final IList<E> newCase = pair.merge((left, right) -> { + final IList<E> returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for (final E val : right.toIterable()) { returnVal.add(val); } @@ -526,7 +529,7 @@ public class WeightedGrammar<E> { * @param initRule * The initial rule of this grammar */ - public void setInitialRule(String initRule) { + public void setInitialRule(final String initRule) { this.initialRule = initRule; } @@ -540,20 +543,20 @@ public class WeightedGrammar<E> { * @param additionalProbability * Additional probability of the prefixed rule */ - public void suffixRule(E ruleName, E suffixToken, int additionalProbability) { + public void suffixRule(final E ruleName, final E suffixToken, final int additionalProbability) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); else if (suffixToken == null) throw new NullPointerException("Prefix token must not be null"); - WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<IList<E>> rule = rules.get(ruleName); - IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach((par) -> { - IList<E> newCase = par.merge((left, right) -> { - IList<E> returnVal = new FunctionalList<>(); + final IList<E> newCase = par.merge((left, right) -> { + final IList<E> returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for (final E val : right.toIterable()) { returnVal.add(val); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java index 88f623e..18225ef 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -1,13 +1,13 @@ package bjc.utils.gen; +import java.util.Random; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; import bjc.utils.data.Identity; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; -import java.util.Random; - /** * Represents a random number generator where certain results are weighted more * heavily than others. @@ -21,17 +21,17 @@ public class WeightedRandom<E> { /* * The list of probabilities for each result */ - private IList<Integer> probabilities; + private final IList<Integer> probabilities; /* * The list of possible results to pick from */ - private IList<E> results; + private final IList<E> results; /* * The source for any needed random numbers */ - private Random source; + private final Random source; private int totalChance; @@ -42,11 +42,11 @@ public class WeightedRandom<E> { * @param src * The source of randomness to use. */ - public WeightedRandom(Random src) { + public WeightedRandom(final Random src) { probabilities = new FunctionalList<>(); results = new FunctionalList<>(); - if(src == null) throw new NullPointerException("Source of randomness must not be null"); + if (src == null) throw new NullPointerException("Source of randomness must not be null"); source = src; } @@ -59,7 +59,7 @@ public class WeightedRandom<E> { * @param result * The result to get when the chance comes up. */ - public void addProbability(int chance, E result) { + public void addProbability(final int chance, final E result) { probabilities.add(chance); results.add(result); @@ -72,13 +72,13 @@ public class WeightedRandom<E> { * @return A random value selected in a weighted fashion. */ public E generateValue() { - IHolder<Integer> value = new Identity<>(source.nextInt(totalChance)); - IHolder<E> current = new Identity<>(); - IHolder<Boolean> picked = new Identity<>(true); + final IHolder<Integer> value = new Identity<>(source.nextInt(totalChance)); + final IHolder<E> current = new Identity<>(); + final IHolder<Boolean> picked = new Identity<>(true); probabilities.forEachIndexed((index, probability) -> { - if(picked.unwrap(bool -> bool)) { - if(value.unwrap((number) -> number < probability)) { + if (picked.unwrap(bool -> bool)) { + if (value.unwrap((number) -> number < probability)) { current.transform((result) -> results.getByIndex(index)); picked.transform((bool) -> false); diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java index 9d415b1..446ab5b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -1,5 +1,11 @@ package bjc.utils.graph; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.InputMismatchException; +import java.util.Scanner; + import bjc.utils.data.IHolder; import bjc.utils.data.Identity; import bjc.utils.funcdata.FunctionalList; @@ -8,12 +14,6 @@ import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.FuncUtils; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.InputMismatchException; -import java.util.Scanner; - /** * An adjacency map representing a graph * @@ -30,24 +30,24 @@ public class AdjacencyMap<T> { * The stream of text to read in * @return An adjacency map defined by the text */ - public static AdjacencyMap<Integer> fromStream(InputStream stream) { - if(stream == null) throw new NullPointerException("Input source must not be null"); + public static AdjacencyMap<Integer> fromStream(final InputStream stream) { + if (stream == null) throw new NullPointerException("Input source must not be null"); // Create the adjacency map AdjacencyMap<Integer> adjacency; - try(Scanner input = new Scanner(stream)) { + try (Scanner input = new Scanner(stream)) { input.useDelimiter("\n"); int vertexCount; - String possible = input.next(); + final String possible = input.next(); try { // First, read in number of vertices vertexCount = Integer.parseInt(possible); - } catch(NumberFormatException nfex) { - InputMismatchException imex = new InputMismatchException( + } catch (final NumberFormatException nfex) { + final InputMismatchException imex = new InputMismatchException( "The first line must contain the number of vertices. " + possible + " is not a valid number"); @@ -56,16 +56,16 @@ public class AdjacencyMap<T> { throw imex; } - if(vertexCount <= 0) + if (vertexCount <= 0) throw new InputMismatchException("The number of vertices must be greater than 0"); - IList<Integer> vertices = new FunctionalList<>(); + final IList<Integer> vertices = new FunctionalList<>(); FuncUtils.doTimes(vertexCount, (vertexNo) -> vertices.add(vertexNo)); adjacency = new AdjacencyMap<>(vertices); - IHolder<Integer> row = new Identity<>(0); + final IHolder<Integer> row = new Identity<>(0); input.forEachRemaining((strang) -> { readRow(adjacency, vertexCount, row, strang); @@ -75,22 +75,22 @@ public class AdjacencyMap<T> { return adjacency; } - private static void readRow(AdjacencyMap<Integer> adjacency, int vertexCount, IHolder<Integer> row, - String strang) { - String[] parts = strang.split(" "); + private static void readRow(final AdjacencyMap<Integer> adjacency, final int vertexCount, + final IHolder<Integer> row, final String strang) { + final String[] parts = strang.split(" "); - if(parts.length != vertexCount) + if (parts.length != vertexCount) throw new InputMismatchException("Must specify a weight for all " + vertexCount + " vertices"); int column = 0; - for(String part : parts) { + for (final String part : parts) { int weight; try { weight = Integer.parseInt(part); - } catch(NumberFormatException nfex) { - InputMismatchException imex = new InputMismatchException( + } catch (final NumberFormatException nfex) { + final InputMismatchException imex = new InputMismatchException( "" + part + " is not a valid weight."); imex.initCause(nfex); @@ -109,7 +109,7 @@ public class AdjacencyMap<T> { /** * The backing storage of the map */ - private IMap<T, IMap<T, Integer>> adjacency = new FunctionalMap<>(); + private final IMap<T, IMap<T, Integer>> adjacency = new FunctionalMap<>(); /** * Create a new map from a set of vertices @@ -117,11 +117,11 @@ public class AdjacencyMap<T> { * @param vertices * The set of vertices to create a map from */ - public AdjacencyMap(IList<T> vertices) { - if(vertices == null) throw new NullPointerException("Vertices must not be null"); + public AdjacencyMap(final IList<T> vertices) { + if (vertices == null) throw new NullPointerException("Vertices must not be null"); vertices.forEach(vertex -> { - IMap<T, Integer> row = new FunctionalMap<>(); + final IMap<T, Integer> row = new FunctionalMap<>(); vertices.forEach(target -> { row.put(target, 0); @@ -137,13 +137,13 @@ public class AdjacencyMap<T> { * @return Whether or not the graph is directed */ public boolean isDirected() { - IHolder<Boolean> result = new Identity<>(true); + final IHolder<Boolean> result = new Identity<>(true); adjacency.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { - int inverseValue = adjacency.get(targetKey).get(sourceKey); + final int inverseValue = adjacency.get(targetKey).get(sourceKey); - if(targetValue != inverseValue) { + if (targetValue != inverseValue) { result.replace(false); } }); @@ -162,14 +162,14 @@ public class AdjacencyMap<T> { * @param weight * The weight of the edge */ - public void setWeight(T source, T target, int weight) { - if(source == null) + public void setWeight(final T source, final T target, final int weight) { + if (source == null) throw new NullPointerException("Source vertex must not be null"); - else if(target == null) throw new NullPointerException("Target vertex must not be null"); + else if (target == null) throw new NullPointerException("Target vertex must not be null"); - if(!adjacency.containsKey(source)) + if (!adjacency.containsKey(source)) throw new IllegalArgumentException("Source vertex " + source + " isn't present in map"); - else if(!adjacency.containsKey(target)) + else if (!adjacency.containsKey(target)) throw new IllegalArgumentException("Target vertex " + target + " isn't present in map"); adjacency.get(source).put(target, weight); @@ -181,7 +181,7 @@ public class AdjacencyMap<T> { * @return The new representation of this graph */ public Graph<T> toGraph() { - Graph<T> ret = new Graph<>(); + final Graph<T> ret = new Graph<>(); adjacency.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { @@ -198,10 +198,10 @@ public class AdjacencyMap<T> { * @param sink * The stream to convert to */ - public void toStream(OutputStream sink) { - if(sink == null) throw new NullPointerException("Output source must not be null"); + public void toStream(final OutputStream sink) { + if (sink == null) throw new NullPointerException("Output source must not be null"); - PrintStream outputPrinter = new PrintStream(sink); + final PrintStream outputPrinter = new PrintStream(sink); adjacency.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java index 37aff29..0152e3d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java @@ -29,10 +29,10 @@ public class Edge<T> { * @param distance * The distance between initial and terminal edge */ - public Edge(T initial, T terminal, int distance) { - if(initial == null) + public Edge(final T initial, final T terminal, final int distance) { + if (initial == null) throw new NullPointerException("Initial node must not be null"); - else if(terminal == null) throw new NullPointerException("Terminal node must not be null"); + else if (terminal == null) throw new NullPointerException("Terminal node must not be null"); this.source = initial; this.target = terminal; @@ -40,25 +40,25 @@ public class Edge<T> { } @Override - public boolean equals(Object obj) { - if(this == obj) + public boolean equals(final Object obj) { + if (this == obj) return true; - else if(obj == null) + else if (obj == null) return false; - else if(getClass() != obj.getClass()) + else if (getClass() != obj.getClass()) return false; else { - Edge<?> other = (Edge<?>) obj; + final Edge<?> other = (Edge<?>) obj; - if(distance != other.distance) + if (distance != other.distance) return false; - else if(source == null) { - if(other.source != null) return false; - } else if(!source.equals(other.source)) + else if (source == null) { + if (other.source != null) return false; + } else if (!source.equals(other.source)) return false; - else if(target == null) { - if(other.target != null) return false; - } else if(!target.equals(other.target)) return false; + else if (target == null) { + if (other.target != null) return false; + } else if (!target.equals(other.target)) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java index ff36b2b..280a7f5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java @@ -1,11 +1,5 @@ package bjc.utils.graph; -import bjc.utils.data.IHolder; -import bjc.utils.data.Identity; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.IMap; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -16,6 +10,12 @@ import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiPredicate; +import bjc.utils.data.IHolder; +import bjc.utils.data.Identity; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.IMap; + /** * A directed weighted graph, where the vertices have some arbitrary label * @@ -35,8 +35,8 @@ public class Graph<T> { * The list of edges to build from * @return A graph built from the provided edge-list */ - public static <E> Graph<E> fromEdgeList(List<Edge<E>> edges) { - Graph<E> g = new Graph<>(); + public static <E> Graph<E> fromEdgeList(final List<Edge<E>> edges) { + final Graph<E> g = new Graph<>(); edges.forEach(edge -> { g.addEdge(edge.getSource(), edge.getTarget(), edge.getDistance(), true); @@ -70,7 +70,7 @@ public class Graph<T> { * @param directed * Whether or not */ - public void addEdge(T source, T target, int distance, boolean directed) { + public void addEdge(final T source, final T target, final int distance, final boolean directed) { // Can't add edges with a null source or target if (source == null) throw new NullPointerException("The source vertex cannot be null"); @@ -105,7 +105,8 @@ public class Graph<T> { * @param action * The action to execute for matching edges */ - public void forAllEdgesMatchingAt(T source, BiPredicate<T, Integer> matcher, BiConsumer<T, Integer> action) { + public void forAllEdgesMatchingAt(final T source, final BiPredicate<T, Integer> matcher, + final BiConsumer<T, Integer> action) { if (matcher == null) throw new NullPointerException("Matcher must not be null"); else if (action == null) throw new NullPointerException("Action must not be null"); @@ -124,7 +125,7 @@ public class Graph<T> { * The vertex to use as a source * @return All of the edges with the specified vertex as a source */ - public IMap<T, Integer> getEdges(T source) { + public IMap<T, Integer> getEdges(final T source) { // Can't find edges for a null source if (source == null) throw new NullPointerException("The source cannot be null."); @@ -153,17 +154,17 @@ public class Graph<T> { */ public List<Edge<T>> getMinimumSpanningTree() { // Set of all of the currently available edges - Queue<Edge<T>> available = new PriorityQueue<>(10, + final Queue<Edge<T>> available = new PriorityQueue<>(10, (left, right) -> left.getDistance() - right.getDistance()); // The MST of the graph - List<Edge<T>> minimums = new ArrayList<>(); + final List<Edge<T>> minimums = new ArrayList<>(); // The set of all of the visited vertices. - Set<T> visited = new HashSet<>(); + final Set<T> visited = new HashSet<>(); // Start at the initial vertex and visit it - IHolder<T> source = new Identity<>(getInitial()); + final IHolder<T> source = new Identity<>(getInitial()); visited.add(source.getValue()); @@ -174,13 +175,13 @@ public class Graph<T> { forAllEdgesMatchingAt(source.getValue(), (target, weight) -> { return !visited.contains(target); }, (target, weight) -> { - T vert = source.unwrap(vertex -> vertex); + final T vert = source.unwrap(vertex -> vertex); available.add(new Edge<>(vert, target, weight)); }); // Get the edge with the minimum distance - IHolder<Edge<T>> minimum = new Identity<>(available.poll()); + final IHolder<Edge<T>> minimum = new Identity<>(available.poll()); // Only consider edges where we haven't visited the // target of @@ -228,7 +229,7 @@ public class Graph<T> { * @param target * The target vertex for the edge */ - public void removeEdge(T source, T target) { + public void removeEdge(final T source, final T target) { // Can't remove things w/ null vertices if (source == null) throw new NullPointerException("The source vertex cannot be null"); @@ -253,7 +254,7 @@ public class Graph<T> { * @return A adjacency map representing this graph */ public AdjacencyMap<T> toAdjacencyMap() { - AdjacencyMap<T> adjacency = new AdjacencyMap<>(backing.keyList()); + final AdjacencyMap<T> adjacency = new AdjacencyMap<>(backing.keyList()); backing.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java index 8662f4e..7c487eb 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -1,13 +1,13 @@ package bjc.utils.gui; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.io.File; import java.util.List; import javax.swing.filechooser.FileFilter; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * A file filter based on extensions. * @@ -20,7 +20,7 @@ public class ExtensionFileFilter extends FileFilter { /** * The list holding all filtered extensions */ - private IList<String> extensions; + private final IList<String> extensions; /** * Create a new filter only showing files with the specified extensions. @@ -28,7 +28,7 @@ public class ExtensionFileFilter extends FileFilter { * @param exts * The extensions to show in this filter. */ - public ExtensionFileFilter(List<String> exts) { + public ExtensionFileFilter(final List<String> exts) { extensions = new FunctionalList<>(exts); } @@ -38,13 +38,13 @@ public class ExtensionFileFilter extends FileFilter { * @param exts * The extensions to show in this filter. */ - public ExtensionFileFilter(String... exts) { + public ExtensionFileFilter(final String... exts) { extensions = new FunctionalList<>(exts); } @Override - public boolean accept(File pathname) { - if(pathname == null) throw new NullPointerException("Pathname must not be null"); + public boolean accept(final File pathname) { + if (pathname == null) throw new NullPointerException("Pathname must not be null"); return extensions.anyMatch(pathname.getName()::endsWith); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java index bb14327..59eb1c3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -1,7 +1,5 @@ package bjc.utils.gui; -import bjc.utils.gui.layout.VLayout; - import java.awt.Component; import java.awt.Frame; import java.util.function.Function; @@ -14,6 +12,8 @@ import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; +import bjc.utils.gui.layout.VLayout; + /** * Utility class for getting simple input from the user. * @@ -36,13 +36,14 @@ public class SimpleDialogs { * The upper integer bound to accept. * @return A int within the specified bounds. */ - public static int getBoundedInt(Component parent, String title, String prompt, int lowerBound, int upperBound) { + public static int getBoundedInt(final Component parent, final String title, final String prompt, + final int lowerBound, final int upperBound) { return getValue(parent, title, prompt, (strang) -> { try { - int value = Integer.parseInt(strang); + final int value = Integer.parseInt(strang); return value < upperBound && value > lowerBound; - } catch(NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -68,28 +69,29 @@ public class SimpleDialogs { * @return The choice the user picked, or null if they didn't pick one */ @SuppressWarnings("unchecked") - public static <E> E getChoice(Frame parent, String title, String question, E... choices) { - if(parent == null) + public static <E> E getChoice(final Frame parent, final String title, final String question, + final E... choices) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(question == null) throw new NullPointerException("Question must not be null"); + else if (question == null) throw new NullPointerException("Question must not be null"); - JDialog chooser = new JDialog(parent, title, true); + final JDialog chooser = new JDialog(parent, title, true); chooser.setLayout(new VLayout(2)); - JPanel questionPane = new JPanel(); + final JPanel questionPane = new JPanel(); - JLabel questionText = new JLabel(question); - JComboBox<E> questionChoices = new JComboBox<>(choices); + final JLabel questionText = new JLabel(question); + final JComboBox<E> questionChoices = new JComboBox<>(choices); questionPane.add(questionText); questionPane.add(questionChoices); - JPanel buttonPane = new JPanel(); + final JPanel buttonPane = new JPanel(); - JButton okButton = new JButton("Ok"); - JButton cancelButton = new JButton("Cancel"); + final JButton okButton = new JButton("Ok"); + final JButton cancelButton = new JButton("Cancel"); okButton.addActionListener((event) -> chooser.dispose()); cancelButton.addActionListener((event) -> chooser.dispose()); @@ -117,12 +119,12 @@ public class SimpleDialogs { * The prompt to tell the user what to enter. * @return A int. */ - public static int getInt(Component parent, String title, String prompt) { + public static int getInt(final Component parent, final String title, final String prompt) { return getValue(parent, title, prompt, strang -> { try { Integer.parseInt(strang); return true; - } catch(NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -142,12 +144,12 @@ public class SimpleDialogs { * The prompt to tell the user what to enter. * @return A string. */ - public static String getString(Component parent, String title, String prompt) { - if(parent == null) + public static String getString(final Component parent, final String title, final String prompt) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(prompt == null) throw new NullPointerException("Prompt must not be null"); + else if (prompt == null) throw new NullPointerException("Prompt must not be null"); return JOptionPane.showInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } @@ -170,15 +172,15 @@ public class SimpleDialogs { * The function to transform the string into a value. * @return The value parsed from a string. */ - public static <E> E getValue(Component parent, String title, String prompt, Predicate<String> validator, - Function<String, E> transformer) { - if(validator == null) + public static <E> E getValue(final Component parent, final String title, final String prompt, + final Predicate<String> validator, final Function<String, E> transformer) { + if (validator == null) throw new NullPointerException("Validator must not be null"); - else if(transformer == null) throw new NullPointerException("Transformer must not be null"); + else if (transformer == null) throw new NullPointerException("Transformer must not be null"); String input = getString(parent, title, prompt); - while(!validator.test(input)) { + while (!validator.test(input)) { showError(parent, "I/O Error", "Please enter a valid value"); input = getString(parent, title, prompt); @@ -198,7 +200,7 @@ public class SimpleDialogs { * The prompt to tell the user what to enter. * @return A whole number. */ - public static int getWhole(Component parent, String title, String prompt) { + public static int getWhole(final Component parent, final String title, final String prompt) { return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE); } @@ -213,14 +215,14 @@ public class SimpleDialogs { * The question to ask the user. * @return True if the user said yes, false otherwise. */ - public static boolean getYesNo(Component parent, String title, String question) { - if(parent == null) + public static boolean getYesNo(final Component parent, final String title, final String question) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(question == null) throw new NullPointerException("Question must not be null"); + else if (question == null) throw new NullPointerException("Question must not be null"); - int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); + final int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); return result == JOptionPane.YES_OPTION ? true : false; } @@ -235,12 +237,12 @@ public class SimpleDialogs { * @param message * The error to show the user. */ - public static void showError(Component parent, String title, String message) { - if(parent == null) + public static void showError(final Component parent, final String title, final String message) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(message == null) throw new NullPointerException("Error message must not be null"); + else if (message == null) throw new NullPointerException("Error message must not be null"); JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -255,12 +257,12 @@ public class SimpleDialogs { * @param message * Show the message for this dialog */ - public static void showMessage(Component parent, String title, String message) { - if(parent == null) + public static void showMessage(final Component parent, final String title, final String message) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(message == null) throw new NullPointerException("Message must not be null"); + else if (message == null) throw new NullPointerException("Message must not be null"); JOptionPane.showMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java index cd7c180..7da0bd8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -1,12 +1,12 @@ package bjc.utils.gui; -import bjc.utils.exceptions.FileNotChosenException; - import java.awt.Component; import java.io.File; import javax.swing.JFileChooser; +import bjc.utils.exceptions.FileNotChosenException; + /** * Utility class for easily prompting user for files. * @@ -16,19 +16,19 @@ import javax.swing.JFileChooser; * */ public class SimpleFileChooser { - private static File doOpenFile(Component parent, String title, JFileChooser files) { - if(title == null) throw new NullPointerException("Title must not be null"); + private static File doOpenFile(final Component parent, final String title, final JFileChooser files) { + if (title == null) throw new NullPointerException("Title must not be null"); files.setDialogTitle(title); boolean success = false; - while(!success) { + while (!success) { try { maybeDoOpenFile(parent, files); success = true; - } catch(FileNotChosenException fncx) { + } catch (final FileNotChosenException fncx) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open"); } @@ -37,25 +37,23 @@ public class SimpleFileChooser { return files.getSelectedFile(); } - private static File doSaveFile(Component parent, String title, JFileChooser files) { - if(title == null) throw new NullPointerException("Title must not be null"); + private static File doSaveFile(final Component parent, final String title, final JFileChooser files) { + if (title == null) throw new NullPointerException("Title must not be null"); files.setDialogTitle(title); - boolean success = false; + final boolean success = false; - while(!success) { + while (!success) { try { maybeDoSaveFile(parent, files); return files.getSelectedFile(); - } catch(FileNotChosenException fncex) { + } catch (final FileNotChosenException fncex) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to"); } } - - return files.getSelectedFile(); } /** @@ -68,8 +66,8 @@ public class SimpleFileChooser { * The title of the dialog to prompt with. * @return The file the user has chosen. */ - public static File getOpenFile(Component parent, String title) { - JFileChooser files = new JFileChooser(); + public static File getOpenFile(final Component parent, final String title) { + final JFileChooser files = new JFileChooser(); return doOpenFile(parent, title, files); } @@ -86,8 +84,8 @@ public class SimpleFileChooser { * The list of file extensions the file should have. * @return The file the user has chosen. */ - public static File getOpenFile(Component parent, String title, String... extensions) { - JFileChooser files = new JFileChooser(); + public static File getOpenFile(final Component parent, final String title, final String... extensions) { + final JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); @@ -103,8 +101,8 @@ public class SimpleFileChooser { * The title of the dialog to prompt with. * @return The file the user chose. */ - public static File getSaveFile(Component parent, String title) { - JFileChooser files = new JFileChooser(); + public static File getSaveFile(final Component parent, final String title) { + final JFileChooser files = new JFileChooser(); return doSaveFile(parent, title, files); } @@ -120,32 +118,34 @@ public class SimpleFileChooser { * The extensions of the files the user can choose. * @return The file the user chose. */ - public static File getSaveFile(Component parent, String title, String... extensions) { - JFileChooser files = new JFileChooser(); + public static File getSaveFile(final Component parent, final String title, final String... extensions) { + final JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); return doSaveFile(parent, title, files); } - private static void maybeDoOpenFile(Component parent, JFileChooser files) throws FileNotChosenException { - if(parent == null) + private static void maybeDoOpenFile(final Component parent, final JFileChooser files) + throws FileNotChosenException { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(files == null) throw new NullPointerException("File chooser must not be null"); + else if (files == null) throw new NullPointerException("File chooser must not be null"); - int result = files.showSaveDialog(parent); + final int result = files.showSaveDialog(parent); - if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); + if (result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); } - private static void maybeDoSaveFile(Component parent, JFileChooser files) throws FileNotChosenException { - if(parent == null) + private static void maybeDoSaveFile(final Component parent, final JFileChooser files) + throws FileNotChosenException { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(files == null) throw new NullPointerException("File chooser must not be null"); + else if (files == null) throw new NullPointerException("File chooser must not be null"); - int result = files.showSaveDialog(parent); + final int result = files.showSaveDialog(parent); - if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); + if (result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); } /** @@ -157,15 +157,15 @@ public class SimpleFileChooser { * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ - public static File maybeOpenFile(Component parent, String title) { - if(title == null) throw new NullPointerException("Title must not be null"); + public static File maybeOpenFile(final Component parent, final String title) { + if (title == null) throw new NullPointerException("Title must not be null"); - JFileChooser files = new JFileChooser(); + final JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoOpenFile(parent, files); - } catch(FileNotChosenException fncex) { + } catch (final FileNotChosenException fncex) { // We don't care about specifics } @@ -181,15 +181,15 @@ public class SimpleFileChooser { * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ - public static File maybeSaveFile(Component parent, String title) { - if(title == null) throw new NullPointerException("Title must not be null"); + public static File maybeSaveFile(final Component parent, final String title) { + if (title == null) throw new NullPointerException("Title must not be null"); - JFileChooser files = new JFileChooser(); + final JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoSaveFile(parent, files); - } catch(FileNotChosenException fncex) { + } catch (final FileNotChosenException fncex) { // We don't care about specifics } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java index d7bb700..5237557 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java @@ -30,13 +30,14 @@ public class SimpleInternalDialogs { * The upper integer bound to accept. * @return A int within the specified bounds. */ - public static int getBoundedInt(Component parent, String title, String prompt, int lowerBound, int upperBound) { + public static int getBoundedInt(final Component parent, final String title, final String prompt, + final int lowerBound, final int upperBound) { return getValue(parent, title, prompt, (strang) -> { try { - int value = Integer.parseInt(strang); + final int value = Integer.parseInt(strang); return value < upperBound && value > lowerBound; - } catch(NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -56,12 +57,12 @@ public class SimpleInternalDialogs { * The prompt to tell the user what to enter. * @return A int. */ - public static int getInt(Component parent, String title, String prompt) { + public static int getInt(final Component parent, final String title, final String prompt) { return getValue(parent, title, prompt, strang -> { try { Integer.parseInt(strang); return true; - } catch(NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -81,12 +82,12 @@ public class SimpleInternalDialogs { * The prompt to tell the user what to enter. * @return A string. */ - public static String getString(Component parent, String title, String prompt) { - if(parent == null) + public static String getString(final Component parent, final String title, final String prompt) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(prompt == null) throw new NullPointerException("Prompt must not be null"); + else if (prompt == null) throw new NullPointerException("Prompt must not be null"); return JOptionPane.showInternalInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } @@ -109,15 +110,15 @@ public class SimpleInternalDialogs { * The function to transform the string into a value. * @return The value parsed from a string. */ - public static <E> E getValue(Component parent, String title, String prompt, Predicate<String> validator, - Function<String, E> transformer) { - if(validator == null) + public static <E> E getValue(final Component parent, final String title, final String prompt, + final Predicate<String> validator, final Function<String, E> transformer) { + if (validator == null) throw new NullPointerException("Validator must not be null"); - else if(transformer == null) throw new NullPointerException("Transformer must not be null"); + else if (transformer == null) throw new NullPointerException("Transformer must not be null"); String strang = getString(parent, title, prompt); - while(!validator.test(strang)) { + while (!validator.test(strang)) { showError(parent, "I/O Error", "Please enter a valid value"); strang = getString(parent, title, prompt); @@ -137,7 +138,7 @@ public class SimpleInternalDialogs { * The prompt to tell the user what to enter. * @return A whole number. */ - public static int getWhole(Component parent, String title, String prompt) { + public static int getWhole(final Component parent, final String title, final String prompt) { return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE); } @@ -152,14 +153,15 @@ public class SimpleInternalDialogs { * The question to ask the user. * @return True if the user said yes, false otherwise. */ - public static boolean getYesNo(Component parent, String title, String question) { - if(parent == null) + public static boolean getYesNo(final Component parent, final String title, final String question) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(question == null) throw new NullPointerException("Question must not be null"); + else if (question == null) throw new NullPointerException("Question must not be null"); - int result = JOptionPane.showInternalConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); + final int result = JOptionPane.showInternalConfirmDialog(parent, question, title, + JOptionPane.YES_NO_OPTION); return result == JOptionPane.YES_OPTION ? true : false; } @@ -174,12 +176,12 @@ public class SimpleInternalDialogs { * @param message * The error to show the user. */ - public static void showError(Component parent, String title, String message) { - if(parent == null) + public static void showError(final Component parent, final String title, final String message) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(message == null) throw new NullPointerException("Error message must not be null"); + else if (message == null) throw new NullPointerException("Error message must not be null"); JOptionPane.showInternalMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -194,12 +196,12 @@ public class SimpleInternalDialogs { * @param message * Show the message for this dialog */ - public static void showMessage(Component parent, String title, String message) { - if(parent == null) + public static void showMessage(final Component parent, final String title, final String message) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) + else if (title == null) throw new NullPointerException("Title must not be null"); - else if(message == null) throw new NullPointerException("Message must not be null"); + else if (message == null) throw new NullPointerException("Message must not be null"); JOptionPane.showInternalMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java index 9fdf18f..afb498e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java @@ -24,7 +24,7 @@ public class SimpleInternalFrame extends JInternalFrame { * @param title * The title of the internal frame */ - public SimpleInternalFrame(String title) { + public SimpleInternalFrame(final String title) { super(title); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java index e469f2f..411d0db 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java @@ -21,8 +21,8 @@ public class SimpleJList { * The list to populate the JList with. * @return A JList populated with the elements from ls. */ - public static <E> JList<E> buildFromList(Iterable<E> source) { - if(source == null) throw new NullPointerException("Source must not be null"); + public static <E> JList<E> buildFromList(final Iterable<E> source) { + if (source == null) throw new NullPointerException("Source must not be null"); return new JList<>(buildModel(source)); } @@ -37,10 +37,10 @@ public class SimpleJList { * The list to fill the list model from. * @return A list model populated with the elements from ls. */ - public static <E> ListModel<E> buildModel(Iterable<E> source) { - if(source == null) throw new NullPointerException("Source must not be null"); + public static <E> ListModel<E> buildModel(final Iterable<E> source) { + if (source == null) throw new NullPointerException("Source must not be null"); - DefaultListModel<E> defaultModel = new DefaultListModel<>(); + final DefaultListModel<E> defaultModel = new DefaultListModel<>(); source.forEach(defaultModel::addElement); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java index 723fad0..9b01507 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java @@ -19,7 +19,7 @@ public class SimpleTitledBorder extends TitledBorder { * @param title * The title for the border. */ - public SimpleTitledBorder(String title) { + public SimpleTitledBorder(final String title) { super(new EtchedBorder(), title); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java index c63abfd..fbc58ed 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java @@ -12,7 +12,7 @@ import javax.swing.JTextArea; * @author Levente S\u00e1ntha (lsantha@users.sourceforge.net) */ public class TextAreaOutputStream extends OutputStream { - private JTextArea textArea; + private final JTextArea textArea; /** * Create a new output stream attached to a textarea @@ -20,15 +20,15 @@ public class TextAreaOutputStream extends OutputStream { * @param console * The textarea to write to */ - public TextAreaOutputStream(JTextArea console) { + public TextAreaOutputStream(final JTextArea console) { this.textArea = console; } @Override - public void write(int b) throws IOException { + public void write(final int b) throws IOException { textArea.append("" + (char) b); - if(b == '\n') { + if (b == '\n') { textArea.repaint(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java index 68978e7..eb60ae2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java @@ -1,12 +1,12 @@ package bjc.utils.gui.awt; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.io.File; import java.io.FilenameFilter; import java.util.List; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * Filter a set of filenames by extension. * @@ -19,7 +19,7 @@ public class ExtensionFileFilter implements FilenameFilter { /** * The list of extensions to filter */ - private IList<String> extensions; + private final IList<String> extensions; /** * Create a new filter only showing files with the specified extensions. @@ -27,8 +27,8 @@ public class ExtensionFileFilter implements FilenameFilter { * @param exts * The extensions to show in this filter. */ - public ExtensionFileFilter(List<String> exts) { - if(exts == null) throw new NullPointerException("Extensions must not be null"); + public ExtensionFileFilter(final List<String> exts) { + if (exts == null) throw new NullPointerException("Extensions must not be null"); extensions = new FunctionalList<>(exts); } @@ -39,12 +39,12 @@ public class ExtensionFileFilter implements FilenameFilter { * @param exts * The extensions to show in this filter. */ - public ExtensionFileFilter(String... exts) { + public ExtensionFileFilter(final String... exts) { extensions = new FunctionalList<>(exts); } @Override - public boolean accept(File directory, String name) { + public boolean accept(final File directory, final String name) { return extensions.anyMatch(name::endsWith); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java index 47f76b8..77a4a59 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java @@ -1,12 +1,12 @@ package bjc.utils.gui.awt; -import bjc.utils.gui.SimpleDialogs; - import java.awt.FileDialog; import java.awt.Frame; import java.io.File; import java.io.FilenameFilter; +import bjc.utils.gui.SimpleDialogs; + /** * A simple way to get the user to pick a file * @@ -25,7 +25,7 @@ public class SimpleFileDialog { * The title of the file picker * @return The file the user picked */ - public static File getOpenFile(Frame parent, String title) { + public static File getOpenFile(final Frame parent, final String title) { return getOpenFile(parent, title, (String[]) null); } @@ -40,21 +40,21 @@ public class SimpleFileDialog { * The extensions to accept as valid * @return The file the user picked */ - public static File getOpenFile(Frame parent, String title, String... extensions) { - if(parent == null) + public static File getOpenFile(final Frame parent, final String title, final String... extensions) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) throw new NullPointerException("Title must not be null"); + else if (title == null) throw new NullPointerException("Title must not be null"); - FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); + final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); - if(extensions != null) { - FilenameFilter filter = new ExtensionFileFilter(extensions); + if (extensions != null) { + final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } chooser.setVisible(true); - while(chooser.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -73,22 +73,22 @@ public class SimpleFileDialog { * The extensions to accept as valid * @return The file the user picked */ - public static File[] getOpenFiles(Frame parent, String title, String... extensions) { - if(parent == null) + public static File[] getOpenFiles(final Frame parent, final String title, final String... extensions) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) throw new NullPointerException("Title must not be null"); + else if (title == null) throw new NullPointerException("Title must not be null"); - FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); + final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); - if(extensions != null) { - FilenameFilter filter = new ExtensionFileFilter(extensions); + if (extensions != null) { + final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } chooser.setMultipleMode(true); chooser.setVisible(true); - while(chooser.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -105,7 +105,7 @@ public class SimpleFileDialog { * The title of the file picker * @return The file the user picked */ - public static File getSaveFile(Frame parent, String title) { + public static File getSaveFile(final Frame parent, final String title) { return getSaveFile(parent, title, (String[]) null); } @@ -120,21 +120,21 @@ public class SimpleFileDialog { * The extensions to accept as valid * @return The file the user picked */ - public static File getSaveFile(Frame parent, String title, String... extensions) { - if(parent == null) + public static File getSaveFile(final Frame parent, final String title, final String... extensions) { + if (parent == null) throw new NullPointerException("Parent must not be null"); - else if(title == null) throw new NullPointerException("Title must not be null"); + else if (title == null) throw new NullPointerException("Title must not be null"); - FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE); + final FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE); - if(extensions != null) { - FilenameFilter filter = new ExtensionFileFilter(extensions); + if (extensions != null) { + final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } chooser.setVisible(true); - while(chooser.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to."); chooser.setVisible(true); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java index be2116a..4ed1661 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java @@ -19,7 +19,7 @@ public class HLayout extends GridLayout { * @param columns * The number of columns in this layout. */ - public HLayout(int columns) { + public HLayout(final int columns) { super(1, columns); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java index 9c5a563..6993365 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java @@ -19,7 +19,7 @@ public class VLayout extends GridLayout { * @param rows * The number of rows. */ - public VLayout(int rows) { + public VLayout(final int rows) { super(rows, 1); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java index 6e6be02..4f71d38 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java @@ -1,9 +1,5 @@ package bjc.utils.gui.panels; -import bjc.utils.funcdata.IList; -import bjc.utils.gui.layout.AutosizeLayout; -import bjc.utils.gui.layout.HLayout; - import java.awt.BorderLayout; import javax.swing.DefaultListModel; @@ -13,6 +9,10 @@ import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; +import bjc.utils.funcdata.IList; +import bjc.utils.gui.layout.AutosizeLayout; +import bjc.utils.gui.layout.HLayout; + /** * A panel that allows you to select choices from a dropdown list * @@ -34,27 +34,27 @@ public class DropdownListPanel extends JPanel { * @param choices * The items to choose from */ - public <T> DropdownListPanel(String type, DefaultListModel<T> model, IList<T> choices) { + public <T> DropdownListPanel(final String type, final DefaultListModel<T> model, final IList<T> choices) { setLayout(new AutosizeLayout()); - JPanel itemInputPanel = new JPanel(); + final JPanel itemInputPanel = new JPanel(); itemInputPanel.setLayout(new BorderLayout()); - JPanel addItemPanel = new JPanel(); + final JPanel addItemPanel = new JPanel(); addItemPanel.setLayout(new HLayout(2)); - JComboBox<T> addItemBox = new JComboBox<>(); + final JComboBox<T> addItemBox = new JComboBox<>(); choices.forEach(addItemBox::addItem); - JButton addItemButton = new JButton("Add " + type); + final JButton addItemButton = new JButton("Add " + type); addItemPanel.add(addItemBox); addItemPanel.add(addItemButton); - JList<T> itemList = new JList<>(model); + final JList<T> itemList = new JList<>(model); itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - JButton removeItemButton = new JButton("Remove " + type); + final JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { model.addElement(addItemBox.getItemAt(addItemBox.getSelectedIndex())); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java index 877f308..2cecf0c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java @@ -1,7 +1,5 @@ package bjc.utils.gui.panels; -import bjc.utils.gui.layout.HLayout; - import java.util.function.Consumer; import javax.swing.JFormattedTextField; @@ -9,6 +7,8 @@ import javax.swing.JFormattedTextField.AbstractFormatter; import javax.swing.JLabel; import javax.swing.JPanel; +import bjc.utils.gui.layout.HLayout; + /** * A simple panel allowing for input of a single formatted value * @@ -20,7 +20,7 @@ import javax.swing.JPanel; public class FormattedInputPanel<InputVal> extends JPanel { private static final long serialVersionUID = 5232016563558588031L; - private JFormattedTextField field; + private final JFormattedTextField field; /** * Create a new formatted input panel @@ -35,10 +35,11 @@ public class FormattedInputPanel<InputVal> extends JPanel { * The action to call whenever the value changes */ @SuppressWarnings("unchecked") - public FormattedInputPanel(String label, int length, AbstractFormatter formatter, Consumer<InputVal> reciever) { + public FormattedInputPanel(final String label, final int length, final AbstractFormatter formatter, + final Consumer<InputVal> reciever) { setLayout(new HLayout(2)); - JLabel lab = new JLabel(label); + final JLabel lab = new JLabel(label); field = new JFormattedTextField(formatter); field.setColumns(length); @@ -59,7 +60,7 @@ public class FormattedInputPanel<InputVal> extends JPanel { * @param value * The value to set the panel to */ - public void resetValues(InputVal value) { + public void resetValues(final InputVal value) { field.setValue(value); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java index 054eb38..653dace 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java @@ -1,12 +1,12 @@ package bjc.utils.gui.panels; -import bjc.utils.data.IHolder; -import bjc.utils.gui.layout.HLayout; - import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; +import bjc.utils.data.IHolder; +import bjc.utils.gui.layout.HLayout; + /** * A panel that outputs a value bound to a {@link IHolder} * @@ -16,10 +16,10 @@ import javax.swing.Timer; public class HolderOutputPanel extends JPanel { private static final long serialVersionUID = 166573313903782080L; - private Timer updater; - private JLabel value; - private int nDelay; - private IHolder<String> val; + private Timer updater; + private final JLabel value; + private final int nDelay; + private final IHolder<String> val; /** * Create a new display panel, backed by a holder @@ -31,13 +31,13 @@ public class HolderOutputPanel extends JPanel { * @param nDelay * The delay in ms between value updates */ - public HolderOutputPanel(String lab, IHolder<String> valueHolder, int nDelay) { + public HolderOutputPanel(final String lab, final IHolder<String> valueHolder, final int nDelay) { this.val = valueHolder; this.nDelay = nDelay; setLayout(new HLayout(2)); - JLabel label = new JLabel(lab); + final JLabel label = new JLabel(lab); value = new JLabel("(stopped)"); updater = new Timer(nDelay, (event) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java index 8f68571..cca73d5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java @@ -1,10 +1,5 @@ package bjc.utils.gui.panels; -import bjc.utils.funcdata.IList; -import bjc.utils.gui.SimpleJList; -import bjc.utils.gui.layout.HLayout; -import bjc.utils.gui.layout.VLayout; - import java.util.function.Consumer; import java.util.function.Supplier; @@ -14,6 +9,11 @@ import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; +import bjc.utils.funcdata.IList; +import bjc.utils.gui.SimpleJList; +import bjc.utils.gui.layout.HLayout; +import bjc.utils.gui.layout.VLayout; + /** * A panel that has a list of objects and ways of manipulating that list * @@ -36,7 +36,7 @@ public class ListParameterPanel<E> extends JPanel { * @param remove * The action that removes items */ - public ListParameterPanel(Supplier<E> add, Consumer<E> edit, Consumer<E> remove) { + public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove) { this(add, edit, remove, null); } @@ -52,12 +52,13 @@ public class ListParameterPanel<E> extends JPanel { * @param defaults * The default values to put in the list */ - public ListParameterPanel(Supplier<E> add, Consumer<E> edit, Consumer<E> remove, IList<E> defaults) { + public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove, + final IList<E> defaults) { setLayout(new VLayout(2)); JList<E> list; - if(defaults != null) { + if (defaults != null) { list = SimpleJList.buildFromList(defaults.toIterable()); } else { list = new JList<>(new DefaultListModel<>()); @@ -65,19 +66,19 @@ public class ListParameterPanel<E> extends JPanel { list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - JPanel buttonPanel = new JPanel(); + final JPanel buttonPanel = new JPanel(); int numButtons = 0; - if(add != null) { + if (add != null) { numButtons++; } - if(edit != null) { + if (edit != null) { numButtons++; } - if(remove != null) { + if (remove != null) { numButtons++; } @@ -85,10 +86,10 @@ public class ListParameterPanel<E> extends JPanel { JButton addParam = null; - if(add != null) { + if (add != null) { addParam = new JButton("Add..."); addParam.addActionListener((event) -> { - DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); + final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); model.addElement(add.get()); }); @@ -96,7 +97,7 @@ public class ListParameterPanel<E> extends JPanel { JButton editParam = null; - if(edit != null) { + if (edit != null) { editParam = new JButton("Edit..."); editParam.addActionListener((event) -> { edit.accept(list.getSelectedValue()); @@ -105,24 +106,24 @@ public class ListParameterPanel<E> extends JPanel { JButton removeParam = null; - if(remove != null) { + if (remove != null) { removeParam = new JButton("Remove..."); removeParam.addActionListener((event) -> { - DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); + final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); remove.accept(model.remove(list.getSelectedIndex())); }); } - if(add != null) { + if (add != null) { buttonPanel.add(addParam); } - if(edit != null) { + if (edit != null) { buttonPanel.add(editParam); } - if(remove != null) { + if (remove != null) { buttonPanel.add(removeParam); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java index d0881c5..65c533d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java @@ -28,12 +28,12 @@ public class SimpleInputPanel extends JPanel { * @param columns * The number of columns of text input to take */ - public SimpleInputPanel(String label, int columns) { + public SimpleInputPanel(final String label, final int columns) { setLayout(new BorderLayout()); - JLabel inputLabel = new JLabel(label); + final JLabel inputLabel = new JLabel(label); - if(columns < 1) { + if (columns < 1) { inputValue = new JTextField(); } else { inputValue = new JTextField(columns); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java index b4fcfe1..edc1797 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java @@ -1,8 +1,5 @@ package bjc.utils.gui.panels; -import bjc.utils.gui.layout.AutosizeLayout; -import bjc.utils.gui.layout.HLayout; - import java.awt.BorderLayout; import java.util.function.Consumer; import java.util.function.Predicate; @@ -15,6 +12,9 @@ import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; +import bjc.utils.gui.layout.AutosizeLayout; +import bjc.utils.gui.layout.HLayout; + /** * A simple list of strings * @@ -24,11 +24,11 @@ import javax.swing.ListSelectionModel; public class SimpleListPanel extends JPanel { private static final long serialVersionUID = 2719963952350133541L; - private static void addItem(DefaultListModel<String> model, Predicate<String> verifier, - Consumer<String> onFailure, JTextField addItemField) { - String potentialItem = addItemField.getText(); + private static void addItem(final DefaultListModel<String> model, final Predicate<String> verifier, + final Consumer<String> onFailure, final JTextField addItemField) { + final String potentialItem = addItemField.getText(); - if(verifier == null || verifier.test(potentialItem)) { + if (verifier == null || verifier.test(potentialItem)) { model.addElement(potentialItem); } else { onFailure.accept(potentialItem); @@ -49,28 +49,28 @@ public class SimpleListPanel extends JPanel { * @param onFailure * The function to call when an item doesn't verify */ - public SimpleListPanel(String type, DefaultListModel<String> model, Predicate<String> verifier, - Consumer<String> onFailure) { + public SimpleListPanel(final String type, final DefaultListModel<String> model, + final Predicate<String> verifier, final Consumer<String> onFailure) { setLayout(new AutosizeLayout()); - JPanel itemInputPanel = new JPanel(); + final JPanel itemInputPanel = new JPanel(); itemInputPanel.setLayout(new BorderLayout()); - JPanel addItemPanel = new JPanel(); + final JPanel addItemPanel = new JPanel(); addItemPanel.setLayout(new HLayout(2)); - JTextField addItemField = new JTextField(255); - JButton addItemButton = new JButton("Add " + type); + final JTextField addItemField = new JTextField(255); + final JButton addItemButton = new JButton("Add " + type); addItemPanel.add(addItemField); addItemPanel.add(addItemButton); - JList<String> itemList = new JList<>(model); + final JList<String> itemList = new JList<>(model); itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - JScrollPane listScroller = new JScrollPane(itemList); + final JScrollPane listScroller = new JScrollPane(itemList); - JButton removeItemButton = new JButton("Remove " + type); + final JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { addItem(model, verifier, onFailure, addItemField); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java index 2b48adf..6106182 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java @@ -29,10 +29,10 @@ public class SimpleSpinnerPanel extends JPanel { * @param model * The model to attach to the spinner */ - public SimpleSpinnerPanel(String label, SpinnerModel model) { + public SimpleSpinnerPanel(final String label, final SpinnerModel model) { setLayout(new BorderLayout()); - JLabel inputLabel = new JLabel(label); + final JLabel inputLabel = new JLabel(label); inputValue = new JSpinner(model); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java index 71eaf33..e6a6da4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java @@ -1,7 +1,5 @@ package bjc.utils.gui.panels; -import bjc.utils.gui.layout.HLayout; - import java.text.ParseException; import java.util.function.Consumer; @@ -10,6 +8,8 @@ import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; +import bjc.utils.gui.layout.HLayout; + /** * A simple input panel for a slider-controlled value and a manual-input field * for setting the slider @@ -21,12 +21,12 @@ public class SliderInputPanel extends JPanel { private final class NumberFormatter extends JFormattedTextField.AbstractFormatter { private static final long serialVersionUID = -4448291795913908270L; - private int minValue; - private int maxValue; + private final int minValue; + private final int maxValue; - private int initValue; + private final int initValue; - public NumberFormatter(SliderSettings settings) { + public NumberFormatter(final SliderSettings settings) { minValue = settings.minValue; maxValue = settings.maxValue; @@ -34,18 +34,17 @@ public class SliderInputPanel extends JPanel { } @Override - public Object stringToValue(String text) throws ParseException { + public Object stringToValue(final String text) throws ParseException { try { - int val = Integer.parseInt(text); + final int val = Integer.parseInt(text); - if(val < minValue) + if (val < minValue) throw new ParseException("Value must be greater than " + minValue, 0); - else if(val > maxValue) + else if (val > maxValue) throw new ParseException("Value must be smaller than " + maxValue, 0); - else - return val; - } catch(NumberFormatException nfex) { - ParseException pex = new ParseException("Value must be a valid integer", 0); + else return val; + } catch (final NumberFormatException nfex) { + final ParseException pex = new ParseException("Value must be a valid integer", 0); pex.initCause(nfex); @@ -54,8 +53,8 @@ public class SliderInputPanel extends JPanel { } @Override - public String valueToString(Object value) throws ParseException { - if(value == null) return Integer.toString(initValue); + public String valueToString(final Object value) throws ParseException { + if (value == null) return Integer.toString(initValue); return Integer.toString((Integer) value); } @@ -91,7 +90,7 @@ public class SliderInputPanel extends JPanel { * @param max * The maximum value of the slider */ - public SliderSettings(int min, int max) { + public SliderSettings(final int min, final int max) { this(min, max, (min + max) / 2); } @@ -105,7 +104,7 @@ public class SliderInputPanel extends JPanel { * @param init * Th initial slider value */ - public SliderSettings(int min, int max, int init) { + public SliderSettings(final int min, final int max, final int init) { minValue = min; maxValue = max; @@ -113,9 +112,9 @@ public class SliderInputPanel extends JPanel { } } - private static final long serialVersionUID = 2956394160569961404L; - private JSlider slider; - private JFormattedTextField field; + private static final long serialVersionUID = 2956394160569961404L; + private final JSlider slider; + private final JFormattedTextField field; /** * Create a new slider input panel @@ -131,11 +130,11 @@ public class SliderInputPanel extends JPanel { * @param action * The action to execute for a given value */ - public SliderInputPanel(String lab, SliderSettings settings, int majorTick, int minorTick, - Consumer<Integer> action) { + public SliderInputPanel(final String lab, final SliderSettings settings, final int majorTick, + final int minorTick, final Consumer<Integer> action) { setLayout(new HLayout(3)); - JLabel label = new JLabel(lab); + final JLabel label = new JLabel(lab); slider = new JSlider(settings.minValue, settings.maxValue, settings.initValue); field = new JFormattedTextField(new NumberFormatter(settings)); @@ -146,10 +145,10 @@ public class SliderInputPanel extends JPanel { slider.setPaintLabels(true); slider.addChangeListener((event) -> { - if(slider.getValueIsAdjusting()) { + if (slider.getValueIsAdjusting()) { // Do nothing } else { - int val = slider.getValue(); + final int val = slider.getValue(); field.setValue(val); @@ -160,9 +159,9 @@ public class SliderInputPanel extends JPanel { field.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT); field.setColumns(15); field.addPropertyChangeListener("value", (event) -> { - Object value = field.getValue(); + final Object value = field.getValue(); - if(value == null) { + if (value == null) { // Do nothing } else { slider.setValue((Integer) value); @@ -180,7 +179,7 @@ public class SliderInputPanel extends JPanel { * @param value * The value to reset the fields to */ - public void resetValues(int value) { + public void resetValues(final int value) { slider.setValue(value); field.setValue(value); diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/Prompter.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/Prompter.java index eed53ae..a6ec4c0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/Prompter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/Prompter.java @@ -1,30 +1,30 @@ package bjc.utils.ioutils; -import bjc.utils.ioutils.blocks.TriggeredBlockReader; - import java.io.PrintStream; +import bjc.utils.ioutils.blocks.TriggeredBlockReader; + /** * A runnable for use with {@link TriggeredBlockReader} to prompt the user for * input. - * + * * @author bjculkin * */ public final class Prompter implements Runnable { - private String promt; - private PrintStream printer; + private String promt; + private final PrintStream printer; /** * Create a new prompter using the specified prompt. - * + * * @param prompt * The prompt to present. - * + * * @param output * The stream to print the prompt on. */ - public Prompter(String prompt, PrintStream output) { + public Prompter(final String prompt, final PrintStream output) { promt = prompt; printer = output; @@ -32,11 +32,11 @@ public final class Prompter implements Runnable { /** * Set the prompt this prompter uses. - * + * * @param prompt * The prompt this prompter uses. */ - public void setPrompt(String prompt) { + public void setPrompt(final String prompt) { promt = prompt; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RegexStringEditor.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RegexStringEditor.java index 4f66a99..ee1e2ea 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RegexStringEditor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RegexStringEditor.java @@ -1,19 +1,19 @@ package bjc.utils.ioutils; +import java.util.function.BiFunction; +import java.util.function.UnaryOperator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import bjc.utils.data.Toggle; import bjc.utils.data.ValueToggle; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import bjc.utils.functypes.ID; -import java.util.function.BiFunction; -import java.util.function.UnaryOperator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * Editor methods for strings based off the command language for the Sam editor. - * + * * @author EVE * */ @@ -23,65 +23,66 @@ public class RegexStringEditor { /** * Replace every occurrence of the pattern with the result of applying * the action to the string matched by the pattern. - * + * * @param input * The input string to process. - * + * * @param patt * The pattern to match the string against. - * + * * @param action * The action to transform matches with. - * + * * @return The string, with matches replaced with the action. */ - public static String onOccurances(String input, Pattern patt, UnaryOperator<String> action) { + public static String onOccurances(final String input, final Pattern patt, final UnaryOperator<String> action) { return reduceOccurances(input, patt, SID, action); } /** * Replace every occurrence between the patterns with the result of * applying the action to the strings between the patterns. - * + * * @param input * The input string to process. - * + * * @param patt * The pattern to match the string against. - * + * * @param action * The action to transform matches with. - * + * * @return The string, with strings between the matches replaced with * the action. */ - public static String betweenOccurances(String input, Pattern patt, UnaryOperator<String> action) { + public static String betweenOccurances(final String input, final Pattern patt, + final UnaryOperator<String> action) { return reduceOccurances(input, patt, action, SID); } /** * Execute actions between and on matches of a regular expression. - * + * * @param input * The input string. - * + * * @param rPatt * The pattern to match against the string. - * + * * @param betweenAction * The function to execute between matches of the string. - * + * * @param onAction * The function to execute on matches of the string. - * + * * @return The string, with both actions applied. */ - public static String reduceOccurances(String input, Pattern rPatt, UnaryOperator<String> betweenAction, - UnaryOperator<String> onAction) { - IList<String> occurances = listOccurances(input, rPatt); + public static String reduceOccurances(final String input, final Pattern rPatt, + final UnaryOperator<String> betweenAction, final UnaryOperator<String> onAction) { + final IList<String> occurances = listOccurances(input, rPatt); - Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction); - BiFunction<String, StringBuilder, StringBuilder> reducer = (strang, state) -> { + final Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction); + final BiFunction<String, StringBuilder, StringBuilder> reducer = (strang, state) -> { return state.append(actions.get().apply(strang)); }; @@ -90,50 +91,50 @@ public class RegexStringEditor { /** * Execute actions between and on matches of a regular expression. - * + * * @param input * The input string. - * + * * @param rPatt * The pattern to match against the string. - * + * * @param betweenAction * The function to execute between matches of the string. - * + * * @param onAction * The function to execute on matches of the string. - * + * * @return The string, with both actions applied. */ - public static IList<String> mapOccurances(String input, Pattern rPatt, UnaryOperator<String> betweenAction, - UnaryOperator<String> onAction) { - IList<String> occurances = listOccurances(input, rPatt); - Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction); + public static IList<String> mapOccurances(final String input, final Pattern rPatt, + final UnaryOperator<String> betweenAction, final UnaryOperator<String> onAction) { + final IList<String> occurances = listOccurances(input, rPatt); + final Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction); return occurances.map(strang -> actions.get().apply(strang)); } /** * Separate a string into match/non-match segments. - * + * * @param input * The string to separate. - * + * * @param rPatt * The pattern to use for separation. - * + * * @return The string, as a list of match/non-match segments, * starting/ending with a non-match segment. */ - public static IList<String> listOccurances(String input, Pattern rPatt) { - IList<String> res = new FunctionalList<>(); + public static IList<String> listOccurances(final String input, final Pattern rPatt) { + final IList<String> res = new FunctionalList<>(); - Matcher matcher = rPatt.matcher(input); + final Matcher matcher = rPatt.matcher(input); StringBuffer work = new StringBuffer(); - while(matcher.find()) { - String match = matcher.group(); + while (matcher.find()) { + final String match = matcher.group(); matcher.appendReplacement(work, ""); @@ -152,50 +153,46 @@ public class RegexStringEditor { /** * Apply an operation to a string if it matches a regular expression. - * + * * @param input * The input string. - * + * * @param patt * The pattern to match against it. - * + * * @param action * The action to execute if it matches. - * + * * @return The string, modified by the action if the pattern matched. */ - public static String ifMatches(String input, Pattern patt, UnaryOperator<String> action) { - Matcher matcher = patt.matcher(input); + public static String ifMatches(final String input, final Pattern patt, final UnaryOperator<String> action) { + final Matcher matcher = patt.matcher(input); - if(matcher.matches()) { + if (matcher.matches()) return action.apply(input); - } else { - return input; - } + else return input; } /** * Apply an operation to a string if it matches a regular expression. - * + * * @param input * The input string. - * + * * @param patt * The pattern to match against it. - * + * * @param action * The action to execute if it doesn't match. - * + * * @return The string, modified by the action if the pattern didn't * match. */ - public static String ifNotMatches(String input, Pattern patt, UnaryOperator<String> action) { - Matcher matcher = patt.matcher(input); + public static String ifNotMatches(final String input, final Pattern patt, final UnaryOperator<String> action) { + final Matcher matcher = patt.matcher(input); - if(matcher.matches()) { + if (matcher.matches()) return input; - } else { - return action.apply(input); - } + else return action.apply(input); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java index b4d56a1..4216544 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java @@ -1,5 +1,11 @@ package bjc.utils.ioutils; +import java.io.InputStream; +import java.util.InputMismatchException; +import java.util.Scanner; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; import bjc.utils.data.Identity; @@ -9,12 +15,6 @@ import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IMap; -import java.io.InputStream; -import java.util.InputMismatchException; -import java.util.Scanner; -import java.util.function.BiConsumer; -import java.util.function.Consumer; - /** * This class parses a rules based config file, and uses it to drive a provided * set of actions @@ -41,7 +41,7 @@ public class RuleBasedConfigReader<E> { // Map of pragma names to pragma actions // Pragma actions are functions taking a tokenizer and application state - private IMap<String, BiConsumer<FunctionalStringTokenizer, E>> pragmas; + private final IMap<String, BiConsumer<FunctionalStringTokenizer, E>> pragmas; /** * Create a new rule-based config reader @@ -53,8 +53,8 @@ public class RuleBasedConfigReader<E> { * @param end * The action to fire when ending a rule */ - public RuleBasedConfigReader(BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, - BiConsumer<FunctionalStringTokenizer, E> continueRule, Consumer<E> end) { + public RuleBasedConfigReader(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, + final BiConsumer<FunctionalStringTokenizer, E> continueRule, final Consumer<E> end) { this.start = start; this.continueRule = continueRule; this.end = end; @@ -70,33 +70,33 @@ public class RuleBasedConfigReader<E> { * @param action * The function to execute when this pragma is read */ - public void addPragma(String name, BiConsumer<FunctionalStringTokenizer, E> action) { - if(name == null) + public void addPragma(final String name, final BiConsumer<FunctionalStringTokenizer, E> action) { + if (name == null) throw new NullPointerException("Pragma name must not be null"); - else if(action == null) throw new NullPointerException("Pragma action must not be null"); + else if (action == null) throw new NullPointerException("Pragma action must not be null"); pragmas.put(name, action); } - private void continueRule(E state, boolean isRuleOpen, String line) { + private void continueRule(final E state, final boolean isRuleOpen, final String line) { // Make sure our input is correct - if(isRuleOpen == false) + if (isRuleOpen == false) throw new InputMismatchException("Cannot continue rule with no rule open"); - else if(continueRule == null) + else if (continueRule == null) throw new InputMismatchException("Rule continuation not supported for current grammar"); // Accept the rule continueRule.accept(new FunctionalStringTokenizer(line.substring(1), " "), state); } - private boolean endRule(E state, boolean isRuleOpen) { + private boolean endRule(final E state, final boolean isRuleOpen) { // Ignore blank line without an open rule - if(isRuleOpen == false) + if (isRuleOpen == false) // Do nothing return false; else { // Nothing happens on rule end - if(end != null) { + if (end != null) { // Process the rule ending end.accept(state); } @@ -115,28 +115,28 @@ public class RuleBasedConfigReader<E> { * The initial state of the reader * @return The final state of the reader */ - public E fromStream(InputStream input, E initialState) { - if(input == null) throw new NullPointerException("Input stream must not be null"); + public E fromStream(final InputStream input, final E initialState) { + if (input == null) throw new NullPointerException("Input stream must not be null"); // Application state: We're giving this back later - E state = initialState; + final E state = initialState; // Prepare our input source - try(Scanner source = new Scanner(input)) { + try (Scanner source = new Scanner(input)) { source.useDelimiter("\n"); // This is true when a rule's open - IHolder<Boolean> isRuleOpen = new Identity<>(false); + final IHolder<Boolean> isRuleOpen = new Identity<>(false); // Do something for every line of the file source.forEachRemaining((line) -> { // Skip comment lines - if(line.startsWith("#") || line.startsWith("//")) + if (line.startsWith("#") || line.startsWith("//")) // It's a comment return; - else if(line.equals("")) { + else if (line.equals("")) { // End the rule isRuleOpen.replace(endRule(state, isRuleOpen.getValue())); - } else if(line.startsWith("\t")) { + } else if (line.startsWith("\t")) { // Continue the rule continueRule(state, isRuleOpen.getValue(), line); } else { @@ -157,7 +157,7 @@ public class RuleBasedConfigReader<E> { * @param continueRule * The action to execute on continuation of a rule */ - public void setContinueRule(BiConsumer<FunctionalStringTokenizer, E> continueRule) { + public void setContinueRule(final BiConsumer<FunctionalStringTokenizer, E> continueRule) { this.continueRule = continueRule; } @@ -167,7 +167,7 @@ public class RuleBasedConfigReader<E> { * @param end * The action to execute on ending of a rule */ - public void setEndRule(Consumer<E> end) { + public void setEndRule(final Consumer<E> end) { this.end = end; } @@ -177,23 +177,23 @@ public class RuleBasedConfigReader<E> { * @param start * The action to execute on starting of a rule */ - public void setStartRule(BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) { - if(start == null) throw new NullPointerException("Action on rule start must be non-null"); + public void setStartRule(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) { + if (start == null) throw new NullPointerException("Action on rule start must be non-null"); this.start = start; } - private boolean startRule(E state, boolean isRuleOpen, String line) { + private boolean startRule(final E state, boolean isRuleOpen, final String line) { // Create the line tokenizer - FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(line, " "); + final FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(line, " "); // Get the initial token - String nextToken = tokenizer.nextToken(); + final String nextToken = tokenizer.nextToken(); // Handle pragmas - if(nextToken.equals("pragma")) { + if (nextToken.equals("pragma")) { // Get the pragma name - String token = tokenizer.nextToken(); + final String token = tokenizer.nextToken(); // Handle pragmas pragmas.getOrDefault(token, (tokenzer, stat) -> { @@ -201,7 +201,7 @@ public class RuleBasedConfigReader<E> { }).accept(tokenizer, state); } else { // Make sure input is correct - if(isRuleOpen == true) + if (isRuleOpen == true) throw new InputMismatchException("Nested rules are currently not supported"); // Start a rule diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java index f19eb2c..ccb73a4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java @@ -1,11 +1,11 @@ package bjc.utils.ioutils; +import java.util.function.BiConsumer; + import bjc.utils.exceptions.PragmaFormatException; import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcutils.ListUtils; -import java.util.function.BiConsumer; - /** * Contains factory methods for common pragma types * @@ -25,22 +25,22 @@ public class RuleBasedReaderPragmas { * The function to invoke with the parsed integer * @return A pragma that functions as described above. */ - public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildInteger(String name, - BiConsumer<Integer, StateType> consumer) { + public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildInteger(final String name, + final BiConsumer<Integer, StateType> consumer) { return (tokenizer, state) -> { // Check our input is correct - if(!tokenizer.hasMoreTokens()) + if (!tokenizer.hasMoreTokens()) throw new PragmaFormatException("Pragma " + name + " requires one integer argument"); // Read the argument - String token = tokenizer.nextToken(); + final String token = tokenizer.nextToken(); try { // Run the pragma consumer.accept(Integer.parseInt(token), state); - } catch(NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { // Tell the user their argument isn't correct - PragmaFormatException pfex = new PragmaFormatException( + final PragmaFormatException pfex = new PragmaFormatException( "Argument " + token + " to " + name + " pragma isn't a valid integer. " + "This pragma requires a integer argument"); @@ -63,15 +63,15 @@ public class RuleBasedReaderPragmas { * The function to invoke with the parsed string * @return A pragma that functions as described above. */ - public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildStringCollapser(String name, - BiConsumer<String, StateType> consumer) { + public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildStringCollapser( + final String name, final BiConsumer<String, StateType> consumer) { return (tokenizer, state) -> { // Check our input - if(!tokenizer.hasMoreTokens()) throw new PragmaFormatException( + if (!tokenizer.hasMoreTokens()) throw new PragmaFormatException( "Pragma " + name + " requires one or more string arguments"); // Build our argument - String collapsed = ListUtils.collapseTokens(tokenizer.toList()); + final String collapsed = ListUtils.collapseTokens(tokenizer.toList()); // Run the pragma consumer.accept(collapsed, state); diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/SimpleProperties.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/SimpleProperties.java index f00f245..e142ea3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/SimpleProperties.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/SimpleProperties.java @@ -10,12 +10,12 @@ import java.util.Set; /** * Simple file based properties. - * + * * @author EVE * */ public class SimpleProperties implements Map<String, String> { - private Map<String, String> props; + private final Map<String, String> props; /** * Create a new set of simple properties. @@ -26,42 +26,46 @@ public class SimpleProperties implements Map<String, String> { /** * Load properties from the provided input stream. - * + * * The format is the name, a space, then the body. - * + * * All leading/trailing spaces from the name & body are removed. - * + * * @param is * The stream to read from. - * + * * @param allowDuplicates * Whether or not duplicate keys should be allowed. */ - public void loadFrom(InputStream is, boolean allowDuplicates) { + public void loadFrom(final InputStream is, final boolean allowDuplicates) { try (Scanner scn = new Scanner(is)) { while (scn.hasNextLine()) { - String ln = scn.nextLine().trim(); + final String ln = scn.nextLine().trim(); /* * Skip blank lines/comments */ - if (ln.equals("")) continue; - if (ln.startsWith("#")) continue; + if (ln.equals("")) { + continue; + } + if (ln.startsWith("#")) { + continue; + } - int sepIdx = ln.indexOf(' '); + final int sepIdx = ln.indexOf(' '); if (sepIdx == -1) { - String fmt = "Properties must be a name, a space, then the body.\n\tOffending line is '%s'"; - String msg = String.format(fmt, ln); + final String fmt = "Properties must be a name, a space, then the body.\n\tOffending line is '%s'"; + final String msg = String.format(fmt, ln); throw new NoSuchElementException(msg); } - String name = ln.substring(0, sepIdx).trim(); - String body = ln.substring(sepIdx).trim(); + final String name = ln.substring(0, sepIdx).trim(); + final String body = ln.substring(sepIdx).trim(); if (!allowDuplicates && containsKey(name)) { - String msg = String.format("Duplicate key '%s'", name); + final String msg = String.format("Duplicate key '%s'", name); throw new IllegalStateException(msg); } @@ -77,7 +81,7 @@ public class SimpleProperties implements Map<String, String> { public void outputProperties() { System.out.println("Read properties:"); - for (Entry<String, String> entry : entrySet()) { + for (final Entry<String, String> entry : entrySet()) { System.out.printf("\t'%s'\t'%s'\n", entry.getKey(), entry.getValue()); } @@ -96,35 +100,35 @@ public class SimpleProperties implements Map<String, String> { @SuppressWarnings("unlikely-arg-type") @Override - public boolean containsKey(Object key) { + public boolean containsKey(final Object key) { return props.containsKey(key); } @SuppressWarnings("unlikely-arg-type") @Override - public boolean containsValue(Object value) { + public boolean containsValue(final Object value) { return props.containsValue(value); } @SuppressWarnings("unlikely-arg-type") @Override - public String get(Object key) { + public String get(final Object key) { return props.get(key); } @Override - public String put(String key, String value) { + public String put(final String key, final String value) { return props.put(key, value); } @SuppressWarnings("unlikely-arg-type") @Override - public String remove(Object key) { + public String remove(final Object key) { return props.remove(key); } @Override - public void putAll(Map<? extends String, ? extends String> m) { + public void putAll(final Map<? extends String, ? extends String> m) { props.putAll(m); } @@ -149,7 +153,7 @@ public class SimpleProperties implements Map<String, String> { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { return props.equals(o); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/Block.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/Block.java index e92644e..b514d17 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/Block.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/Block.java @@ -2,7 +2,7 @@ package bjc.utils.ioutils.blocks; /** * Represents a block of text read in from a source. - * + * * @author EVE * */ @@ -29,7 +29,7 @@ public class Block { /** * Create a new block. - * + * * @param blockNo * The number of this block. * @param contents @@ -39,7 +39,7 @@ public class Block { * @param endLine * The line this block ended. */ - public Block(int blockNo, String contents, int startLine, int endLine) { + public Block(final int blockNo, final String contents, final int startLine, final int endLine) { this.contents = contents; this.startLine = startLine; this.endLine = endLine; @@ -52,7 +52,7 @@ public class Block { int result = 1; result = prime * result + blockNo; - result = prime * result + ((contents == null) ? 0 : contents.hashCode()); + result = prime * result + (contents == null ? 0 : contents.hashCode()); result = prime * result + endLine; result = prime * result + startLine; @@ -60,21 +60,21 @@ public class Block { } @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Block)) return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof Block)) return false; - Block other = (Block) obj; + final Block other = (Block) obj; - if(blockNo != other.blockNo) return false; + if (blockNo != other.blockNo) return false; - if(contents == null) { - if(other.contents != null) return false; - } else if(!contents.equals(other.contents)) return false; + if (contents == null) { + if (other.contents != null) return false; + } else if (!contents.equals(other.contents)) return false; - if(endLine != other.endLine) return false; - if(startLine != other.startLine) return false; + if (endLine != other.endLine) return false; + if (startLine != other.startLine) return false; return true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java index d45a4f3..dac535e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java @@ -7,39 +7,39 @@ import java.util.function.Consumer; /** * A source of blocks of characters, marked with line numbers as to block * start/block end. - * + * * @author bjculkin * */ public interface BlockReader extends AutoCloseable, Iterator<Block> { /** * Check if this reader has an available block. - * + * * @return Whether or not another block is available. */ boolean hasNextBlock(); /** * Get the current block. - * + * * @return The current block, or null if there is no current block. */ Block getBlock(); /** * Move to the next block. - * + * * @return Whether or not the next block was successfully read. */ boolean nextBlock(); /** * Execute an action for each remaining block. - * + * * @param action * The action to execute for each block */ - default void forEachBlock(Consumer<Block> action) { + default void forEachBlock(final Consumer<Block> action) { while (hasNext()) { action.accept(next()); } @@ -47,11 +47,12 @@ public interface BlockReader extends AutoCloseable, Iterator<Block> { /** * Retrieve the number of blocks that have been read so far. - * + * * @return The number of blocks read so far. */ int getBlockCount(); + @Override void close() throws IOException; @Override diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java index ca82b51..8bbb89c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java @@ -4,50 +4,50 @@ import java.io.Reader; /** * Utility methods for constructing instances of {@link BlockReader} - * + * * @author bjculkin * */ public class BlockReaders { /** * Create a new simple block reader that works off a regex. - * + * * @param blockDelim * The regex that separates blocks. - * + * * @param source * The reader to get blocks from. - * + * * @return A configured simple reader. */ - public static SimpleBlockReader simple(String blockDelim, Reader source) { + public static SimpleBlockReader simple(final String blockDelim, final Reader source) { return new SimpleBlockReader(blockDelim, source); } /** * Create a new pushback block reader. - * + * * @param src * The block reader to read blocks from. - * + * * @return A configured pushback reader. */ - public static PushbackBlockReader pushback(BlockReader src) { + public static PushbackBlockReader pushback(final BlockReader src) { return new PushbackBlockReader(src); } /** * Create a new triggered block reader. - * + * * @param source * The block reader to read blocks from. - * + * * @param action * The action to execute before reading a block. - * + * * @return A configured triggered block reader. */ - public static BlockReader trigger(BlockReader source, Runnable action) { + public static BlockReader trigger(final BlockReader source, final Runnable action) { return new TriggeredBlockReader(source, action); } @@ -56,26 +56,26 @@ public class BlockReaders { * * @param primary * The first source to read blocks from. - * + * * @param secondary * The second source to read blocks from. - * + * * @return A configured layered block reader. */ - public static BlockReader layered(BlockReader primary, BlockReader secondary) { + public static BlockReader layered(final BlockReader primary, final BlockReader secondary) { return new LayeredBlockReader(primary, secondary); } /** * Create a new serial block reader. - * + * * @param readers * The readers to pull from, in the order to pull from * them. - * + * * @return A configured serial block reader. */ - public static BlockReader serial(BlockReader... readers) { + public static BlockReader serial(final BlockReader... readers) { return new SerialBlockReader(readers); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java index 9ece6df..54010fe 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java @@ -5,30 +5,30 @@ import java.io.IOException; /** * A block reader that supports draining all the blocks from one reading before * swapping to another. - * + * * This is more a 'prioritize blocks from one over the other', than a 'read all * the blocks from one, then all the blocks from the other'. If you need that, * look at {@link SerialBlockReader}. - * + * * @author bjculkin * */ public class LayeredBlockReader implements BlockReader { - private BlockReader first; - private BlockReader second; + private final BlockReader first; + private final BlockReader second; private int blockNo; /** * Create a new layered block reader. - * + * * @param primary * The first source to read blocks from. - * + * * @param secondary * The second source to read blocks from. */ - public LayeredBlockReader(BlockReader primary, BlockReader secondary) { + public LayeredBlockReader(final BlockReader primary, final BlockReader secondary) { first = primary; second = secondary; } @@ -40,18 +40,20 @@ public class LayeredBlockReader implements BlockReader { @Override public Block getBlock() { - Block firstBlock = first.getBlock(); + final Block firstBlock = first.getBlock(); return firstBlock == null ? second.getBlock() : firstBlock; } @Override public boolean nextBlock() { - boolean gotFirst = first.nextBlock(); + final boolean gotFirst = first.nextBlock(); - boolean succ = gotFirst ? gotFirst : second.nextBlock(); + final boolean succ = gotFirst ? gotFirst : second.nextBlock(); - if (succ) blockNo += 1; + if (succ) { + blockNo += 1; + } return succ; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java index 96906ae..d7ba247 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java @@ -7,14 +7,14 @@ import java.util.LinkedList; /** * A block reader that supports pushing blocks onto the input queue so that they * are provided before blocks read from an input source. - * + * * @author bjculkin * */ public class PushbackBlockReader implements BlockReader { - private BlockReader source; + private final BlockReader source; - private Deque<Block> waiting; + private final Deque<Block> waiting; private Block curBlock; @@ -22,11 +22,11 @@ public class PushbackBlockReader implements BlockReader { /** * Create a new pushback block reader. - * + * * @param src * The block reader to use when no blocks are queued. */ - public PushbackBlockReader(BlockReader src) { + public PushbackBlockReader(final BlockReader src) { source = src; waiting = new LinkedList<>(); @@ -51,10 +51,12 @@ public class PushbackBlockReader implements BlockReader { return true; } else { - boolean succ = source.nextBlock(); + final boolean succ = source.nextBlock(); curBlock = source.getBlock(); - if (succ) blockNo += 1; + if (succ) { + blockNo += 1; + } return succ; } @@ -72,21 +74,21 @@ public class PushbackBlockReader implements BlockReader { /** * Insert a block at the back of the queue of pending blocks. - * + * * @param blk * The block to put at the back. */ - public void addBlock(Block blk) { + public void addBlock(final Block blk) { waiting.add(blk); } /** * Insert a block at the front of the queue of pending blocks. - * + * * @param blk * The block to put at the front. */ - public void pushBlock(Block blk) { + public void pushBlock(final Block blk) { waiting.push(blk); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java index 2363468..7735981 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java @@ -5,7 +5,7 @@ import java.util.Deque; /** * Provides a means of concatenating two block readers. - * + * * @author bjculkin * */ @@ -16,13 +16,13 @@ public class SerialBlockReader implements BlockReader { /** * Create a new serial block reader. - * + * * @param readers * The readers to pull from, in the order to pull from * them. */ - public SerialBlockReader(BlockReader... readers) { - for (BlockReader reader : readers) { + public SerialBlockReader(final BlockReader... readers) { + for (final BlockReader reader : readers) { readerQueue.add(reader); } } @@ -38,7 +38,7 @@ public class SerialBlockReader implements BlockReader { while (!cont) { try { readerQueue.pop().close(); - } catch (IOException ioex) { + } catch (final IOException ioex) { throw new IllegalStateException("Exception thrown by discarded reader", ioex); } @@ -68,7 +68,7 @@ public class SerialBlockReader implements BlockReader { while (!cont) { try { readerQueue.pop().close(); - } catch (IOException ioex) { + } catch (final IOException ioex) { throw new IllegalStateException("Exception thrown by discarded reader", ioex); } @@ -77,7 +77,9 @@ public class SerialBlockReader implements BlockReader { cont = gotBlock || readerQueue.isEmpty(); } - if (cont) blockNo += 1; + if (cont) { + blockNo += 1; + } return cont; } @@ -90,7 +92,7 @@ public class SerialBlockReader implements BlockReader { @Override public void close() throws IOException { while (!readerQueue.isEmpty()) { - BlockReader reader = readerQueue.pop(); + final BlockReader reader = readerQueue.pop(); reader.close(); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java index 6ee1d57..87083d1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java @@ -9,10 +9,10 @@ import java.util.regex.Pattern; /** * Simple implementation of {@link BlockReader} - * + * * NOTE: The EOF marker is always treated as a delimiter. You are expected to * handle blocks that may be shorter than you expect. - * + * * @author EVE * */ @@ -20,8 +20,8 @@ public class SimpleBlockReader implements BlockReader { /* * I/O source for blocks. */ - private LineNumberReader lnReader; - private Scanner blockReader; + private final LineNumberReader lnReader; + private final Scanner blockReader; /* * The current block. @@ -31,21 +31,21 @@ public class SimpleBlockReader implements BlockReader { /** * Create a new block reader. - * + * * @param blockDelim * The pattern that separates blocks. Note that the end * of file is always considered to end a block. - * + * * @param source * The source to read blocks from. */ - public SimpleBlockReader(String blockDelim, Reader source) { + public SimpleBlockReader(final String blockDelim, final Reader source) { lnReader = new LineNumberReader(source); blockReader = new Scanner(lnReader); - String pattern = String.format("(?:%s)|\\Z", blockDelim); - Pattern pt = Pattern.compile(pattern, Pattern.MULTILINE); + final String pattern = String.format("(?:%s)|\\Z", blockDelim); + final Pattern pt = Pattern.compile(pattern, Pattern.MULTILINE); blockReader.useDelimiter(pt); } @@ -63,15 +63,15 @@ public class SimpleBlockReader implements BlockReader { @Override public boolean nextBlock() { try { - int blockStartLine = lnReader.getLineNumber(); - String blockContents = blockReader.next(); - int blockEndLine = lnReader.getLineNumber(); + final int blockStartLine = lnReader.getLineNumber(); + final String blockContents = blockReader.next(); + final int blockEndLine = lnReader.getLineNumber(); blockNo += 1; currBlock = new Block(blockNo, blockContents, blockStartLine, blockEndLine); return true; - } catch (NoSuchElementException nseex) { + } catch (final NoSuchElementException nseex) { currBlock = null; return false; @@ -92,11 +92,11 @@ public class SimpleBlockReader implements BlockReader { /** * Set the delimiter used to separate blocks. - * + * * @param delim * The delimiter used to separate blocks. */ - public void setDelimiter(String delim) { + public void setDelimiter(final String delim) { blockReader.useDelimiter(delim); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java index cfe72c2..0e50ad6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java @@ -4,25 +4,25 @@ import java.io.IOException; /** * A block reader that fires an action before a block is actually read. - * + * * @author bjculkin * */ public class TriggeredBlockReader implements BlockReader { - private BlockReader source; + private final BlockReader source; - private Runnable action; + private final Runnable action; /** * Create a new triggered reader with the specified source/action. - * + * * @param source * The block reader to read blocks from. - * + * * @param action * The action to execute before reading a block. */ - public TriggeredBlockReader(BlockReader source, Runnable action) { + public TriggeredBlockReader(final BlockReader source, final Runnable action) { super(); this.source = source; this.action = action; diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/DoubleMatcher.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/DoubleMatcher.java index a91bf2a..888ea7a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/DoubleMatcher.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/DoubleMatcher.java @@ -1,8 +1,9 @@ package bjc.utils.parserutils; -import java.util.regex.Pattern; +import static bjc.utils.PropertyDB.applyFormat; +import static bjc.utils.PropertyDB.getRegex; -import static bjc.utils.PropertyDB.*; +import java.util.regex.Pattern; /* * Checks if a string would pass Double.parseDouble. diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java index bb6ebac..aa366cf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -15,7 +15,7 @@ public interface IPrecedent { * The precedence of the object to handle * @return A new object with set precedence */ - public static IPrecedent newSimplePrecedent(int precedence) { + public static IPrecedent newSimplePrecedent(final int precedence) { return () -> precedence; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ParserException.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ParserException.java index 2a41009..ae33aba 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ParserException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ParserException.java @@ -2,27 +2,35 @@ package bjc.utils.parserutils; /** * General superclass for exceptions thrown during parsing. - * + * * @author EVE * */ public class ParserException extends Exception { /** + * + */ + private static final long serialVersionUID = 631298568113373233L; + + /** * Create a new exception with the provided message. - * - * @param msg The message for the exception. + * + * @param msg + * The message for the exception. */ - public ParserException(String msg) { + public ParserException(final String msg) { super(msg); } - + /** * Create a new exception with the provided message and cause. - * - * @param msg The message for the exception. - * @param cause The cause of the exception. + * + * @param msg + * The message for the exception. + * @param cause + * The cause of the exception. */ - public ParserException(String msg, Exception cause) { + public ParserException(final String msg, final Exception cause) { super(msg, cause); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java index b30a69c..44744f5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -1,16 +1,16 @@ package bjc.utils.parserutils; +import java.util.Deque; +import java.util.LinkedList; +import java.util.function.Consumer; +import java.util.function.Function; + import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.StringUtils; -import java.util.Deque; -import java.util.LinkedList; -import java.util.function.Consumer; -import java.util.function.Function; - /** * Utility to run the shunting yard algorithm on a bunch of tokens. * @@ -47,7 +47,7 @@ public class ShuntingYard<TokenType> { private final int precedence; - private Operator(int prec) { + private Operator(final int prec) { precedence = prec; } @@ -58,40 +58,40 @@ public class ShuntingYard<TokenType> { } private final class TokenShunter implements Consumer<String> { - private IList<TokenType> output; - private Deque<String> stack; - private Function<String, TokenType> transformer; + private final IList<TokenType> output; + private final Deque<String> stack; + private final Function<String, TokenType> transformer; - public TokenShunter(IList<TokenType> outpt, Deque<String> stack, - Function<String, TokenType> transformer) { + public TokenShunter(final IList<TokenType> outpt, final Deque<String> stack, + final Function<String, TokenType> transformer) { this.output = outpt; this.stack = stack; this.transformer = transformer; } @Override - public void accept(String token) { + public void accept(final String token) { // Handle operators - if(operators.containsKey(token)) { + if (operators.containsKey(token)) { // Pop operators while there isn't a higher // precedence one - while(!stack.isEmpty() && isHigherPrec(token, stack.peek())) { + while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) { output.add(transformer.apply(stack.pop())); } // Put this operator onto the stack stack.push(token); - } else if(StringUtils.containsOnly(token, "\\(")) { + } else if (StringUtils.containsOnly(token, "\\(")) { // Handle groups of parenthesis for multiple // nesting levels stack.push(token); - } else if(StringUtils.containsOnly(token, "\\)")) { + } else if (StringUtils.containsOnly(token, "\\)")) { // Handle groups of parenthesis for multiple // nesting levels - String swappedToken = token.replace(')', '('); + final String swappedToken = token.replace(')', '('); // Remove tokens up to a matching parenthesis - while(!stack.peek().equals(swappedToken)) { + while (!stack.peek().equals(swappedToken)) { output.add(transformer.apply(stack.pop())); } @@ -116,11 +116,11 @@ public class ShuntingYard<TokenType> { * Whether or not basic math operators should be * provided. */ - public ShuntingYard(boolean configureBasics) { + public ShuntingYard(final boolean configureBasics) { operators = new FunctionalMap<>(); // Add basic operators if we're configured to do so - if(configureBasics) { + if (configureBasics) { operators.put("+", Operator.ADD); operators.put("-", Operator.SUBTRACT); operators.put("*", Operator.MULTIPLY); @@ -133,15 +133,15 @@ public class ShuntingYard<TokenType> { * * @param operator * The token representing the operator. - * + * * @param precedence * The precedence of the operator to add. */ - public void addOp(String operator, int precedence) { + public void addOp(final String operator, final int precedence) { /* * Create the precedence marker */ - IPrecedent prec = IPrecedent.newSimplePrecedent(precedence); + final IPrecedent prec = IPrecedent.newSimplePrecedent(precedence); this.addOp(operator, prec); } @@ -151,17 +151,17 @@ public class ShuntingYard<TokenType> { * * @param operator * The token representing the operator. - * + * * @param precedence * The precedence of the operator. */ - public void addOp(String operator, IPrecedent precedence) { + public void addOp(final String operator, final IPrecedent precedence) { /* * Complain about trying to add an incorrect operator */ - if(operator == null) + if (operator == null) throw new NullPointerException("Operator must not be null"); - else if(precedence == null) throw new NullPointerException("Precedence must not be null"); + else if (precedence == null) throw new NullPointerException("Precedence must not be null"); /* * Add the operator to the ones we handle @@ -169,16 +169,16 @@ public class ShuntingYard<TokenType> { operators.put(operator, precedence); } - private boolean isHigherPrec(String left, String right) { + private boolean isHigherPrec(final String left, final String right) { // Check if the right operator exists - boolean exists = operators.containsKey(right); + final boolean exists = operators.containsKey(right); // If it doesn't, the left is higher precedence. - if(!exists) return false; + if (!exists) return false; // Get the precedence of operators - int rightPrecedence = operators.get(right).getPrecedence(); - int leftPrecedence = operators.get(left).getPrecedence(); + final int rightPrecedence = operators.get(right).getPrecedence(); + final int leftPrecedence = operators.get(left).getPrecedence(); // Evaluate what we were asked return rightPrecedence >= leftPrecedence; @@ -189,23 +189,23 @@ public class ShuntingYard<TokenType> { * * @param input * The string to transform. - * + * * @param transformer * The function to use to transform strings to tokens. - * + * * @return A list of tokens in postfix notation. */ - public IList<TokenType> postfix(IList<String> input, Function<String, TokenType> transformer) { + public IList<TokenType> postfix(final IList<String> input, final Function<String, TokenType> transformer) { // Check our input - if(input == null) + if (input == null) throw new NullPointerException("Input must not be null"); - else if(transformer == null) throw new NullPointerException("Transformer must not be null"); + else if (transformer == null) throw new NullPointerException("Transformer must not be null"); // Here's what we're handing back - IList<TokenType> output = new FunctionalList<>(); + final IList<TokenType> output = new FunctionalList<>(); // The stack to put operators on - Deque<String> stack = new LinkedList<>(); + final Deque<String> stack = new LinkedList<>(); // Shunt the tokens input.forEach(new TokenShunter(output, stack, transformer)); @@ -225,9 +225,9 @@ public class ShuntingYard<TokenType> { * The token representing the operator. If null, remove * all operators. */ - public void removeOp(String operator) { + public void removeOp(final String operator) { // Check if we want to remove all operators - if(operator == null) { + if (operator == null) { operators = new FunctionalMap<>(); } else { operators.remove(operator); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java index c441dff..89dc35f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java @@ -1,5 +1,11 @@ package bjc.utils.parserutils; +import java.util.Deque; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + import bjc.utils.data.IHolder; import bjc.utils.data.ITree; import bjc.utils.data.Pair; @@ -7,23 +13,17 @@ import bjc.utils.data.Tree; import bjc.utils.parserutils.TreeConstructor.ConstructorState; import bjc.utils.parserutils.TreeConstructor.QueueFlattener; -import java.util.Deque; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.function.UnaryOperator; - final class TokenTransformer<TokenType> implements Consumer<TokenType> { // Handle operators private final class OperatorHandler implements UnaryOperator<ConstructorState<TokenType>> { - private TokenType element; + private final TokenType element; - public OperatorHandler(TokenType element) { + public OperatorHandler(final TokenType element) { this.element = element; } @Override - public ConstructorState<TokenType> apply(ConstructorState<TokenType> pair) { + public ConstructorState<TokenType> apply(final ConstructorState<TokenType> pair) { // Replace the current AST with the result of handling // an operator return new ConstructorState<>(pair.bindLeft(queuedASTs -> { @@ -31,18 +31,18 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { })); } - private ConstructorState<TokenType> handleOperator(Deque<ITree<TokenType>> queuedASTs) { + private ConstructorState<TokenType> handleOperator(final Deque<ITree<TokenType>> queuedASTs) { // The AST we're going to hand back ITree<TokenType> newAST; // Handle special operators - if(isSpecialOperator.test(element)) { + if (isSpecialOperator.test(element)) { newAST = handleSpecialOperator.apply(element).apply(queuedASTs); } else { // Error if we don't have enough for a binary // operator - if(queuedASTs.size() < 2) { - String msg = String.format( + if (queuedASTs.size() < 2) { + final String msg = String.format( "Attempted to parse binary operator without enough operands\n\tProblem operator is: %s\n\tPossible operand is: %s", element.toString(), queuedASTs.peek().toString()); @@ -50,8 +50,8 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { } // Grab the two operands - ITree<TokenType> right = queuedASTs.pop(); - ITree<TokenType> left = queuedASTs.pop(); + final ITree<TokenType> right = queuedASTs.pop(); + final ITree<TokenType> left = queuedASTs.pop(); // Create a new AST newAST = new Tree<>(element, left, right); @@ -65,17 +65,17 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { } } - private IHolder<ConstructorState<TokenType>> initialState; + private final IHolder<ConstructorState<TokenType>> initialState; - private Predicate<TokenType> operatorPredicate; + private final Predicate<TokenType> operatorPredicate; - private Predicate<TokenType> isSpecialOperator; - private Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator; + private final Predicate<TokenType> isSpecialOperator; + private final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator; // Create a new transformer - public TokenTransformer(IHolder<ConstructorState<TokenType>> initialState, - Predicate<TokenType> operatorPredicate, Predicate<TokenType> isSpecialOperator, - Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { + public TokenTransformer(final IHolder<ConstructorState<TokenType>> initialState, + final Predicate<TokenType> operatorPredicate, final Predicate<TokenType> isSpecialOperator, + final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { this.initialState = initialState; this.operatorPredicate = operatorPredicate; this.isSpecialOperator = isSpecialOperator; @@ -83,12 +83,12 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { } @Override - public void accept(TokenType element) { + public void accept(final TokenType element) { // Handle operators - if(operatorPredicate.test(element)) { + if (operatorPredicate.test(element)) { initialState.transform(new OperatorHandler(element)); } else { - ITree<TokenType> newAST = new Tree<>(element); + final ITree<TokenType> newAST = new Tree<>(element); // Insert the new tree into the AST initialState.transform(pair -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenUtils.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenUtils.java index 39e0c4e..5de0586 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenUtils.java @@ -1,17 +1,17 @@ package bjc.utils.parserutils; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; -import bjc.utils.parserutils.splitterv2.TokenSplitter; +import static bjc.utils.PropertyDB.applyFormat; +import static bjc.utils.PropertyDB.getCompiledRegex; +import static bjc.utils.PropertyDB.getRegex; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static bjc.utils.PropertyDB.getRegex; -import static bjc.utils.PropertyDB.getCompiledRegex; -import static bjc.utils.PropertyDB.applyFormat; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; +import bjc.utils.parserutils.splitterv2.TokenSplitter; /** * Utilities useful for operating on PL tokens. @@ -27,7 +27,7 @@ public class TokenUtils { */ public static class StringTokenSplitter implements TokenSplitter { @Override - public IList<String> split(String input) { + public IList<String> split(final String input) { return new FunctionalList<>(TokenUtils.removeDQuotedStrings(input)); } } @@ -67,34 +67,33 @@ public class TokenUtils { * @return An list containing alternating bits of the string and the * embedded double-quoted strings that separated them. */ - public static List<String> removeDQuotedStrings(String inp) { - if(inp == null) { - throw new NullPointerException("inp must not be null"); - } + public static List<String> removeDQuotedStrings(final String inp) { + if (inp == null) throw new NullPointerException("inp must not be null"); /* * What we need for piece-by-piece string building */ StringBuffer work = new StringBuffer(); - List<String> res = new LinkedList<>(); + final List<String> res = new LinkedList<>(); /* * Matcher for proper strings and single quotes. */ - Matcher mt = doubleQuotePatt.matcher(inp); - Matcher corr = quotePatt.matcher(inp); + final Matcher mt = doubleQuotePatt.matcher(inp); + final Matcher corr = quotePatt.matcher(inp); - if(corr.find() && !corr.find()) { + if (corr.find() && !corr.find()) { /* * There's a unmatched opening quote with no strings. */ - String msg = String.format("Unclosed string literal '%s'. Opening quote was at position %d", - inp, inp.indexOf("\"")); + final String msg = String.format( + "Unclosed string literal '%s'. Opening quote was at position %d", inp, + inp.indexOf("\"")); throw new IllegalArgumentException(msg); } - while(mt.find()) { + while (mt.find()) { /* * Remove the string until the quoted string. */ @@ -117,15 +116,16 @@ public class TokenUtils { * Grab the remainder of the string. */ mt.appendTail(work); - String tail = work.toString(); + final String tail = work.toString(); - if(tail.contains("\"")) { + if (tail.contains("\"")) { /* * There's a unmatched opening quote with at least one * string. */ - String msg = String.format("Unclosed string literal '%s'. Opening quote was at position %d", - inp, inp.lastIndexOf("\"")); + final String msg = String.format( + "Unclosed string literal '%s'. Opening quote was at position %d", inp, + inp.lastIndexOf("\"")); throw new IllegalArgumentException(msg); } @@ -133,7 +133,7 @@ public class TokenUtils { /* * Only add an empty tail if the string was empty. */ - if(!tail.equals("") || res.isEmpty()) { + if (!tail.equals("") || res.isEmpty()) { res.add(tail); } @@ -149,28 +149,26 @@ public class TokenUtils { * @return The string with escape sequences replaced by their equivalent * characters. */ - public static String descapeString(String inp) { - if(inp == null) { - throw new NullPointerException("inp must not be null"); - } + public static String descapeString(final String inp) { + if (inp == null) throw new NullPointerException("inp must not be null"); - StringBuffer work = new StringBuffer(); + final StringBuffer work = new StringBuffer(); - Matcher possibleEscapeFinder = possibleEscapePatt.matcher(inp); - Matcher escapeFinder = escapePatt.matcher(inp); + final Matcher possibleEscapeFinder = possibleEscapePatt.matcher(inp); + final Matcher escapeFinder = escapePatt.matcher(inp); - while(possibleEscapeFinder.find()) { - if(!escapeFinder.find()) { - String msg = String.format("Illegal escape sequence '%s' at position %d", + while (possibleEscapeFinder.find()) { + if (!escapeFinder.find()) { + final String msg = String.format("Illegal escape sequence '%s' at position %d", possibleEscapeFinder.group(), possibleEscapeFinder.start()); throw new IllegalArgumentException(msg); } - String escapeSeq = escapeFinder.group(); + final String escapeSeq = escapeFinder.group(); String escapeRep = ""; - switch(escapeSeq) { + switch (escapeSeq) { case "\\b": escapeRep = "\b"; break; @@ -200,7 +198,7 @@ public class TokenUtils { escapeRep = "\\"; break; default: - if(escapeSeq.startsWith("u")) { + if (escapeSeq.startsWith("u")) { escapeRep = handleUnicodeEscape(escapeSeq.substring(1)); } else { escapeRep = handleOctalEscape(escapeSeq); @@ -215,15 +213,15 @@ public class TokenUtils { return work.toString(); } - private static String handleUnicodeEscape(String seq) { + private static String handleUnicodeEscape(final String seq) { try { - int codepoint = Integer.parseInt(seq, 16); + final int codepoint = Integer.parseInt(seq, 16); return new String(Character.toChars(codepoint)); - } catch(IllegalArgumentException iaex) { - String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq); + } catch (final IllegalArgumentException iaex) { + final String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq); - IllegalArgumentException reiaex = new IllegalArgumentException(msg); + final IllegalArgumentException reiaex = new IllegalArgumentException(msg); reiaex.initCause(iaex); @@ -231,21 +229,22 @@ public class TokenUtils { } } - private static String handleOctalEscape(String seq) { + private static String handleOctalEscape(final String seq) { try { - int codepoint = Integer.parseInt(seq, 8); + final int codepoint = Integer.parseInt(seq, 8); - if(codepoint > 255) { - String msg = String.format("'%d' is outside the range of octal escapes', codepoint"); + if (codepoint > 255) { + final String msg = String + .format("'%d' is outside the range of octal escapes', codepoint"); throw new IllegalArgumentException(msg); } return new String(Character.toChars(codepoint)); - } catch(IllegalArgumentException iaex) { - String msg = String.format("'%s' is not a valid octal escape sequence'", seq); + } catch (final IllegalArgumentException iaex) { + final String msg = String.format("'%s' is not a valid octal escape sequence'", seq); - IllegalArgumentException reiaex = new IllegalArgumentException(msg); + final IllegalArgumentException reiaex = new IllegalArgumentException(msg); reiaex.initCause(iaex); @@ -256,27 +255,27 @@ public class TokenUtils { /** * Check if a given string would be successfully converted to a double * by {@link Double#parseDouble(String)}. - * + * * @param inp * The string to check. * @return Whether the string is a valid double or not. */ - public static boolean isDouble(String inp) { + public static boolean isDouble(final String inp) { return DoubleMatcher.doubleLiteral.matcher(inp).matches(); } /** * Check if a given string would be successfully converted to a integer * by {@link Integer#parseInt(String)}. - * + * * NOTE: This only checks syntax. Using values out of the range of * integers will still cause errors. - * + * * @param inp * The input to check. * @return Whether the string is a valid double or not. */ - public static boolean isInt(String inp) { + public static boolean isInt(final String inp) { return intLitPattern.matcher(inp).matches(); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java index bd0ab97..d7ed5b0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -1,5 +1,10 @@ package bjc.utils.parserutils; +import java.util.Deque; +import java.util.LinkedList; +import java.util.function.Function; +import java.util.function.Predicate; + import bjc.utils.data.IHolder; import bjc.utils.data.IPair; import bjc.utils.data.ITree; @@ -7,11 +12,6 @@ import bjc.utils.data.Identity; import bjc.utils.data.Pair; import bjc.utils.funcdata.IList; -import java.util.Deque; -import java.util.LinkedList; -import java.util.function.Function; -import java.util.function.Predicate; - /** * Creates a parse tree from a postfix expression * @@ -21,7 +21,7 @@ import java.util.function.Predicate; public class TreeConstructor { /** * Alias interface for special operator types. - * + * * @param <TokenType> * The token type of the tree. */ @@ -33,11 +33,11 @@ public class TreeConstructor { * Alias for constructor state. */ static final class ConstructorState<TokenType> extends Pair<Deque<ITree<TokenType>>, ITree<TokenType>> { - public ConstructorState(Deque<ITree<TokenType>> left, ITree<TokenType> right) { + public ConstructorState(final Deque<ITree<TokenType>> left, final ITree<TokenType> right) { super(left, right); } - public ConstructorState(IPair<Deque<ITree<TokenType>>, ITree<TokenType>> par) { + public ConstructorState(final IPair<Deque<ITree<TokenType>>, ITree<TokenType>> par) { super(par.getLeft(), par.getRight()); } } @@ -56,8 +56,8 @@ public class TreeConstructor { * operator * @return A AST from the expression */ - public static <TokenType> ITree<TokenType> constructTree(IList<TokenType> tokens, - Predicate<TokenType> isOperator) { + public static <TokenType> ITree<TokenType> constructTree(final IList<TokenType> tokens, + final Predicate<TokenType> isOperator) { // Construct a tree with no special operators return constructTree(tokens, isOperator, op -> false, null); } @@ -70,37 +70,37 @@ public class TreeConstructor { * * @param <TokenType> * The elements of the parse tree. - * + * * @param tokens * The list of tokens to build a tree from. - * + * * @param isOperator * The predicate to use to determine if something is a * operator. - * + * * @param isSpecialOperator * The predicate to use to determine if an operator needs * special handling. - * + * * @param handleSpecialOperator * The function to use to handle special case operators. - * + * * @return A AST from the expression * */ - public static <TokenType> ITree<TokenType> constructTree(IList<TokenType> tokens, - Predicate<TokenType> isOperator, Predicate<TokenType> isSpecialOperator, - Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { + public static <TokenType> ITree<TokenType> constructTree(final IList<TokenType> tokens, + final Predicate<TokenType> isOperator, final Predicate<TokenType> isSpecialOperator, + final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { // Make sure our parameters are valid - if(tokens == null) + if (tokens == null) throw new NullPointerException("Tokens must not be null"); - else if(isOperator == null) + else if (isOperator == null) throw new NullPointerException("Operator predicate must not be null"); - else if(isSpecialOperator == null) + else if (isSpecialOperator == null) throw new NullPointerException("Special operator determiner must not be null"); // Here is the state for the tree construction - IHolder<ConstructorState<TokenType>> initialState = new Identity<>( + final IHolder<ConstructorState<TokenType>> initialState = new Identity<>( new ConstructorState<>(new LinkedList<>(), null)); // Transform each of the tokens diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java index 3aba434..071afb4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java @@ -5,12 +5,17 @@ package bjc.utils.parserutils.delims; */ public class DelimiterException extends RuntimeException { /** + * + */ + private static final long serialVersionUID = 2079514406049040888L; + + /** * Create a new generic delimiter exception. - * + * * @param res * The reason for this exception. */ - public DelimiterException(String res) { + public DelimiterException(final String res) { super(res); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java index db6ae8c..85d4038 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java @@ -1,12 +1,5 @@ package bjc.utils.parserutils.delims; -import bjc.utils.data.IPair; -import bjc.utils.data.ITree; -import bjc.utils.data.Pair; -import bjc.utils.data.Tree; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.Arrays; import java.util.Deque; import java.util.HashMap; @@ -18,9 +11,16 @@ import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Function; +import bjc.utils.data.IPair; +import bjc.utils.data.ITree; +import bjc.utils.data.Pair; +import bjc.utils.data.Tree; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * Represents a possible delimiter group to match. - * + * * @author EVE * * @param <T> @@ -29,29 +29,29 @@ import java.util.function.Function; public class DelimiterGroup<T> { /** * Represents an instance of a delimiter group. - * + * * @author EVE * */ public class OpenGroup { - private Deque<ITree<T>> contents; + private final Deque<ITree<T>> contents; private IList<ITree<T>> currentGroup; - private T opener; + private final T opener; - private T[] params; + private final T[] params; /** * Create a new instance of a delimiter group. - * + * * @param open * The item that opened this group. - * + * * @param parms * Any parameters from the opener. */ - public OpenGroup(T open, T[] parms) { + public OpenGroup(final T open, final T[] parms) { opener = open; params = parms; @@ -62,36 +62,36 @@ public class DelimiterGroup<T> { /** * Add an item to this group instance. - * + * * @param itm * The item to add to this group instance. */ - public void addItem(ITree<T> itm) { + public void addItem(final ITree<T> itm) { currentGroup.add(itm); } /** * Mark a subgroup. - * + * * @param marker * The item that indicated this subgroup. - * + * * @param chars * The characteristics for building the tree. */ - public void markSubgroup(T marker, SequenceCharacteristics<T> chars) { - ITree<T> subgroupContents = new Tree<>(chars.contents); - for(ITree<T> itm : currentGroup) { + public void markSubgroup(final T marker, final SequenceCharacteristics<T> chars) { + final ITree<T> subgroupContents = new Tree<>(chars.contents); + for (final ITree<T> itm : currentGroup) { subgroupContents.addChild(itm); } - while(!contents.isEmpty()) { - ITree<T> possibleSubordinate = contents.peek(); + while (!contents.isEmpty()) { + final ITree<T> possibleSubordinate = contents.peek(); - if(possibleSubordinate.getHead().equals(chars.subgroup)) { - T otherMarker = possibleSubordinate.getChild(1).getHead(); + if (possibleSubordinate.getHead().equals(chars.subgroup)) { + final T otherMarker = possibleSubordinate.getChild(1).getHead(); - if(subgroups.get(marker) > subgroups.get(otherMarker)) { + if (subgroups.get(marker) > subgroups.get(otherMarker)) { subgroupContents.prependChild(contents.pop()); } else { break; @@ -101,7 +101,7 @@ public class DelimiterGroup<T> { } } - Tree<T> subgroup = new Tree<>(chars.subgroup, subgroupContents, new Tree<>(marker)); + final Tree<T> subgroup = new Tree<>(chars.subgroup, subgroupContents, new Tree<>(marker)); //System.out.println("\tTRACE: generated subgroup\n" + subgroup + "\n\n"); contents.push(subgroup); @@ -111,26 +111,26 @@ public class DelimiterGroup<T> { /** * Convert this group into a tree. - * + * * @param closer * The item that closed this group. - * + * * @param chars * The characteristics for building the tree. - * + * * @return This group as a tree. */ - public ITree<T> toTree(T closer, SequenceCharacteristics<T> chars) { - if(impliedSubgroups.containsKey(closer)) { + public ITree<T> toTree(final T closer, final SequenceCharacteristics<T> chars) { + if (impliedSubgroups.containsKey(closer)) { markSubgroup(impliedSubgroups.get(closer), chars); } - ITree<T> res = new Tree<>(chars.contents); + final ITree<T> res = new Tree<>(chars.contents); - if(contents.isEmpty()) { + if (contents.isEmpty()) { currentGroup.forEach(res::addChild); } else { - while(!contents.isEmpty()) { + while (!contents.isEmpty()) { res.prependChild(contents.poll()); } @@ -142,7 +142,7 @@ public class DelimiterGroup<T> { @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("OpenGroup [contents="); builder.append(contents); @@ -157,34 +157,30 @@ public class DelimiterGroup<T> { /** * Check if a group is excluded at the top level of this group. - * + * * @param groupName * The group to check. - * + * * @return Whether or not the provided group is excluded. */ - public boolean excludes(T groupName) { + public boolean excludes(final T groupName) { return topLevelExclusions.contains(groupName); } /** * Check if the provided delimiter would close this group. - * + * * @param del * The string to check as a closing delimiter. - * + * * @return Whether or not the provided delimiter closes this * group. */ - public boolean isClosing(T del) { - if(closingDelimiters.contains(del)) { - return true; - } + public boolean isClosing(final T del) { + if (closingDelimiters.contains(del)) return true; - for(BiPredicate<T, T[]> pred : predClosers) { - if(pred.test(del, params)) { - return true; - } + for (final BiPredicate<T, T[]> pred : predClosers) { + if (pred.test(del, params)) return true; } return closingDelimiters.contains(del); @@ -192,7 +188,7 @@ public class DelimiterGroup<T> { /** * Get the name of the group this is an instance of. - * + * * @return The name of the group this is an instance of. */ public T getName() { @@ -201,7 +197,7 @@ public class DelimiterGroup<T> { /** * Get the groups that aren't allowed at all in this group. - * + * * @return The groups that aren't allowed at all in this group. */ public Set<T> getNestingExclusions() { @@ -211,7 +207,7 @@ public class DelimiterGroup<T> { /** * Get the groups that are allowed to open anywhere inside this * group. - * + * * @return The groups allowed to open anywhere inside this * group. */ @@ -221,36 +217,32 @@ public class DelimiterGroup<T> { /** * Checks if a given token marks a subgroup. - * + * * @param tok * The token to check. - * + * * @return Whether or not the token marks a subgroup. */ - public boolean marksSubgroup(T tok) { + public boolean marksSubgroup(final T tok) { return subgroups.containsKey(tok); } /** * Checks if a given token opens a group. - * + * * @param marker * The token to check. - * + * * @return The name of the group T opens, or null if it doesn't * open one. */ - public IPair<T, T[]> doesOpen(T marker) { - if(openDelimiters.containsKey(marker)) { - return new Pair<>(openDelimiters.get(marker), null); - } + public IPair<T, T[]> doesOpen(final T marker) { + if (openDelimiters.containsKey(marker)) return new Pair<>(openDelimiters.get(marker), null); - for(Function<T, IPair<T, T[]>> pred : predOpeners) { - IPair<T, T[]> par = pred.apply(marker); + for (final Function<T, IPair<T, T[]>> pred : predOpeners) { + final IPair<T, T[]> par = pred.apply(marker); - if(par.getLeft() != null) { - return par; - } + if (par.getLeft() != null) return par; } return new Pair<>(null, null); @@ -258,7 +250,7 @@ public class DelimiterGroup<T> { /** * Check if this group starts a new nesting scope. - * + * * @return Whether this group starts a new nesting scope. */ public boolean isForgetful() { @@ -274,48 +266,48 @@ public class DelimiterGroup<T> { /* * The delimiters that open groups at the top level of this group. */ - private Map<T, T> openDelimiters; + private final Map<T, T> openDelimiters; /* * The delimiters that open groups inside of this group. */ - private Map<T, T> nestedOpenDelimiters; + private final Map<T, T> nestedOpenDelimiters; /* * The delimiters that close this group. */ - private Set<T> closingDelimiters; + private final Set<T> closingDelimiters; /* * The groups that can't occur in the top level of this group. */ - private Set<T> topLevelExclusions; + private final Set<T> topLevelExclusions; /* * The groups that can't occur anywhere inside this group. */ - private Set<T> groupExclusions; + private final Set<T> groupExclusions; /* * Mapping from sub-group delimiters, to any sub-groups enclosed in * them. */ - private Map<T, Integer> subgroups; + private final Map<T, Integer> subgroups; /* * Subgroups implied by a particular closing delimiter */ - private Map<T, T> impliedSubgroups; + private final Map<T, T> impliedSubgroups; /* * Allows more complex openings */ - private List<Function<T, IPair<T, T[]>>> predOpeners; + private final List<Function<T, IPair<T, T[]>>> predOpeners; /* * Allow more complex closings */ - private List<BiPredicate<T, T[]>> predClosers; + private final List<BiPredicate<T, T[]>> predClosers; /* * Whether or not this group starts a new nesting set. @@ -324,12 +316,12 @@ public class DelimiterGroup<T> { /** * Create a new empty delimiter group. - * + * * @param name * The name of the delimiter group */ - public DelimiterGroup(T name) { - if(name == null) throw new NullPointerException("Group name must not be null"); + public DelimiterGroup(final T name) { + if (name == null) throw new NullPointerException("Group name must not be null"); groupName = name; @@ -350,25 +342,25 @@ public class DelimiterGroup<T> { /** * Adds one or more delimiters that close this group. - * + * * @param closers * Delimiters that close this group. */ @SafeVarargs - public final void addClosing(T... closers) { - List<T> closerList = Arrays.asList(closers); + public final void addClosing(final T... closers) { + final List<T> closerList = Arrays.asList(closers); - for(T closer : closerList) { - if(closer == null) { + for (final T closer : closerList) { + if (closer == null) throw new NullPointerException("Closing delimiter must not be null"); - } else if(closer.equals("")) { + else if (closer.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same * type. */ throw new IllegalArgumentException("Empty string is not a valid exclusion"); - } else { + else { closingDelimiters.add(closer); } } @@ -377,23 +369,23 @@ public class DelimiterGroup<T> { /** * Adds one or more groups that cannot occur in the top level of this * group. - * + * * @param exclusions * The groups forbidden in the top level of this group. */ @SafeVarargs - public final void addTopLevelForbid(T... exclusions) { - for(T exclusion : exclusions) { - if(exclusion == null) { + public final void addTopLevelForbid(final T... exclusions) { + for (final T exclusion : exclusions) { + if (exclusion == null) throw new NullPointerException("Exclusion must not be null"); - } else if(exclusion.equals("")) { + else if (exclusion.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same * type. */ throw new IllegalArgumentException("Empty string is not a valid exclusion"); - } else { + else { topLevelExclusions.add(exclusion); } } @@ -401,23 +393,23 @@ public class DelimiterGroup<T> { /** * Adds one or more groups that cannot occur at all in this group. - * + * * @param exclusions * The groups forbidden inside this group. */ @SafeVarargs - public final void addGroupForbid(T... exclusions) { - for(T exclusion : exclusions) { - if(exclusion == null) { + public final void addGroupForbid(final T... exclusions) { + for (final T exclusion : exclusions) { + if (exclusion == null) throw new NullPointerException("Exclusion must not be null"); - } else if(exclusion.equals("")) { + else if (exclusion.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same * type. */ throw new IllegalArgumentException("Empty string is not a valid exclusion"); - } else { + else { groupExclusions.add(exclusion); } } @@ -425,85 +417,78 @@ public class DelimiterGroup<T> { /** * Adds sub-group markers to this group. - * + * * @param subgroup * The token to mark a sub-group. - * + * * @param priority * The priority of this sub-group. */ - public void addSubgroup(T subgroup, int priority) { - if(subgroup == null) { - throw new NullPointerException("Subgroup marker must not be null"); - } + public void addSubgroup(final T subgroup, final int priority) { + if (subgroup == null) throw new NullPointerException("Subgroup marker must not be null"); subgroups.put(subgroup, priority); } /** * Adds a marker that opens a group at the top level of this group. - * + * * @param opener * The marker that opens the group. - * + * * @param group * The group opened by the marker. */ - public void addOpener(T opener, T group) { - if(opener == null) { + public void addOpener(final T opener, final T group) { + if (opener == null) throw new NullPointerException("Opener must not be null"); - } else if(group == null) { - throw new NullPointerException("Group to open must not be null"); - } + else if (group == null) throw new NullPointerException("Group to open must not be null"); openDelimiters.put(opener, group); } /** * Adds a marker that opens a group inside of this group. - * + * * @param opener * The marker that opens the group. - * + * * @param group * The group opened by the marker. */ - public void addNestedOpener(T opener, T group) { - if(opener == null) { + public void addNestedOpener(final T opener, final T group) { + if (opener == null) throw new NullPointerException("Opener must not be null"); - } else if(group == null) { - throw new NullPointerException("Group to open must not be null"); - } + else if (group == null) throw new NullPointerException("Group to open must not be null"); nestedOpenDelimiters.put(opener, group); } /** * Mark a closing delimiter as implying a subgroup. - * + * * @param closer * The closing delimiter. - * + * * @param subgroup * The subgroup to imply. */ - public void implySubgroup(T closer, T subgroup) { - if(closer == null) { + public void implySubgroup(final T closer, final T subgroup) { + if (closer == null) throw new NullPointerException("Closer must not be null"); - } else if(subgroup == null) { + else if (subgroup == null) throw new NullPointerException("Subgroup must not be null"); - } else if(!closingDelimiters.contains(closer)) { + else if (!closingDelimiters.contains(closer)) throw new IllegalArgumentException(String.format("No closing delimiter '%s' defined", closer)); - } else if(!subgroups.containsKey(subgroup)) { + else if (!subgroups.containsKey(subgroup)) throw new IllegalArgumentException(String.format("No subgroup '%s' defined", subgroup)); - } impliedSubgroups.put(closer, subgroup); } @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("("); @@ -512,26 +497,26 @@ public class DelimiterGroup<T> { builder.append("], "); builder.append("closingDelimiters=["); - for(T closer : closingDelimiters) { + for (final T closer : closingDelimiters) { builder.append(closer + ","); } builder.deleteCharAt(builder.length() - 1); builder.append("]"); - if(topLevelExclusions != null && !topLevelExclusions.isEmpty()) { + if (topLevelExclusions != null && !topLevelExclusions.isEmpty()) { builder.append(", "); builder.append("topLevelExclusions=["); - for(T exclusion : topLevelExclusions) { + for (final T exclusion : topLevelExclusions) { builder.append(exclusion + ","); } builder.deleteCharAt(builder.length() - 1); builder.append("]"); } - if(groupExclusions != null && !groupExclusions.isEmpty()) { + if (groupExclusions != null && !groupExclusions.isEmpty()) { builder.append(", "); builder.append("groupExclusions=["); - for(T exclusion : groupExclusions) { + for (final T exclusion : groupExclusions) { builder.append(exclusion + ","); } builder.deleteCharAt(builder.length() - 1); @@ -545,47 +530,47 @@ public class DelimiterGroup<T> { /** * Open an instance of this group. - * + * * @param opener * The item that opened this group. - * + * * @param parms * The parameters that opened this group - * + * * @return An opened instance of this group. */ - public OpenGroup open(T opener, T[] parms) { + public OpenGroup open(final T opener, final T[] parms) { return new OpenGroup(opener, parms); } /** * Adds a predicated opener to the top level of this group. - * + * * @param pred * The predicate that defines the opener and its * parameters. */ - public void addPredOpener(Function<T, IPair<T, T[]>> pred) { + public void addPredOpener(final Function<T, IPair<T, T[]>> pred) { predOpeners.add(pred); } /** * Adds a predicated closer to the top level of this group. - * + * * @param pred * The predicate that defines the closer. */ - public void addPredCloser(BiPredicate<T, T[]> pred) { + public void addPredCloser(final BiPredicate<T, T[]> pred) { predClosers.add(pred); } /** * Set whether or not this group starts a new nesting set. - * + * * @param forgetful * Whether this group starts a new nesting set. */ - public void setForgetful(boolean forgetful) { + public void setForgetful(final boolean forgetful) { this.forgetful = forgetful; } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java index dc94686..4b29949 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java @@ -4,29 +4,29 @@ import java.util.function.BiPredicate; /** * A predicated closer for use with {@link RegexOpener}. - * + * * @author bjculkin * */ public class RegexCloser implements BiPredicate<String, String[]> { - private String rep; + private final String rep; /** * Create a new regex closer. - * + * * @param closer * The format string to use for closing. */ - public RegexCloser(String closer) { + public RegexCloser(final String closer) { rep = closer; } @Override - public boolean test(String closer, String[] params) { + public boolean test(final String closer, final String[] params) { /* * Confirm passing an array instead of a single var-arg. */ - String work = String.format(rep, (Object[]) params); + final String work = String.format(rep, (Object[]) params); return work.equals(closer); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java index 7b4aac0..98c1dc1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java @@ -1,46 +1,46 @@ package bjc.utils.parserutils.delims; -import bjc.utils.data.IPair; -import bjc.utils.data.Pair; - import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; +import bjc.utils.data.IPair; +import bjc.utils.data.Pair; + /** * A predicated opener for use with {@link RegexOpener} - * + * * @author bjculkin * */ public class RegexOpener implements Function<String, IPair<String, String[]>> { - private String name; + private final String name; - private Pattern patt; + private final Pattern patt; /** * Create a new regex opener. - * + * * @param groupName * The name of the opened group. - * + * * @param groupRegex * The regex that matches the opener. */ - public RegexOpener(String groupName, String groupRegex) { + public RegexOpener(final String groupName, final String groupRegex) { name = groupName; patt = Pattern.compile(groupRegex); } @Override - public IPair<String, String[]> apply(String str) { - Matcher m = patt.matcher(str); + public IPair<String, String[]> apply(final String str) { + final Matcher m = patt.matcher(str); if (m.matches()) { - int numGroups = m.groupCount(); + final int numGroups = m.groupCount(); - String[] parms = new String[numGroups + 1]; + final String[] parms = new String[numGroups + 1]; for (int i = 0; i <= numGroups; i++) { parms[i] = m.group(i); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java index 5dcda2d..882b4c5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java @@ -2,7 +2,7 @@ package bjc.utils.parserutils.delims; /** * Marks the parameters for building a sequence tree. - * + * * @author EVE * * @param <T> @@ -27,7 +27,7 @@ public class SequenceCharacteristics<T> { /** * Create a new set of parameters for building a tree. - * + * * @param root * The root marker. * @param contents @@ -35,7 +35,7 @@ public class SequenceCharacteristics<T> { * @param subgroup * The subgroup marker. */ - public SequenceCharacteristics(T root, T contents, T subgroup) { + public SequenceCharacteristics(final T root, final T contents, final T subgroup) { this.root = root; this.contents = contents; this.subgroup = subgroup; @@ -46,39 +46,39 @@ public class SequenceCharacteristics<T> { final int prime = 31; int result = 1; - result = prime * result + ((contents == null) ? 0 : contents.hashCode()); - result = prime * result + ((root == null) ? 0 : root.hashCode()); - result = prime * result + ((subgroup == null) ? 0 : subgroup.hashCode()); + result = prime * result + (contents == null ? 0 : contents.hashCode()); + result = prime * result + (root == null ? 0 : root.hashCode()); + result = prime * result + (subgroup == null ? 0 : subgroup.hashCode()); return result; } @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof SequenceCharacteristics)) return false; + public boolean equals(final Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof SequenceCharacteristics)) return false; - SequenceCharacteristics<?> other = (SequenceCharacteristics<?>) obj; + final SequenceCharacteristics<?> other = (SequenceCharacteristics<?>) obj; - if(contents == null) { - if(other.contents != null) return false; - } else if(!contents.equals(other.contents)) return false; + if (contents == null) { + if (other.contents != null) return false; + } else if (!contents.equals(other.contents)) return false; - if(root == null) { - if(other.root != null) return false; - } else if(!root.equals(other.root)) return false; + if (root == null) { + if (other.root != null) return false; + } else if (!root.equals(other.root)) return false; - if(subgroup == null) { - if(other.subgroup != null) return false; - } else if(!subgroup.equals(other.subgroup)) return false; + if (subgroup == null) { + if (other.subgroup != null) return false; + } else if (!subgroup.equals(other.subgroup)) return false; return true; } @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("SequenceCharacteristics [root="); builder.append(root == null ? "(null)" : root); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java index e723123..48d85c1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java @@ -1,5 +1,14 @@ package bjc.utils.parserutils.delims; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multiset; + import bjc.utils.data.IPair; import bjc.utils.data.ITree; import bjc.utils.data.Tree; @@ -9,18 +18,9 @@ import bjc.utils.esodata.Stack; import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.StringUtils; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multiset; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - /** * Convert linear sequences into trees that represent group structure. - * + * * @author EVE * * @param <T> @@ -30,7 +30,7 @@ public class SequenceDelimiter<T> { /* * Mapping from group names to actual groups. */ - private Map<T, DelimiterGroup<T>> groups; + private final Map<T, DelimiterGroup<T>> groups; private DelimiterGroup<T> initialGroup; @@ -44,64 +44,62 @@ public class SequenceDelimiter<T> { /** * Convert a linear sequence into a tree that matches the delimiter * structure. - * + * * Essentially, creates a parse tree of the expression against the * following grammar while obeying the defined grouping rules. - * + * * <pre> * <tree> -> (<data> | <subgroup> | <group>)* * <subgroup> -> <tree> <marker> * <group> -> <open> <tree> <close> - * + * * <data> -> STRING * <open> -> STRING * <close> -> STRING * <marker> -> STRING * </pre> - * + * * @param chars * The parameters on how to mark certain portions of the * tree. * @param seq * The sequence to delimit. - * + * * @return The sequence as a tree that matches its group structure. Each * node in the tree is either a data node, a subgroup node, or a * group node. - * + * * A data node is a leaf node whose data is the string it * represents. - * + * * A subgroup node is a node with two children, and the name of * the sub-group as its label. The first child is the contents * of the sub-group, and the second is the marker that started * the subgroup. The marker is a leaf node labeled with its * contents, and the contents contains a recursive tree. - * + * * A group node is a node with three children, and the name of * the group as its label. The first child is the opening * delimiter, the second is the group contents, and the third is * the closing delimiter. The delimiters are leaf nodes labeled * with their contents, while the group node contains a * recursive tree. - * + * * @throws DelimiterException * Thrown if something went wrong during sequence * delimitation. - * + * */ - public ITree<T> delimitSequence(SequenceCharacteristics<T> chars, @SuppressWarnings("unchecked") T... seq) - throws DelimiterException { - if(initialGroup == null) { + public ITree<T> delimitSequence(final SequenceCharacteristics<T> chars, + @SuppressWarnings("unchecked") final T... seq) throws DelimiterException { + if (initialGroup == null) throw new NullPointerException("Initial group must be specified."); - } else if(chars == null) { - throw new NullPointerException("Sequence characteristics must not be null"); - } + else if (chars == null) throw new NullPointerException("Sequence characteristics must not be null"); /* * The stack of opened and not yet closed groups. */ - Stack<DelimiterGroup<T>.OpenGroup> groupStack = new SimpleStack<>(); + final Stack<DelimiterGroup<T>.OpenGroup> groupStack = new SimpleStack<>(); /* * Open initial group. @@ -111,34 +109,34 @@ public class SequenceDelimiter<T> { /* * Groups that aren't allowed to be opened at the moment. */ - Stack<Multiset<T>> forbiddenDelimiters = new SimpleStack<>(); + final Stack<Multiset<T>> forbiddenDelimiters = new SimpleStack<>(); forbiddenDelimiters.push(HashMultiset.create()); /* * Groups that are allowed to be opened at the moment. */ - Stack<Multimap<T, T>> allowedDelimiters = new SimpleStack<>(); + final Stack<Multimap<T, T>> allowedDelimiters = new SimpleStack<>(); allowedDelimiters.push(HashMultimap.create()); /* * Map of who forbid what for debugging purposes. */ - IMap<T, T> whoForbid = new PushdownMap<>(); + final IMap<T, T> whoForbid = new PushdownMap<>(); - for(int i = 0; i < seq.length; i++) { - T tok = seq[i]; + for (int i = 0; i < seq.length; i++) { + final T tok = seq[i]; - IPair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok); + final IPair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok); T possibleOpen = possibleOpenPar.getLeft(); - if(possibleOpen == null) { + if (possibleOpen == null) { /* * Handle nested openers. - * + * * Local openers take priority over nested ones * if they overlap. */ - if(allowedDelimiters.top().containsKey(tok)) { + if (allowedDelimiters.top().containsKey(tok)) { possibleOpen = allowedDelimiters.top().get(tok).iterator().next(); } } @@ -146,29 +144,29 @@ public class SequenceDelimiter<T> { /* * If we have an opening delimiter, handle it. */ - if(possibleOpen != null) { - DelimiterGroup<T> group = groups.get(possibleOpen); + if (possibleOpen != null) { + final DelimiterGroup<T> group = groups.get(possibleOpen); /* * Error on groups that can't open in this * context. - * + * * This means groups that can't occur at the * top-level of this group, as well as nested * exclusions from all enclosing groups. */ - if(isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) { - StringBuilder msgBuilder = new StringBuilder(); + if (isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) { + final StringBuilder msgBuilder = new StringBuilder(); T forbiddenBy; - if(whoForbid.containsKey(tok)) { + if (whoForbid.containsKey(tok)) { forbiddenBy = whoForbid.get(tok); } else { forbiddenBy = groupStack.top().getName(); } - String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then"); + final String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then"); msgBuilder.append("Group '"); msgBuilder.append(group); @@ -184,13 +182,13 @@ public class SequenceDelimiter<T> { /* * Add an open group. */ - DelimiterGroup<T>.OpenGroup open = group.open(tok, possibleOpenPar.getRight()); + final DelimiterGroup<T>.OpenGroup open = group.open(tok, possibleOpenPar.getRight()); groupStack.push(open); /* * Handle 'forgetful' groups that reset nesting */ - if(open.isForgetful()) { + if (open.isForgetful()) { allowedDelimiters.push(HashMultimap.create()); forbiddenDelimiters.push(HashMultiset.create()); } @@ -198,33 +196,33 @@ public class SequenceDelimiter<T> { /* * Add the nested opens from this group. */ - Multimap<T, T> currentAllowed = allowedDelimiters.top(); - for(Entry<T, T> opener : open.getNestingOpeners().entrySet()) { + final Multimap<T, T> currentAllowed = allowedDelimiters.top(); + for (final Entry<T, T> opener : open.getNestingOpeners().entrySet()) { currentAllowed.put(opener.getKey(), opener.getValue()); } /* * Add the nested exclusions from this group */ - Multiset<T> currentForbidden = forbiddenDelimiters.top(); - for(T exclusion : open.getNestingExclusions()) { + final Multiset<T> currentForbidden = forbiddenDelimiters.top(); + for (final T exclusion : open.getNestingExclusions()) { currentForbidden.add(exclusion); whoForbid.put(exclusion, possibleOpen); } - } else if(!groupStack.empty() && groupStack.top().isClosing(tok)) { + } else if (!groupStack.empty() && groupStack.top().isClosing(tok)) { /* * Close the group. */ - DelimiterGroup<T>.OpenGroup closed = groupStack.pop(); + final DelimiterGroup<T>.OpenGroup closed = groupStack.pop(); groupStack.top().addItem(closed.toTree(tok, chars)); /* * Remove nested exclusions from this group. */ - Multiset<T> currentForbidden = forbiddenDelimiters.top(); - for(T excludedGroup : closed.getNestingExclusions()) { + final Multiset<T> currentForbidden = forbiddenDelimiters.top(); + for (final T excludedGroup : closed.getNestingExclusions()) { currentForbidden.remove(excludedGroup); whoForbid.remove(excludedGroup); @@ -233,19 +231,19 @@ public class SequenceDelimiter<T> { /* * Remove the nested opens from this group. */ - Multimap<T, T> currentAllowed = allowedDelimiters.top(); - for(Entry<T, T> closer : closed.getNestingOpeners().entrySet()) { + final Multimap<T, T> currentAllowed = allowedDelimiters.top(); + for (final Entry<T, T> closer : closed.getNestingOpeners().entrySet()) { currentAllowed.remove(closer.getKey(), closer.getValue()); } /* * Handle 'forgetful' groups that reset nesting. */ - if(closed.isForgetful()) { + if (closed.isForgetful()) { allowedDelimiters.drop(); forbiddenDelimiters.drop(); } - } else if(!groupStack.empty() && groupStack.top().marksSubgroup(tok)) { + } else if (!groupStack.empty() && groupStack.top().marksSubgroup(tok)) { groupStack.top().markSubgroup(tok, chars); } else { groupStack.top().addItem(new Tree<>(tok)); @@ -255,14 +253,15 @@ public class SequenceDelimiter<T> { /* * Error if not all groups were closed. */ - if(groupStack.size() > 1) { - DelimiterGroup<T>.OpenGroup group = groupStack.top(); + if (groupStack.size() > 1) { + final DelimiterGroup<T>.OpenGroup group = groupStack.top(); - StringBuilder msgBuilder = new StringBuilder(); + final StringBuilder msgBuilder = new StringBuilder(); - String closingDelims = StringUtils.toEnglishList(group.getNestingExclusions().toArray(), false); + final String closingDelims = StringUtils.toEnglishList(group.getNestingExclusions().toArray(), + false); - String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then"); + final String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then"); msgBuilder.append("Unclosed group '"); msgBuilder.append(group.getName()); @@ -277,35 +276,34 @@ public class SequenceDelimiter<T> { return groupStack.pop().toTree(chars.root, chars); } - private boolean isForbidden(Stack<DelimiterGroup<T>.OpenGroup> groupStack, - Stack<Multiset<T>> forbiddenDelimiters, T groupName) { + private boolean isForbidden(final Stack<DelimiterGroup<T>.OpenGroup> groupStack, + final Stack<Multiset<T>> forbiddenDelimiters, final T groupName) { boolean localForbid; - if(groupStack.empty()) + if (groupStack.empty()) { localForbid = false; - else + } else { localForbid = groupStack.top().excludes(groupName); + } return localForbid || forbiddenDelimiters.top().contains(groupName); } /** * Add a delimiter group. - * + * * @param group * The delimiter group. */ - public void addGroup(DelimiterGroup<T> group) { - if(group == null) { - throw new NullPointerException("Group must not be null"); - } + public void addGroup(final DelimiterGroup<T> group) { + if (group == null) throw new NullPointerException("Group must not be null"); groups.put(group.groupName, group); } /** * Creates and adds a delimiter group using the provided settings. - * + * * @param openers * The tokens that open this group * @param groupName @@ -313,31 +311,31 @@ public class SequenceDelimiter<T> { * @param closers * The tokens that close this group */ - public void addGroup(T[] openers, T groupName, @SuppressWarnings("unchecked") T... closers) { - DelimiterGroup<T> group = new DelimiterGroup<>(groupName); + public void addGroup(final T[] openers, final T groupName, @SuppressWarnings("unchecked") final T... closers) { + final DelimiterGroup<T> group = new DelimiterGroup<>(groupName); group.addClosing(closers); addGroup(group); - for(T open : openers) { + for (final T open : openers) { group.addOpener(open, groupName); } } @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("SequenceDelimiter ["); - if(groups != null) { + if (groups != null) { builder.append("groups="); builder.append(groups); builder.append(","); } - if(initialGroup != null) { + if (initialGroup != null) { builder.append("initialGroup="); builder.append(initialGroup); } @@ -349,11 +347,11 @@ public class SequenceDelimiter<T> { /** * Set the initial group of this delimiter. - * + * * @param initialGroup * The initial group of this delimiter. */ - public void setInitialGroup(DelimiterGroup<T> initialGroup) { + public void setInitialGroup(final DelimiterGroup<T> initialGroup) { this.initialGroup = initialGroup; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java index 6db1c98..e3eeea5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java @@ -4,7 +4,7 @@ import bjc.utils.data.ITree; /** * A sequence delimiter specialized for strings. - * + * * @author EVE * */ @@ -14,18 +14,18 @@ public class StringDelimiter extends SequenceDelimiter<String> { * Override of * {@link SequenceDelimiter#delimitSequence(SequenceCharacteristics, Object...)} * for ease of use for strings. - * + * * @param seq * The sequence to delimit. - * + * * @return The sequence as a tree. - * + * * @throws DelimiterException * if something went wrong with delimiting the sequence. - * + * * @see SequenceDelimiter */ - public ITree<String> delimitSequence(String... seq) throws DelimiterException { + public ITree<String> delimitSequence(final String... seq) throws DelimiterException { return super.delimitSequence(new SequenceCharacteristics<>("root", "contents", "subgroup"), seq); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java index ccc823d..b30cec1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java @@ -6,7 +6,7 @@ import java.util.regex.Pattern; /** * Simple implementation of {@link TokenSplitter} - * + * * @author EVE */ @Deprecated @@ -15,7 +15,7 @@ public class SimpleTokenSplitter implements TokenSplitter { * This string is a format template for the delimiter matching regex * * It does two things: - * + * * <ol> <li> Match to the left of the provided delimiter by positive * lookahead </li> <li> Match to the right of the provided delimiter by * positive lookbehind </li> </ol> @@ -52,9 +52,9 @@ public class SimpleTokenSplitter implements TokenSplitter { /* * These represent info for debugging. */ - private Set<String> delimSet; - private Set<String> multidelimSet; - private Set<String> exclusionSet; + private final Set<String> delimSet; + private final Set<String> multidelimSet; + private final Set<String> exclusionSet; /** * Create a new token splitter. @@ -66,14 +66,14 @@ public class SimpleTokenSplitter implements TokenSplitter { } @Override - public String[] split(String inp) { - if(compPatt == null) throw new IllegalStateException("Token splitter has not been compiled yet"); + public String[] split(final String inp) { + if (compPatt == null) throw new IllegalStateException("Token splitter has not been compiled yet"); /* * Don't split something that we should exclude from being * split. */ - if(exclusionPatt.matcher(inp).matches()) return new String[] { inp }; + if (exclusionPatt.matcher(inp).matches()) return new String[] { inp }; return compPatt.split(inp); } @@ -88,14 +88,14 @@ public class SimpleTokenSplitter implements TokenSplitter { * @param delims * The delimiters to match on. */ - public void addDelimiter(String... delims) { - for(String delim : delims) { - if(delim == null) throw new NullPointerException("Delim must not be null"); + public void addDelimiter(final String... delims) { + for (final String delim : delims) { + if (delim == null) throw new NullPointerException("Delim must not be null"); - String quoteDelim = Pattern.quote(delim); - String delimPat = String.format(WITH_DELIM, quoteDelim); + final String quoteDelim = Pattern.quote(delim); + final String delimPat = String.format(WITH_DELIM, quoteDelim); - if(currPatt == null) { + if (currPatt == null) { currPatt = new StringBuilder(); currExclusionPatt = new StringBuilder(); @@ -119,13 +119,13 @@ public class SimpleTokenSplitter implements TokenSplitter { * @param delims * The delimiter to split on. */ - public void addMultiDelimiter(String... delims) { - for(String delim : delims) { - if(delim == null) throw new NullPointerException("Delim must not be null"); + public void addMultiDelimiter(final String... delims) { + for (final String delim : delims) { + if (delim == null) throw new NullPointerException("Delim must not be null"); - String delimPat = String.format(WITH_MULTI_DELIM, "(?:" + delim + ")"); + final String delimPat = String.format(WITH_MULTI_DELIM, "(?:" + delim + ")"); - if(currPatt == null) { + if (currPatt == null) { currPatt = new StringBuilder(); currExclusionPatt = new StringBuilder(); @@ -147,11 +147,11 @@ public class SimpleTokenSplitter implements TokenSplitter { * @param delims * The regex to not splitting matching strings. */ - public void addNonMatcher(String... delims) { - for(String delim : delims) { - if(delim == null) throw new NullPointerException("Delim must not be null"); + public void addNonMatcher(final String... delims) { + for (final String delim : delims) { + if (delim == null) throw new NullPointerException("Delim must not be null"); - if(currPatt == null) { + if (currPatt == null) { currPatt = new StringBuilder(); currExclusionPatt = new StringBuilder(); @@ -170,8 +170,12 @@ public class SimpleTokenSplitter implements TokenSplitter { * Makes this splitter ready to use. */ public void compile() { - if(currPatt == null) currPatt = new StringBuilder(); - if(currExclusionPatt == null) currExclusionPatt = new StringBuilder(); + if (currPatt == null) { + currPatt = new StringBuilder(); + } + if (currExclusionPatt == null) { + currExclusionPatt = new StringBuilder(); + } compPatt = Pattern.compile(currPatt.toString()); exclusionPatt = Pattern.compile(currExclusionPatt.toString()); @@ -179,52 +183,52 @@ public class SimpleTokenSplitter implements TokenSplitter { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append("SimpleTokenSplitter ["); - if(currPatt != null) { + if (currPatt != null) { builder.append("currPatt="); builder.append(currPatt); builder.append("\n\t, "); } - if(currExclusionPatt != null) { + if (currExclusionPatt != null) { builder.append("currExclusionPatt="); builder.append(currExclusionPatt); builder.append("\n\t, "); } - if(compPatt != null) { + if (compPatt != null) { builder.append("compPatt="); builder.append(compPatt); builder.append("\n\t, "); } - if(exclusionPatt != null) { + if (exclusionPatt != null) { builder.append("exclusionPatt="); builder.append(exclusionPatt); builder.append("\n\t, "); } - if(delimSet != null) { + if (delimSet != null) { builder.append("delimSet="); builder.append(delimSet); builder.append("\n\t, "); } - if(multidelimSet != null) { + if (multidelimSet != null) { builder.append("multidelimSet="); builder.append(multidelimSet); builder.append("\n\t, "); } - if(exclusionSet != null) { + if (exclusionSet != null) { builder.append("exclusionSet="); builder.append(exclusionSet); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java index 04551a7..6fd9f7b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java @@ -14,7 +14,7 @@ public interface TokenSplitter { * <p> * The splitter must be compiled first. * </p> - * + * * @param inp * The string to split. * diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TwoLevelSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TwoLevelSplitter.java index 1d6d0a2..92b9de0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TwoLevelSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitter/TwoLevelSplitter.java @@ -6,22 +6,22 @@ import java.util.regex.Pattern; /** * Implementation of a splitter that runs in two passes. - * + * * This is useful because {@link SimpleTokenSplitter} doesn't like handling both * <= and = without mangling them. - * + * * The first pass splits on compound operators, which are built up from simple * operators. - * + * * The second pass removes simple operators. - * + * * @author EVE * */ @Deprecated public class TwoLevelSplitter implements TokenSplitter { - private SimpleTokenSplitter high; - private SimpleTokenSplitter low; + private final SimpleTokenSplitter high; + private final SimpleTokenSplitter low; /** * Create a new two level splitter. @@ -32,15 +32,15 @@ public class TwoLevelSplitter implements TokenSplitter { } @Override - public String[] split(String inp) { - List<String> ret = new ArrayList<>(); + public String[] split(final String inp) { + final List<String> ret = new ArrayList<>(); - String[] partials = high.split(inp); + final String[] partials = high.split(inp); - for(String partial : partials) { - String[] finals = low.split(partial); + for (final String partial : partials) { + final String[] finals = low.split(partial); - for(String fin : finals) { + for (final String fin : finals) { ret.add(fin); } } @@ -50,12 +50,12 @@ public class TwoLevelSplitter implements TokenSplitter { /** * Adds compound operators to split on. - * + * * @param delims * The compound operators to split on. */ - public void addCompoundDelim(String... delims) { - for(String delim : delims) { + public void addCompoundDelim(final String... delims) { + for (final String delim : delims) { high.addDelimiter(delim); low.addNonMatcher(Pattern.quote(delim)); @@ -64,24 +64,24 @@ public class TwoLevelSplitter implements TokenSplitter { /** * Adds simple operators to split on. - * + * * @param delims * The simple operators to split on. */ - public void addSimpleDelim(String... delims) { - for(String delim : delims) { + public void addSimpleDelim(final String... delims) { + for (final String delim : delims) { low.addDelimiter(delim); } } /** * Adds repeated compound operators to split on. - * + * * @param delims * The repeated compound operators to split on. */ - public void addCompoundMulti(String... delims) { - for(String delim : delims) { + public void addCompoundMulti(final String... delims) { + for (final String delim : delims) { high.addMultiDelimiter(delim); low.addNonMatcher("(?:" + delim + ")+"); @@ -90,12 +90,12 @@ public class TwoLevelSplitter implements TokenSplitter { /** * Adds simple compound operators to split on. - * + * * @param delims * The repeated simple operators to split on. */ - public void addSimpleMulti(String... delims) { - for(String delim : delims) { + public void addSimpleMulti(final String... delims) { + for (final String delim : delims) { low.addMultiDelimiter(delim); } } @@ -106,8 +106,8 @@ public class TwoLevelSplitter implements TokenSplitter { * @param exclusions * The regexes to exclude matches for. */ - public void exclude(String... exclusions) { - for(String exclusion : exclusions) { + public void exclude(final String... exclusions) { + for (final String exclusion : exclusions) { high.addNonMatcher(exclusion); low.addNonMatcher(exclusion); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ChainTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ChainTokenSplitter.java index 2ecadaf..75afd34 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ChainTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ChainTokenSplitter.java @@ -6,12 +6,12 @@ import bjc.utils.functypes.ID; /** * A token splitter that chains several other splitters together. - * + * * @author EVE * */ public class ChainTokenSplitter implements TokenSplitter { - private IList<TokenSplitter> spliters; + private final IList<TokenSplitter> spliters; /** * Create a new chain token splitter. @@ -22,27 +22,27 @@ public class ChainTokenSplitter implements TokenSplitter { /** * Append a series of splitters to the chain. - * + * * @param splitters * The splitters to append to the chain. */ - public void appendSplitters(TokenSplitter... splitters) { + public void appendSplitters(final TokenSplitter... splitters) { spliters.addAll(splitters); } /** * Prepend a series of splitters to the chain. - * + * * @param splitters * The splitters to append to the chain. */ - public void prependSplitters(TokenSplitter... splitters) { + public void prependSplitters(final TokenSplitter... splitters) { spliters.prependAll(splitters); } @Override - public IList<String> split(String input) { - IList<String> initList = new FunctionalList<>(input); + public IList<String> split(final String input) { + final IList<String> initList = new FunctionalList<>(input); return spliters.reduceAux(initList, (splitter, strangs) -> { return strangs.flatMap(splitter::split); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ConfigurableTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ConfigurableTokenSplitter.java index 021821a..b9503bc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ConfigurableTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ConfigurableTokenSplitter.java @@ -1,32 +1,32 @@ package bjc.utils.parserutils.splitterv2; -import bjc.utils.funcdata.IList; +import static bjc.utils.PropertyDB.applyFormat; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; -import static bjc.utils.PropertyDB.applyFormat; +import bjc.utils.funcdata.IList; /** * Split a string into pieces around a regular expression, and offer an easy way * to configure the regular expression. - * + * * @author EVE * */ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { - private Set<String> simpleDelimiters; - private Set<String> multipleDelimiters; - private Set<String> rRawDelimiters; + private final Set<String> simpleDelimiters; + private final Set<String> multipleDelimiters; + private final Set<String> rRawDelimiters; /** * Create a new token splitter with blank configuration. - * + * * @param keepDelims * Whether or not to keep delimiters. */ - public ConfigurableTokenSplitter(boolean keepDelims) { + public ConfigurableTokenSplitter(final boolean keepDelims) { super(null, keepDelims); /* @@ -39,44 +39,44 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { /** * Add a set of simple delimiters to this splitter. - * + * * Simple delimiters match one occurrence of themselves as literals. - * + * * @param simpleDelims * The simple delimiters to add. */ - public void addSimpleDelimiters(String... simpleDelims) { - for(String simpleDelim : simpleDelims) { + public void addSimpleDelimiters(final String... simpleDelims) { + for (final String simpleDelim : simpleDelims) { simpleDelimiters.add(simpleDelim); } } /** * Add a set of multiple delimiters to this splitter. - * + * * Multiple delimiters match one or more occurrences of themselves as * literals. - * + * * @param multiDelims * The multiple delimiters to add. */ - public void addMultiDelimiters(String... multiDelims) { - for(String multiDelim : multiDelims) { + public void addMultiDelimiters(final String... multiDelims) { + for (final String multiDelim : multiDelims) { multipleDelimiters.add(multiDelim); } } /** * Add a set of raw delimiters to this splitter. - * + * * Raw delimiters match one occurrence of themselves as regular * expressions. - * + * * @param rRawDelims * The raw delimiters to add. */ - public void addRawDelimiters(String... rRawDelims) { - for(String rRawDelim : rRawDelims) { + public void addRawDelimiters(final String... rRawDelims) { + for (final String rRawDelim : rRawDelims) { rRawDelimiters.add(rRawDelim); } } @@ -86,17 +86,17 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { * use when splitting. */ public void compile() { - StringBuilder rPattern = new StringBuilder(); + final StringBuilder rPattern = new StringBuilder(); - for(String rRawDelimiter : rRawDelimiters) { + for (final String rRawDelimiter : rRawDelimiters) { rPattern.append(applyFormat("rawDelim", rRawDelimiter)); } - for(String multipleDelimiter : multipleDelimiters) { + for (final String multipleDelimiter : multipleDelimiters) { rPattern.append(applyFormat("multipleDelim", multipleDelimiter)); } - for(String simpleDelimiter : simpleDelimiters) { + for (final String simpleDelimiter : simpleDelimiters) { rPattern.append(applyFormat("simpleDelim", simpleDelimiter)); } @@ -106,17 +106,15 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { } @Override - public IList<String> split(String input) { - if(spliter == null) { - throw new IllegalStateException("Must compile splitter before use"); - } + public IList<String> split(final String input) { + if (spliter == null) throw new IllegalStateException("Must compile splitter before use"); return super.split(input); } @Override public String toString() { - String fmt = "ConfigurableTokenSplitter [simpleDelimiters=%s, multipleDelimiters=%s," + final String fmt = "ConfigurableTokenSplitter [simpleDelimiters=%s, multipleDelimiters=%s," + " rRawDelimiters=%s, spliter=%s]"; return String.format(fmt, simpleDelimiters, multipleDelimiters, rRawDelimiters, spliter); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ExcludingTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ExcludingTokenSplitter.java index 25bddf5..c5f6f03 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ExcludingTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/ExcludingTokenSplitter.java @@ -1,32 +1,32 @@ package bjc.utils.parserutils.splitterv2; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - import java.util.HashSet; import java.util.Set; import java.util.function.Predicate; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + /** * A token splitter that will not split certain tokens. - * + * * @author EVE * */ public class ExcludingTokenSplitter implements TokenSplitter { - private Set<String> literalExclusions; + private final Set<String> literalExclusions; - private IList<Predicate<String>> predExclusions; + private final IList<Predicate<String>> predExclusions; - private TokenSplitter spliter; + private final TokenSplitter spliter; /** * Create a new excluding token splitter. - * + * * @param splitter * The splitter to apply to non-excluded strings. */ - public ExcludingTokenSplitter(TokenSplitter splitter) { + public ExcludingTokenSplitter(final TokenSplitter splitter) { spliter = splitter; literalExclusions = new HashSet<>(); @@ -36,12 +36,12 @@ public class ExcludingTokenSplitter implements TokenSplitter { /** * Exclude literal strings from splitting. - * + * * @param exclusions * The strings to exclude from splitting. */ - public final void addLiteralExclusions(String... exclusions) { - for (String exclusion : exclusions) { + public final void addLiteralExclusions(final String... exclusions) { + for (final String exclusion : exclusions) { literalExclusions.add(exclusion); } } @@ -49,25 +49,23 @@ public class ExcludingTokenSplitter implements TokenSplitter { /** * Exclude all of the strings matching any of the predicates from * splitting. - * + * * @param exclusions * The predicates to use for exclusions. */ @SafeVarargs - public final void addPredicateExclusion(Predicate<String>... exclusions) { - for (Predicate<String> exclusion : exclusions) { + public final void addPredicateExclusion(final Predicate<String>... exclusions) { + for (final Predicate<String> exclusion : exclusions) { predExclusions.add(exclusion); } } @Override - public IList<String> split(String input) { - if (literalExclusions.contains(input)) { + public IList<String> split(final String input) { + if (literalExclusions.contains(input)) return new FunctionalList<>(input); - } else if (predExclusions.anyMatch(pred -> pred.test(input))) { + else if (predExclusions.anyMatch(pred -> pred.test(input))) return new FunctionalList<>(input); - } else { - return spliter.split(input); - } + else return spliter.split(input); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/SimpleTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/SimpleTokenSplitter.java index b111ca3..ce1c336 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/SimpleTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/SimpleTokenSplitter.java @@ -1,44 +1,42 @@ package bjc.utils.parserutils.splitterv2; +import java.util.regex.Pattern; + import bjc.utils.funcdata.IList; import bjc.utils.functypes.ID; import bjc.utils.ioutils.RegexStringEditor; -import java.util.regex.Pattern; - /** * Splits a string into pieces around a regular expression. - * + * * @author EVE * */ public class SimpleTokenSplitter implements TokenSplitter { protected Pattern spliter; - private boolean keepDelim; + private final boolean keepDelim; /** * Create a new simple token splitter. - * + * * @param splitter * The pattern to split around. - * + * * @param keepDelims * Whether or not delimiters should be kept. */ - public SimpleTokenSplitter(Pattern splitter, boolean keepDelims) { + public SimpleTokenSplitter(final Pattern splitter, final boolean keepDelims) { spliter = splitter; keepDelim = keepDelims; } @Override - public IList<String> split(String input) { - if(keepDelim) { + public IList<String> split(final String input) { + if (keepDelim) return RegexStringEditor.mapOccurances(input, spliter, ID.id(), ID.id()); - } else { - return RegexStringEditor.mapOccurances(input, spliter, ID.id(), strang -> ""); - } + else return RegexStringEditor.mapOccurances(input, spliter, ID.id(), strang -> ""); } @Override diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/TokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/TokenSplitter.java index 5d510c1..ad6865d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/TokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/splitterv2/TokenSplitter.java @@ -4,17 +4,17 @@ import bjc.utils.funcdata.IList; /** * Split a string into a list of pieces. - * + * * @author EVE * */ public interface TokenSplitter { /** * Split a string into a list of pieces. - * + * * @param input * The string to split. - * + * * @return The pieces of the string. */ public IList<String> split(String input); |
