From 504ca816530efdff06bc202e0432ebd354aec304 Mon Sep 17 00:00:00 2001 From: EVE Date: Tue, 14 Mar 2017 12:07:14 -0400 Subject: Cleanup --- .../java/bjc/utils/examples/BinarySearchTest.java | 20 +-- .../java/bjc/utils/examples/parsing/ShuntTest.java | 8 +- .../utils/examples/parsing/TreeConstructTest.java | 32 ++-- .../bjc/utils/examples/rangen/DiabloItemGen.java | 6 +- .../examples/rangen/RandomStringExamples.java | 8 +- .../src/main/java/bjc/utils/cli/CLICommander.java | 36 ++-- .../main/java/bjc/utils/cli/DelegatingCommand.java | 4 +- .../main/java/bjc/utils/cli/GenericCommand.java | 10 +- .../java/bjc/utils/cli/GenericCommandMode.java | 109 ++++++------ .../src/main/java/bjc/utils/cli/GenericHelp.java | 16 +- .../src/main/java/bjc/utils/cli/ICommand.java | 10 +- .../main/java/bjc/utils/cli/ICommandHandler.java | 4 +- .../src/main/java/bjc/utils/cli/ICommandHelp.java | 8 +- .../src/main/java/bjc/utils/cli/ICommandMode.java | 14 +- .../src/main/java/bjc/utils/cli/NullHelp.java | 2 +- .../src/main/java/bjc/utils/cli/package-info.java | 2 +- .../bjc/utils/components/ComponentDescription.java | 24 +-- .../components/ComponentDescriptionFileParser.java | 14 +- .../components/ComponentDescriptionState.java | 12 +- .../utils/components/FileComponentRepository.java | 51 +++--- .../bjc/utils/components/IComponentRepository.java | 10 +- .../bjc/utils/components/IDescribedComponent.java | 18 +- .../java/bjc/utils/components/package-info.java | 2 +- .../main/java/bjc/utils/data/CircularIterator.java | 14 +- .../src/main/java/bjc/utils/data/Either.java | 64 +++---- .../src/main/java/bjc/utils/data/IHolder.java | 38 ++--- BJC-Utils2/src/main/java/bjc/utils/data/IPair.java | 40 ++--- BJC-Utils2/src/main/java/bjc/utils/data/ITree.java | 38 ++--- .../src/main/java/bjc/utils/data/Identity.java | 28 ++- BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java | 28 ++- .../src/main/java/bjc/utils/data/LazyPair.java | 62 +++---- .../src/main/java/bjc/utils/data/ListHolder.java | 14 +- .../src/main/java/bjc/utils/data/Option.java | 18 +- BJC-Utils2/src/main/java/bjc/utils/data/Pair.java | 28 +-- .../main/java/bjc/utils/data/SingleIterator.java | 2 + .../main/java/bjc/utils/data/SingleSupplier.java | 10 +- .../bjc/utils/data/TopDownTransformIterator.java | 87 +++++----- .../bjc/utils/data/TopDownTransformResult.java | 2 +- .../java/bjc/utils/data/TransformedIterator.java | 2 + BJC-Utils2/src/main/java/bjc/utils/data/Tree.java | 89 +++++----- .../java/bjc/utils/data/internals/BoundLazy.java | 38 ++--- .../bjc/utils/data/internals/BoundLazyPair.java | 66 +++---- .../bjc/utils/data/internals/BoundListHolder.java | 26 +-- .../utils/data/internals/HalfBoundLazyPair.java | 38 ++--- .../java/bjc/utils/data/internals/WrappedLazy.java | 6 +- .../bjc/utils/data/internals/WrappedOption.java | 22 +-- .../src/main/java/bjc/utils/esodata/Directory.java | 16 +- .../main/java/bjc/utils/esodata/DoubleTape.java | 26 ++- .../java/bjc/utils/esodata/SimpleDirectory.java | 10 +- .../main/java/bjc/utils/esodata/SingleTape.java | 38 +++-- .../java/bjc/utils/esodata/SpaghettiStack.java | 8 +- .../src/main/java/bjc/utils/esodata/Stack.java | 36 ++-- .../src/main/java/bjc/utils/esodata/Tape.java | 2 +- .../main/java/bjc/utils/esodata/TapeChanger.java | 69 ++++---- .../main/java/bjc/utils/esodata/TapeLibrary.java | 60 +++---- .../java/bjc/utils/esodata/UnifiedDirectory.java | 12 +- .../utils/exceptions/FileNotChosenException.java | 4 +- .../utils/exceptions/PragmaFormatException.java | 4 +- .../utils/exceptions/UnknownPragmaException.java | 4 +- .../main/java/bjc/utils/funcdata/ExtendedMap.java | 12 +- .../java/bjc/utils/funcdata/FunctionalList.java | 131 +++++--------- .../java/bjc/utils/funcdata/FunctionalMap.java | 31 ++-- .../utils/funcdata/FunctionalStringTokenizer.java | 56 +++--- .../src/main/java/bjc/utils/funcdata/IList.java | 77 ++++----- .../src/main/java/bjc/utils/funcdata/IMap.java | 40 ++--- .../main/java/bjc/utils/funcdata/SentryList.java | 4 +- .../bjc/utils/funcdata/TransformedValueMap.java | 6 +- .../bjc/utils/funcdata/bst/BinarySearchTree.java | 44 +++-- .../utils/funcdata/bst/BinarySearchTreeLeaf.java | 20 +-- .../utils/funcdata/bst/BinarySearchTreeNode.java | 106 +++++------- .../utils/funcdata/bst/DirectedWalkFunction.java | 8 +- .../java/bjc/utils/funcdata/bst/ITreePart.java | 18 +- .../funcdata/bst/TreeLinearizationMethod.java | 2 +- .../java/bjc/utils/funcdata/theory/Bifunctor.java | 12 +- .../java/bjc/utils/funcdata/theory/Functor.java | 8 +- .../bjc/utils/funcdata/theory/package-info.java | 2 +- .../java/bjc/utils/funcutils/CollectorUtils.java | 8 +- .../bjc/utils/funcutils/CompoundCollector.java | 14 +- .../java/bjc/utils/funcutils/DoubleMatcher.java | 8 +- .../main/java/bjc/utils/funcutils/EnumUtils.java | 14 +- .../main/java/bjc/utils/funcutils/FileUtils.java | 8 +- .../main/java/bjc/utils/funcutils/FuncUtils.java | 8 +- .../bjc/utils/funcutils/FunctionalFileVisitor.java | 12 +- .../bjc/utils/funcutils/GroupPartIteration.java | 22 +-- .../main/java/bjc/utils/funcutils/IBuilder.java | 6 +- .../main/java/bjc/utils/funcutils/ListUtils.java | 109 ++++++------ .../java/bjc/utils/funcutils/NeoTokenSplitter.java | 19 +-- .../main/java/bjc/utils/funcutils/NumberUtils.java | 14 +- .../main/java/bjc/utils/funcutils/StringUtils.java | 55 +++--- .../java/bjc/utils/funcutils/TokenDeaffixer.java | 28 ++- .../java/bjc/utils/funcutils/TokenSplitter.java | 21 +-- .../src/main/java/bjc/utils/gen/RandomGrammar.java | 16 +- .../main/java/bjc/utils/gen/WeightedGrammar.java | 190 +++++++++------------ .../main/java/bjc/utils/gen/WeightedRandom.java | 24 ++- .../main/java/bjc/utils/graph/AdjacencyMap.java | 65 +++---- BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java | 48 +++--- .../src/main/java/bjc/utils/graph/Graph.java | 77 ++++----- .../java/bjc/utils/gui/ExtensionFileFilter.java | 18 +- .../src/main/java/bjc/utils/gui/SimpleDialogs.java | 84 ++++----- .../main/java/bjc/utils/gui/SimpleFileChooser.java | 68 +++----- .../java/bjc/utils/gui/SimpleInternalDialogs.java | 68 ++++---- .../java/bjc/utils/gui/SimpleInternalFrame.java | 4 +- .../src/main/java/bjc/utils/gui/SimpleJList.java | 18 +- .../java/bjc/utils/gui/SimpleTitledBorder.java | 4 +- .../java/bjc/utils/gui/TextAreaOutputStream.java | 4 +- .../bjc/utils/gui/awt/ExtensionFileFilter.java | 18 +- .../java/bjc/utils/gui/awt/SimpleFileDialog.java | 48 +++--- .../java/bjc/utils/gui/layout/AutosizeLayout.java | 2 +- .../main/java/bjc/utils/gui/layout/HLayout.java | 4 +- .../main/java/bjc/utils/gui/layout/VLayout.java | 4 +- .../bjc/utils/gui/panels/DropdownListPanel.java | 12 +- .../bjc/utils/gui/panels/FormattedInputPanel.java | 10 +- .../bjc/utils/gui/panels/HolderOutputPanel.java | 18 +- .../bjc/utils/gui/panels/ListParameterPanel.java | 36 ++-- .../bjc/utils/gui/panels/SimpleInputPanel.java | 6 +- .../java/bjc/utils/gui/panels/SimpleListPanel.java | 12 +- .../bjc/utils/gui/panels/SimpleSpinnerPanel.java | 4 +- .../bjc/utils/gui/panels/SliderInputPanel.java | 47 +++-- .../java/bjc/utils/parserutils/IPrecedent.java | 6 +- .../utils/parserutils/RuleBasedConfigReader.java | 66 ++++--- .../utils/parserutils/RuleBasedReaderPragmas.java | 21 +-- .../java/bjc/utils/parserutils/ShuntingYard.java | 60 +++---- .../bjc/utils/parserutils/TokenTransformer.java | 31 ++-- .../bjc/utils/parserutils/TreeConstructor.java | 29 ++-- 124 files changed, 1553 insertions(+), 1961 deletions(-) (limited to 'BJC-Utils2') diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java index a33847c..1e0a1df 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java @@ -1,13 +1,13 @@ package bjc.utils.examples; -import java.util.Scanner; - import bjc.utils.funcdata.bst.BinarySearchTree; import bjc.utils.funcdata.bst.TreeLinearizationMethod; +import java.util.Scanner; + /** * Example showing how to use the binary search tree. - * + * * @author ben * */ @@ -16,11 +16,11 @@ public class BinarySearchTest { System.out.print("What order would you like the tree to be printed in (m for options): "); char command; - while (true) { + while(true) { command = input.nextLine().charAt(0); TreeLinearizationMethod method = null; - switch (command) { + switch(command) { case 'm': System.out.println("Possible tree printing methods: "); System.out.println("\tp: Preorder printing (print parent first, then left & right)."); @@ -40,7 +40,7 @@ public class BinarySearchTest { System.out.println("ERROR: Unknown command."); } - if (method != null) { + if(method != null) { tree.traverse(method, (element) -> { System.out.println("Node: " + element); return true; @@ -55,7 +55,7 @@ public class BinarySearchTest { /** * Main method of class - * + * * @param args * Unused CLI args */ @@ -68,11 +68,11 @@ public class BinarySearchTest { BinarySearchTree tree = new BinarySearchTree<>((o1, o2) -> o1 - o2); - while (command != 'e') { + while(command != 'e') { System.out.print("Enter a command (m for help): "); command = input.nextLine().charAt(0); - switch (command) { + switch(command) { case 'm': System.out.println("Valid commands: "); System.out.println("\tm: Display this help message."); @@ -104,7 +104,7 @@ public class BinarySearchTest { command = input.nextLine().charAt(0); boolean inTree = tree.isInTree(command); - if (inTree) { + if(inTree) { System.out.printf("Node %s was found\n", command); } else { System.out.printf("Node %s was not found\n", command); diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/ShuntTest.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/ShuntTest.java index 6b523ce..e228765 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/ShuntTest.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/ShuntTest.java @@ -1,21 +1,21 @@ package bjc.utils.examples.parsing; -import java.util.Scanner; - import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IList; import bjc.utils.parserutils.ShuntingYard; +import java.util.Scanner; + /** * Test of shunting yard - * + * * @author ben * */ public class ShuntTest { /** * Main method - * + * * @param args * Unused CLI args */ diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/TreeConstructTest.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/TreeConstructTest.java index bd67cc8..58a6a5c 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/TreeConstructTest.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/parsing/TreeConstructTest.java @@ -1,11 +1,5 @@ package bjc.utils.examples.parsing; -import java.util.Deque; -import java.util.LinkedList; -import java.util.Scanner; -import java.util.function.Function; -import java.util.function.Predicate; - import bjc.utils.data.IPair; import bjc.utils.data.ITree; import bjc.utils.data.Pair; @@ -19,9 +13,15 @@ import bjc.utils.funcutils.StringUtils; import bjc.utils.parserutils.ShuntingYard; import bjc.utils.parserutils.TreeConstructor; +import java.util.Deque; +import java.util.LinkedList; +import java.util.Scanner; +import java.util.function.Function; +import java.util.function.Predicate; + /** * Test of tree constructor - * + * * @author ben * */ @@ -29,13 +29,11 @@ public class TreeConstructTest { private static final class OperatorPicker implements Predicate { @Override public boolean test(String token) { - if (StringUtils.containsOnly(token, "\\[")) { + if(StringUtils.containsOnly(token, "\\[")) return true; - } else if (StringUtils.containsOnly(token, "\\]")) { - return true; - } + else if(StringUtils.containsOnly(token, "\\]")) return true; - switch (token) { + switch(token) { case "+": case "-": case "*": @@ -49,7 +47,7 @@ public class TreeConstructTest { /** * Main method - * + * * @param args * Unused CLI args */ @@ -89,11 +87,9 @@ public class TreeConstructTest { System.out.println("Shunted: " + shuntedTokens.toString()); Predicate specialPicker = (operator) -> { - if (StringUtils.containsOnly(operator, "\\[")) { + if(StringUtils.containsOnly(operator, "\\[")) return true; - } else if (StringUtils.containsOnly(operator, "\\]")) { - return true; - } + else if(StringUtils.containsOnly(operator, "\\]")) return true; return false; }; @@ -115,7 +111,7 @@ public class TreeConstructTest { operators.put("]", (queuedTrees) -> { ITree arrayTree = new Tree<>("[]"); - while (!queuedTrees.peek().getHead().equals("[")) { + while(!queuedTrees.peek().getHead().equals("[")) { arrayTree.addChild(queuedTrees.pop()); } diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java index 8ebf08f..c83c86e 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java @@ -6,7 +6,7 @@ import bjc.utils.gen.WeightedGrammar; /** * Example showing how to use the weighted random number generator. - * + * * @author ben * */ @@ -65,7 +65,7 @@ public class DiabloItemGen { /** * Main Method - * + * * @param args * Unused CLI args */ @@ -82,7 +82,7 @@ public class DiabloItemGen { rules.addRule(""); addInfixRules(); - for (int i = 0; i < 100; i++) { + for(int i = 0; i < 100; i++) { IList ls = rules.generateListValues("", " "); StringBuilder sb = new StringBuilder(); diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java index 6de6c68..c490107 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java @@ -7,7 +7,7 @@ import bjc.utils.gen.RandomGrammar; /** * Examples of random grammar - * + * * @author ben * */ @@ -17,7 +17,7 @@ public class RandomStringExamples { private static void addRule(String rule, String... cases) { IList> cses = new FunctionalList<>(); - for (String strang : cases) { + for(String strang : cases) { IList lst = FunctionalStringTokenizer.fromString(strang).toList(s -> s); cses.add(lst); @@ -28,7 +28,7 @@ public class RandomStringExamples { /** * Main method - * + * * @param args * Unused CLI args */ @@ -52,7 +52,7 @@ public class RandomStringExamples { addRule("", "", " with ", ""); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) { IList ls = rg.generateListValues("", " "); StringBuilder sb = new StringBuilder(); 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 22fb276..b732f01 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java @@ -8,7 +8,7 @@ import java.util.Scanner; /** * Runs a CLI interface from the provided set of streams. - * + * * @author ben * */ @@ -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 InputStream input; + private OutputStream output; + private OutputStream error; /* * The command mode to start execution in @@ -27,7 +27,7 @@ public class CLICommander { /** * Create a new CLI interface powered by streams. - * + * * @param input * The stream to get user input from. * @param output @@ -36,13 +36,11 @@ public class CLICommander { * The stream to send error output to. */ public CLICommander(InputStream input, OutputStream output, OutputStream error) { - if (input == null) { + if(input == null) throw new NullPointerException("Input stream must not be null"); - } else if (output == 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"); - } + else if(error == null) throw new NullPointerException("Error stream must not be null"); this.input = input; this.output = output; @@ -59,7 +57,7 @@ public class CLICommander { /* * Set up input streams. - * + * * We're suppressing the warning because we might use the input * stream multiple times */ @@ -68,18 +66,18 @@ public class CLICommander { /* * The mode currently being used to handle commands. - * + * * Used to preserve the initial mode */ ICommandMode currentMode = initialMode; // 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() + ">> "); @@ -89,12 +87,12 @@ public class CLICommander { String currentLine = inputSource.nextLine(); // Handle commands we can handle - if (currentMode.canHandle(currentLine)) { + if(currentMode.canHandle(currentLine)) { String[] commandTokens = currentLine.split(" "); String[] commandArgs = null; // Parse args if they are present - if (commandTokens.length > 1) { + if(commandTokens.length > 1) { commandArgs = Arrays.copyOfRange(commandTokens, 1, commandTokens.length); } @@ -110,14 +108,12 @@ public class CLICommander { /** * Set the initial command mode to use - * + * * @param initialMode * The initial command mode to use */ public void setInitialCommandMode(ICommandMode initialMode) { - if (initialMode == null) { - throw new NullPointerException("Initial mode must be non-zero"); - } + 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/DelegatingCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java index 7d2f807..ddad5e2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -2,7 +2,7 @@ package bjc.utils.cli; /** * A class for a command that delegates to another command - * + * * @author ben * */ @@ -12,7 +12,7 @@ class DelegatingCommand implements ICommand { /** * Create a new command that delegates to another command - * + * * @param delegate * The command to delegate to */ 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 b0ceb3b..4dde938 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java @@ -2,7 +2,7 @@ package bjc.utils.cli; /** * Generic command implementation - * + * * @author ben * */ @@ -15,7 +15,7 @@ public class GenericCommand implements ICommand { /** * Create a new generic command - * + * * @param handler * The handler to use for the command * @param description @@ -24,13 +24,11 @@ public class GenericCommand implements ICommand { * The detailed help message for the command. May be null */ public GenericCommand(ICommandHandler handler, String description, String help) { - if (handler == null) { - throw new NullPointerException("Command handler must not be null"); - } + 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); 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 62d0008..982cf48 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -1,19 +1,19 @@ 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 - * + * * There is a small set of commands which is handled by default. The first is * 'list', which lists all the commands the user can input. The second is * 'alias', which allows the user to bind a new name to a command - * + * * @author ben * */ @@ -21,8 +21,8 @@ public class GenericCommandMode implements ICommandMode { /* * Contains the commands this mode handles */ - private IMap commandHandlers; - private IMap defaultHandlers; + private IMap commandHandlers; + private IMap defaultHandlers; // Contains help topics without an associated command private IMap helpTopics; @@ -31,8 +31,8 @@ public class GenericCommandMode implements ICommandMode { private BiConsumer unknownCommandHandler; // The functions to use for input/output - private Consumer errorOutput; - private Consumer normalOutput; + private Consumer errorOutput; + private Consumer normalOutput; // The name of this command mode, or null if it is unnamed private String modeName; @@ -42,18 +42,16 @@ public class GenericCommandMode implements ICommandMode { /** * Create a new generic command mode - * + * * @param normalOutput * The function to use for normal output * @param errorOutput * The function to use for error output */ public GenericCommandMode(Consumer normalOutput, Consumer errorOutput) { - if (normalOutput == null) { + 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; @@ -69,31 +67,31 @@ public class GenericCommandMode implements ICommandMode { /** * Add an alias to an existing command - * + * * @param commandName * The name of the command to add an alias for * @param aliasName * The new alias for the command - * + * * @throws IllegalArgumentException * if the specified command doesn't have a bound * handler, or if the alias name already has a bound * value */ public void addCommandAlias(String commandName, String aliasName) { - if (commandName == null) { + 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 { + else { ICommand aliasedCommand; - if (defaultHandlers.containsKey(commandName)) { + if(defaultHandlers.containsKey(commandName)) { aliasedCommand = defaultHandlers.get(commandName).aliased(); } else { aliasedCommand = commandHandlers.get(commandName).aliased(); @@ -105,31 +103,31 @@ public class GenericCommandMode implements ICommandMode { /** * Add a command to this command mode - * + * * @param command * The name of the command to add * @param handler * The handler to use for the specified command - * + * * @throws IllegalArgumentException * if the specified command already has a handler * registered */ public void addCommandHandler(String command, ICommand handler) { - if (command == null) { + 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 { + else { commandHandlers.put(command, handler); } } /** * Add a help topic to this command mode that isn't tied to a command - * + * * @param topicName * The name of the topic * @param topic @@ -187,7 +185,7 @@ public class GenericCommandMode implements ICommandMode { + " 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 doHelpSummary(); } else { @@ -221,16 +219,16 @@ public class GenericCommandMode implements ICommandMode { */ private void doAliasCommands(String[] args) { - if (args.length != 2) { + 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]; - 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); @@ -239,15 +237,15 @@ public class GenericCommandMode implements ICommandMode { } private void doHelpCommand(String commandName) { - if (commandHandlers.containsKey(commandName)) { + if(commandHandlers.containsKey(commandName)) { String desc = commandHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if (defaultHandlers.containsKey(commandName)) { + } else if(defaultHandlers.containsKey(commandName)) { 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( @@ -258,9 +256,9 @@ public class GenericCommandMode implements ICommandMode { private void doHelpSummary() { normalOutput.accept("Help topics for this command mode are as follows:\n"); - if (commandHandlers.getSize() > 0) { + if(commandHandlers.getSize() > 0) { commandHandlers.forEachValue(command -> { - if (!command.isAlias()) { + if(!command.isAlias()) { normalOutput.accept("\t" + command.getHelp().getSummary() + "\n"); } }); @@ -269,9 +267,9 @@ public class GenericCommandMode implements ICommandMode { } normalOutput.accept("\nHelp topics available in all command modes are as follows\n"); - if (defaultHandlers.getSize() > 0) { + if(defaultHandlers.getSize() > 0) { defaultHandlers.forEachValue(command -> { - if (!command.isAlias()) { + if(!command.isAlias()) { normalOutput.accept("\t" + command.getHelp().getSummary() + "\n"); } }); @@ -280,7 +278,7 @@ public class GenericCommandMode implements ICommandMode { } normalOutput.accept("\nHelp topics not associated with a command are as follows\n"); - if (helpTopics.getSize() > 0) { + if(helpTopics.getSize() > 0) { helpTopics.forEachValue(topic -> { normalOutput.accept("\t" + topic.getSummary() + "\n"); }); @@ -306,18 +304,14 @@ public class GenericCommandMode implements ICommandMode { @Override public String getCustomPrompt() { - if (customPrompt != null) { - return customPrompt; - } + if(customPrompt != null) return customPrompt; return ICommandMode.super.getCustomPrompt(); } @Override public String getName() { - if (modeName != null) { - return modeName; - } + if(modeName != null) return modeName; return ICommandMode.super.getName(); } @@ -331,20 +325,19 @@ public class GenericCommandMode implements ICommandMode { public ICommandMode process(String command, 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) { + else { + 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); } @@ -354,7 +347,7 @@ public class GenericCommandMode implements ICommandMode { /** * Set the custom prompt for this mode - * + * * @param prompt * The custom prompt for this mode, or null to disable * the custom prompt @@ -365,7 +358,7 @@ public class GenericCommandMode implements ICommandMode { /** * Set the name of this mode - * + * * @param name * The desired name of this mode, or null to use the * default name @@ -376,15 +369,13 @@ public class GenericCommandMode implements ICommandMode { /** * Set the handler to use for unknown commands - * + * * @param handler * The handler to use for unknown commands, or null to * throw on unknown commands */ public void setUnknownCommandHandler(BiConsumer handler) { - if (handler == null) { - throw new NullPointerException("Handler must not be null"); - } + if(handler == null) throw new NullPointerException("Handler must not be null"); unknownCommandHandler = handler; } 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 595d7d9..6fa367c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java @@ -2,18 +2,18 @@ package bjc.utils.cli; /** * Generic implementation of a help topic - * + * * @author ben * */ public class GenericHelp implements ICommandHelp { // The strings for this help topic - private String summary; - private String description; + private String summary; + private String description; /** * Create a new help topic - * + * * @param summary * The summary of this help topic * @param description @@ -21,9 +21,7 @@ public class GenericHelp implements ICommandHelp { * 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"); - } + if(summary == null) throw new NullPointerException("Help summary must be non-null"); this.summary = summary; this.description = description; @@ -31,9 +29,7 @@ public class GenericHelp implements ICommandHelp { @Override public String getDescription() { - if (description == null) { - return summary; - } + if(description == null) return summary; return description; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java index a72ecdf..6703460 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java @@ -2,35 +2,35 @@ package bjc.utils.cli; /** * Represents a command that can be invoked from a {@link ICommandMode} - * + * * @author ben * */ public interface ICommand { /** * Create a command that serves as an alias to this one - * + * * @return A command that serves as an alias to this one */ public ICommand aliased(); /** * Get the handler that executes this command - * + * * @return The handler that executes this command */ public ICommandHandler getHandler(); /** * Get the help entry for this command - * + * * @return The help entry for this command */ public ICommandHelp getHelp(); /** * Check if this command is an alias of another command - * + * * @return Whether or not this command is an alias of another */ public default boolean isAlias() { diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java index a774108..d105ce3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java @@ -4,7 +4,7 @@ import java.util.function.Function; /** * A handler for a command - * + * * @author ben * */ @@ -12,7 +12,7 @@ import java.util.function.Function; public interface ICommandHandler extends Function { /** * Execute this command - * + * * @param args * The arguments for this command * @return The command mode to switch to after this command, or null to diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java index 472d6a3..9fc9388 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java @@ -2,25 +2,25 @@ package bjc.utils.cli; /** * Interface for the help entry for a command - * + * * @author ben * */ public interface ICommandHelp { /** * Get the description of a command. - * + * * @return The description of a command */ public String getDescription(); /** * Get the summary line for a command. - * + * * A summary line should consist of a string of the following format * "\t" where anything in angle brackets * should be filled in. - * + * * @return The summary line line for a command */ public String getSummary(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java index 56f7869..2bf9ccf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java @@ -3,14 +3,14 @@ package bjc.utils.cli; /** * A mode for determining the commands that are valid to enter, and then * handling those commands - * + * * @author ben * */ public interface ICommandMode { /** * Check to see if this mode can handle the specified command - * + * * @param command * The command to check * @return Whether or not this mode can handle the command. It is @@ -22,9 +22,9 @@ public interface ICommandMode { /** * Get the custom prompt for this mode - * + * * @return the custom prompt for this mode - * + * * @throws UnsupportedOperationException * if this mode doesn't support a custom prompt */ @@ -34,7 +34,7 @@ public interface ICommandMode { /** * Get the name of this command mode - * + * * @return The name of this command mode, which is the empty string by * default */ @@ -44,7 +44,7 @@ public interface ICommandMode { /** * Check if this mode uses a custom prompt - * + * * @return Whether or not this mode uses a custom prompt */ public default boolean isCustomPromptEnabled() { @@ -53,7 +53,7 @@ public interface ICommandMode { /** * Process a command in this mode - * + * * @param command * The command to process * @param args 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 3e016e2..94dee4d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/NullHelp.java @@ -2,7 +2,7 @@ package bjc.utils.cli; /** * Implementation of a help topic that doesn't exist - * + * * @author ben * */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/package-info.java b/BJC-Utils2/src/main/java/bjc/utils/cli/package-info.java index 012ccc0..7446a3c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/package-info.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/package-info.java @@ -1,6 +1,6 @@ /** * Holds classes for easier CLI design - * + * * @author ben * */ 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 c473150..13132ed 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java @@ -2,31 +2,29 @@ package bjc.utils.components; /** * Generic implementation of a description for a component - * + * * @author ben * */ public class ComponentDescription implements IDescribedComponent { private static void sanityCheckArgs(String name, String author, String description, int version) { - if (name == null) { + 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 String author; /** * The description of the component */ - private String description; + private String description; /** * The name of the component */ - private String name; + private String name; /** * The version of the component @@ -35,7 +33,7 @@ public class ComponentDescription implements IDescribedComponent { /** * Create a new component description - * + * * @param name * The name of the component * @param author @@ -58,18 +56,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; } 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 22221d2..c939708 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java @@ -1,15 +1,15 @@ package bjc.utils.components; -import static bjc.utils.parserutils.RuleBasedReaderPragmas.buildInteger; -import static bjc.utils.parserutils.RuleBasedReaderPragmas.buildStringCollapser; +import bjc.utils.parserutils.RuleBasedConfigReader; import java.io.InputStream; -import bjc.utils.parserutils.RuleBasedConfigReader; +import static bjc.utils.parserutils.RuleBasedReaderPragmas.buildInteger; +import static bjc.utils.parserutils.RuleBasedReaderPragmas.buildStringCollapser; /** * Read a component description from a file - * + * * @author ben * */ @@ -35,15 +35,13 @@ public class ComponentDescriptionFileParser { /** * Parse a component description from a stream - * + * * @param inputSource * 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"); - } + if(inputSource == null) throw new NullPointerException("Input source must not be null"); ComponentDescriptionState readState = reader.fromStream(inputSource, new ComponentDescriptionState()); 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 70f308b..02e003a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java @@ -2,7 +2,7 @@ package bjc.utils.components; /** * Internal state of component description parser - * + * * @author ben * */ @@ -21,7 +21,7 @@ public class ComponentDescriptionState { /** * Set the author of this component - * + * * @param author * The author of this component */ @@ -31,7 +31,7 @@ public class ComponentDescriptionState { /** * Set the description of this component - * + * * @param description * The description of this component */ @@ -41,7 +41,7 @@ public class ComponentDescriptionState { /** * Set the name of this component - * + * * @param name * The name of this component */ @@ -51,7 +51,7 @@ public class ComponentDescriptionState { /** * Set the version of this component - * + * * @param version * The version of this component */ @@ -61,7 +61,7 @@ public class ComponentDescriptionState { /** * Convert this state into the description it represents - * + * * @return The description represented by this state */ public ComponentDescription toDescription() { 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 7aa7c07..d69b794 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -1,5 +1,12 @@ 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; @@ -9,16 +16,9 @@ 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 - * + * * @author ben * * @param @@ -38,10 +38,10 @@ public class FileComponentRepository /** * Create a new component repository sourcing components from files in a * directory - * + * * An exception thrown during the loading of a component will only cause * the loading of that component to fail, but a warning will be logged. - * + * * @param directory * The directory to read component files from * @param componentReader @@ -49,14 +49,12 @@ public class FileComponentRepository */ public FileComponentRepository(File directory, Function 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<>(); @@ -69,13 +67,14 @@ public class FileComponentRepository // but // not recurse into sub-directories BiPredicate firstLevelTraverser = (pth, attr) -> { - if (attr.isDirectory() && !isFirstDir.getValue()) { - /* - * Skip directories, they probably have - * component support files. - */ + if(attr.isDirectory() && !isFirstDir + .getValue()) /* + * Skip directories, + * they probably have + * component support + * files. + */ return false; - } /* * Don't skip the first directory, that's the parent @@ -95,7 +94,7 @@ public class FileComponentRepository // failed return true; }); - } catch (IOException ioex) { + } catch(IOException ioex) { CLASS_LOGGER.log(Level.WARNING, ioex, () -> "Error found reading component from file."); } } @@ -128,14 +127,14 @@ public class FileComponentRepository // Try to load the component 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); - if (oldComponent.getVersion() > component.getVersion()) { + if(oldComponent.getVersion() > component.getVersion()) { components.put(oldComponent.getName(), oldComponent); } } else { @@ -144,7 +143,7 @@ public class FileComponentRepository + "Only the latest version of the component" + component + " will be registered ."); } - } catch (Exception ex) { + } catch(Exception ex) { CLASS_LOGGER.log(Level.WARNING, ex, () -> "Error found reading component from file " + pth.toString() + ". This component will not be loaded"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java index f3aab76..5ef65ee 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java @@ -6,7 +6,7 @@ import bjc.utils.funcdata.IMap; /** * A collection of implementations of a particular type of * {@link IDescribedComponent} - * + * * @author ben * * @param @@ -15,7 +15,7 @@ import bjc.utils.funcdata.IMap; public interface IComponentRepository { /** * Get all of the components this repository knows about - * + * * @return A map from component name to component, containing all of the * components in the repositories */ @@ -23,7 +23,7 @@ public interface IComponentRepository /** * Get a component with a specific name - * + * * @param name * The name of the component to retrieve * @return The named component, or null if no component with that name @@ -33,7 +33,7 @@ public interface IComponentRepository /** * Get a list of all the registered componets - * + * * @return A list of all the registered components */ public default IList getList() { @@ -42,7 +42,7 @@ public interface IComponentRepository /** * Get the source from which these components came - * + * * @return The source from which these components came */ public String getSource(); 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 6b87ba7..a397bbc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java @@ -3,16 +3,16 @@ package bjc.utils.components; /** * Represents a optional component that has status information associated with * it - * + * * @author ben * */ public interface IDescribedComponent { /** * Get the author of this component - * + * * Providing this is optional, with "Anonymous" as the default author - * + * * @return The author of the component */ public default String getAuthor() { @@ -21,10 +21,10 @@ public interface IDescribedComponent { /** * Get the description of this component - * + * * Providing this is optional, with the default being a note that no * description was provided - * + * * @return The description of the component */ public default String getDescription() { @@ -33,18 +33,18 @@ public interface IDescribedComponent { /** * Get the name of this component. - * + * * This is the only thing required of all components - * + * * @return The name of the component */ public String getName(); /** * Get the version of this component - * + * * Providing this is optional, with "1" as the default version - * + * * @return The version of this component */ public default int getVersion() { diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/package-info.java b/BJC-Utils2/src/main/java/bjc/utils/components/package-info.java index 9f83fb0..37a9e84 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/package-info.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/package-info.java @@ -1,6 +1,6 @@ /** * This package contains utilities for components - * + * * @author ben * */ 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 8e0bf86..7131114 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java @@ -3,8 +3,8 @@ package bjc.utils.data; import java.util.Iterator; public class CircularIterator implements Iterator { - private Iterable source; - private Iterator curr; + private Iterable source; + private Iterator curr; private E curElm; @@ -21,18 +21,19 @@ public class CircularIterator implements Iterator { this(src, true); } + @Override public boolean hasNext() { // We always have something return true; } + @Override public E next() { - if (!curr.hasNext()) { - if (doCircle) { + if(!curr.hasNext()) { + if(doCircle) { curr = source.iterator(); - } else { + } else return curElm; - } } curElm = curr.next(); @@ -40,6 +41,7 @@ public class CircularIterator implements Iterator { return curElm; } + @Override public void remove() { curr.remove(); } 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 7ec1720..d34f752 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Either.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Either.java @@ -5,7 +5,7 @@ import java.util.function.Function; /** * Represents a pair where only one side has a value - * + * * @author ben * @param * The type that could be on the left @@ -16,7 +16,7 @@ import java.util.function.Function; public class Either implements IPair { /** * Create a new either with the left value occupied - * + * * @param * The type of the left value * @param @@ -31,7 +31,7 @@ public class Either implements IPair { /** * Create a new either with the right value occupied - * + * * @param * The type of the empty left value * @param @@ -51,7 +51,7 @@ public class Either implements IPair { private boolean isLeft; private Either(LeftType left, RightType right) { - if (left == null) { + if(left == null) { rightVal = right; } else { leftVal = left; @@ -63,9 +63,7 @@ public class Either implements IPair { @Override public IPair bind( BiFunction> binder) { - if (binder == null) { - throw new NullPointerException("Binder must not be null"); - } + if(binder == null) throw new NullPointerException("Binder must not be null"); return binder.apply(leftVal, rightVal); } @@ -73,13 +71,9 @@ public class Either implements IPair { @Override public IPair bindLeft( Function> leftBinder) { - if (leftBinder == null) { - throw new NullPointerException("Left binder must not be null"); - } + 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); } @@ -87,13 +81,9 @@ public class Either implements IPair { @Override public IPair bindRight( Function> rightBinder) { - if (rightBinder == null) { - throw new NullPointerException("Right binder must not be null"); - } + 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); } @@ -103,19 +93,15 @@ public class Either implements IPair { IPair otherPair, BiFunction leftCombiner, BiFunction rightCombiner) { - if (otherPair == null) { + 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"); - 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)); @@ -124,35 +110,25 @@ public class Either implements IPair { @Override public IPair mapLeft(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + 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 IPair mapRight(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + 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 merge(BiFunction merger) { - if (merger == null) { - throw new NullPointerException("Merger must not be null"); - } + if(merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftVal, rightVal); } 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 7b6c8d5..999f3da 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java @@ -1,18 +1,18 @@ 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. - * + * * @author ben * * @param @@ -21,7 +21,7 @@ import bjc.utils.funcdata.theory.Functor; public interface IHolder extends Functor { /** * Bind a function across the value in this container - * + * * @param * The type of value in this container * @param binder @@ -32,7 +32,7 @@ public interface IHolder extends Functor { /** * Apply an action to the value - * + * * @param action * The action to apply to the value */ @@ -48,10 +48,8 @@ public interface IHolder extends Functor { default Function, Functor> fmap( Function func) { return (argumentFunctor) -> { - if (!(argumentFunctor instanceof IHolder)) { - throw new IllegalArgumentException( - "This functor only supports mapping over instances of IHolder"); - } + if(!(argumentFunctor instanceof IHolder)) throw new IllegalArgumentException( + "This functor only supports mapping over instances of IHolder"); IHolder holder = (IHolder) argumentFunctor; @@ -66,7 +64,7 @@ public interface IHolder extends Functor { /** * Lifts a function to bind over this holder - * + * * @param * The type of the functions return * @param func @@ -77,7 +75,7 @@ public interface IHolder extends Functor { /** * Make this holder lazy - * + * * @return A lazy version of this holder */ public default IHolder makeLazy() { @@ -86,7 +84,7 @@ public interface IHolder extends Functor { /** * Make this holder a list - * + * * @return A list version of this holder */ public default IHolder makeList() { @@ -95,7 +93,7 @@ public interface IHolder extends Functor { /** * Make this holder optional - * + * * @return An optional version of this holder */ public default IHolder makeOptional() { @@ -105,9 +103,9 @@ public interface IHolder extends Functor { /** * Create a new holder with a mapped version of the value in this * holder. - * + * * Does not change the internal state of this holder - * + * * @param * The type of the mapped value * @param mapper @@ -118,7 +116,7 @@ public interface IHolder extends Functor { /** * Replace the held value with a new one - * + * * @param newValue * The value to hold instead * @return The holder itself @@ -131,7 +129,7 @@ public interface IHolder extends Functor { /** * Transform the value held in this holder - * + * * @param transformer * The function to transform the value with * @return The holder itself, for easy chaining @@ -141,7 +139,7 @@ public interface IHolder extends Functor { /** * Unwrap the value contained in this holder so that it is no longer * held - * + * * @param * The type of the unwrapped value * @param unwrapper 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 1405d75..24e0381 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java @@ -1,14 +1,14 @@ 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 - * + * * @author ben * @param * The type of the left side of the pair @@ -19,7 +19,7 @@ import bjc.utils.funcdata.theory.Bifunctor; public interface IPair extends Bifunctor { /** * Bind a function across the values in this pair - * + * * @param * The type of the bound left * @param @@ -33,7 +33,7 @@ public interface IPair extends Bifunctor * The type of the bound value * @param leftBinder @@ -45,7 +45,7 @@ public interface IPair extends Bifunctor * The type of the bound value * @param rightBinder @@ -57,7 +57,7 @@ public interface IPair extends Bifunctor * The left type of the other pair * @param @@ -74,7 +74,7 @@ public interface IPair extends Bifunctor * The type of the left value of the other pair * @param @@ -97,7 +97,7 @@ public interface IPair extends Bifunctor extends Bifunctor Function, Bifunctor> fmapLeft( Function func) { return (argumentPair) -> { - if (!(argumentPair instanceof IPair)) { - throw new IllegalArgumentException( - "This function can only be applied to instances of IPair"); - } + if(!(argumentPair instanceof IPair)) throw new IllegalArgumentException( + "This function can only be applied to instances of IPair"); IPair argPair = (IPair) argumentPair; @@ -129,10 +127,8 @@ public interface IPair extends Bifunctor func) { return (argumentPair) -> { - if (!(argumentPair instanceof IPair)) { - throw new IllegalArgumentException( - "This function can only be applied to instances of IPair"); - } + if(!(argumentPair instanceof IPair)) throw new IllegalArgumentException( + "This function can only be applied to instances of IPair"); IPair argPair = (IPair) argumentPair; @@ -142,7 +138,7 @@ public interface IPair extends Bifunctor extends Bifunctor extends Bifunctor * The new type of the left part of the pair * @param mapper @@ -176,7 +172,7 @@ public interface IPair extends Bifunctor * The new type of the right part of the pair * @param mapper @@ -188,7 +184,7 @@ public interface IPair extends Bifunctor * The type of the single value * @param merger 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 4b6725c..63a82b8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java @@ -1,16 +1,16 @@ package bjc.utils.data; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.bst.TreeLinearizationMethod; + import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.bst.TreeLinearizationMethod; - /** * A node in a homogenous tree with a unlimited amount of children - * + * * @author ben * @param * The type of data contained in the tree nodes @@ -19,7 +19,7 @@ import bjc.utils.funcdata.bst.TreeLinearizationMethod; public interface ITree { /** * Add a child to this node - * + * * @param child * The child to add to this node */ @@ -27,7 +27,7 @@ public interface ITree { /** * Collapse a tree into a single version - * + * * @param * The intermediate type being folded * @param @@ -48,7 +48,7 @@ public interface ITree { /** * Execute a given action for each of this tree's children - * + * * @param action * The action to execute for each child */ @@ -57,7 +57,7 @@ public interface ITree { /** * Expand the nodes of a tree into trees, and then merge the contents of * those trees into a single tree - * + * * @param mapper * The function to use to map values into trees * @return A tree, with some nodes expanded into trees @@ -66,7 +66,7 @@ public interface ITree { /** * Get the specified child of this tree - * + * * @param childNo * The number of the child to get * @return The specified child of this tree @@ -77,14 +77,14 @@ public interface ITree { /** * Get a count of the number of direct children this node has - * + * * @return The number of direct children this node has */ public int getChildrenCount(); /** * Get the data stored in this node - * + * * @return The data stored in this node */ default ContainedType getHead() { @@ -93,7 +93,7 @@ public interface ITree { /** * Rebuild the tree with the same structure, but different nodes - * + * * @param * The type of the new tree * @param leafTransformer @@ -107,7 +107,7 @@ public interface ITree { /** * Transform some of the nodes in this tree - * + * * @param nodePicker * The predicate to use to pick nodes to transform * @param transformer @@ -117,7 +117,7 @@ public interface ITree { /** * Do a top-down transform of the tree - * + * * @param transformPicker * The function to use to pick how to progress * @param transformer @@ -129,7 +129,7 @@ public interface ITree { /** * Transform one of this nodes children - * + * * @param * The type of the transformed value * @param childNo @@ -137,7 +137,7 @@ public interface ITree { * @param transformer * The function to use to transform the value * @return The transformed value - * + * * @throws IllegalArgumentException * if the childNo is out of bounds (0 <= childNo <= * childCount()) @@ -147,7 +147,7 @@ public interface ITree { /** * Transform the value that is the head of this node - * + * * @param * The type of the transformed value * @param transformer @@ -158,7 +158,7 @@ public interface ITree { /** * Transform the tree into a tree with a different type of token - * + * * @param * The type of the new tree * @param transformer @@ -169,7 +169,7 @@ public interface ITree { /** * Perform an action on each part of the tree - * + * * @param linearizationMethod * The way to traverse the tree * @param action 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 aa3f7aa..9c4ea45 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java @@ -10,7 +10,7 @@ import java.util.function.UnaryOperator; */ /** * Simple implementation of IHolder that has no hidden behavior - * + * * @author ben * * @param @@ -28,7 +28,7 @@ public class Identity implements IHolder { /** * Create a holder holding the specified value - * + * * @param value * The value to hold */ @@ -43,35 +43,29 @@ public class Identity implements IHolder { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - if (this == obj) { + if(this == obj) return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { + else if(obj == null) return false; - } + else if(getClass() != obj.getClass()) return false; Identity other = (Identity) obj; - if (heldValue == null) { - if (other.heldValue != null) { - return false; - } - } else if (!heldValue.equals(other.heldValue)) { - return false; - } + if(heldValue == null) { + if(other.heldValue != null) return false; + } else if(!heldValue.equals(other.heldValue)) return false; return true; } /* * (non-Javadoc) - * + * * @see java.lang.Object#hashCode() */ @Override @@ -80,7 +74,7 @@ public class Identity implements IHolder { int result = 1; - int fieldHash = (heldValue == null) ? 0 : heldValue.hashCode(); + int fieldHash = heldValue == null ? 0 : heldValue.hashCode(); result = prime * result + fieldHash; 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 3a037d7..d4d350a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java @@ -1,17 +1,17 @@ package bjc.utils.data; -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; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + /** * A holder that holds a means to create a value, but doesn't actually compute * the value until it's needed - * + * * @author ben * * @param @@ -27,7 +27,7 @@ public class Lazy implements IHolder { /** * Create a new lazy value from the specified seed value - * + * * @param value * The seed value to use */ @@ -39,7 +39,7 @@ public class Lazy implements IHolder { /** * Create a new lazy value from the specified value source - * + * * @param supp * The source of a value to use */ @@ -62,9 +62,7 @@ public class Lazy implements IHolder { actions.forEach(pendingActions::add); Supplier supplier = () -> { - if (valueMaterialized) { - return heldValue; - } + if(valueMaterialized) return heldValue; return valueSupplier.get(); }; @@ -90,7 +88,7 @@ public class Lazy implements IHolder { return new Lazy<>(() -> { ContainedType currVal = heldValue; - if (!valueMaterialized) { + if(!valueMaterialized) { currVal = valueSupplier.get(); } @@ -101,10 +99,8 @@ public class Lazy implements IHolder { @Override public String toString() { - if (valueMaterialized) { - if (actions.isEmpty()) { - return "value[v='" + heldValue + "']"; - } + if(valueMaterialized) { + if(actions.isEmpty()) return "value[v='" + heldValue + "']"; return "value[v='" + heldValue + "'] (has pending transforms)"; } @@ -121,7 +117,7 @@ public class Lazy implements IHolder { @Override public UnwrappedType unwrap(Function unwrapper) { - if (!valueMaterialized) { + if(!valueMaterialized) { heldValue = valueSupplier.get(); valueMaterialized = true; 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 29e37ac..59df1b1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java @@ -1,36 +1,36 @@ 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 - * + * * @author ben * * @param * The type on the left side of the pair * @param * The type on the right side of the pair - * + * */ public class LazyPair implements IPair { - private LeftType leftValue; - private RightType rightValue; + private LeftType leftValue; + private RightType rightValue; - private Supplier leftSupplier; - private Supplier rightSupplier; + private Supplier leftSupplier; + private Supplier rightSupplier; - private boolean leftMaterialized; - private boolean rightMaterialized; + private boolean leftMaterialized; + private boolean rightMaterialized; /** * Create a new lazy pair, using the set values - * + * * @param leftVal * The value for the left side of the pair * @param rightVal @@ -46,7 +46,7 @@ public class LazyPair implements IPair /** * Create a new lazy pair from the given value sources - * + * * @param leftSupp * The source for a value on the left side of the pair * @param rightSupp @@ -71,9 +71,7 @@ public class LazyPair implements IPair public IPair bindLeft( Function> leftBinder) { Supplier leftSupp = () -> { - if (leftMaterialized) { - return leftValue; - } + if(leftMaterialized) return leftValue; return leftSupplier.get(); }; @@ -85,9 +83,7 @@ public class LazyPair implements IPair public IPair bindRight( Function> rightBinder) { Supplier rightSupp = () -> { - if (rightMaterialized) { - return rightValue; - } + if(rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -110,7 +106,7 @@ public class LazyPair implements IPair @Override public LeftType getLeft() { - if (!leftMaterialized) { + if(!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; @@ -121,7 +117,7 @@ public class LazyPair implements IPair @Override public RightType getRight() { - if (!rightMaterialized) { + if(!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -133,17 +129,13 @@ public class LazyPair implements IPair @Override public IPair mapLeft(Function mapper) { Supplier leftSupp = () -> { - if (leftMaterialized) { - return mapper.apply(leftValue); - } + if(leftMaterialized) return mapper.apply(leftValue); return mapper.apply(leftSupplier.get()); }; Supplier rightSupp = () -> { - if (rightMaterialized) { - return rightValue; - } + if(rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -154,17 +146,13 @@ public class LazyPair implements IPair @Override public IPair mapRight(Function mapper) { Supplier leftSupp = () -> { - if (leftMaterialized) { - return leftValue; - } + if(leftMaterialized) return leftValue; return leftSupplier.get(); }; Supplier rightSupp = () -> { - if (rightMaterialized) { - return mapper.apply(rightValue); - } + if(rightMaterialized) return mapper.apply(rightValue); return mapper.apply(rightSupplier.get()); }; @@ -174,13 +162,13 @@ public class LazyPair implements IPair @Override public MergedType merge(BiFunction merger) { - if (!leftMaterialized) { + if(!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; } - if (!rightMaterialized) { + if(!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -193,7 +181,7 @@ public class LazyPair implements IPair public String toString() { StringBuilder sb = new StringBuilder("pair[l="); - if (leftMaterialized) { + if(leftMaterialized) { sb.append(leftValue.toString()); } else { sb.append("(un-materialized)"); @@ -201,7 +189,7 @@ public class LazyPair implements IPair sb.append(", r="); - if (rightMaterialized) { + if(rightMaterialized) { sb.append(rightValue.toString()); } else { sb.append("(un-materialized)"); 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 5c14475..84ea01d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java @@ -1,15 +1,15 @@ 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 - * + * * @author ben * * @param @@ -20,7 +20,7 @@ public class ListHolder implements IHolder { /** * Create a new list holder - * + * * @param values * The possible values for the computation */ @@ -28,8 +28,8 @@ public class ListHolder implements IHolder { public ListHolder(ContainedType... values) { heldValues = new FunctionalList<>(); - if (values != null) { - for (ContainedType containedValue : values) { + if(values != null) { + for(ContainedType containedValue : values) { heldValues.add(containedValue); } } 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 210d2aa..052e78a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java @@ -5,7 +5,7 @@ import java.util.function.UnaryOperator; /** * A holder that may or may not contain a value - * + * * @author ben * * @param @@ -16,7 +16,7 @@ public class Option implements IHolder { /** * Create a new optional, using the given initial value - * + * * @param seed * The initial value for the optional */ @@ -26,9 +26,7 @@ public class Option implements IHolder { @Override public IHolder bind(Function> binder) { - if (held == null) { - return new Option<>(null); - } + if(held == null) return new Option<>(null); return binder.apply(held); } @@ -42,16 +40,14 @@ public class Option implements IHolder { @Override public IHolder map(Function mapper) { - if (held == null) { - return new Option<>(null); - } + if(held == null) return new Option<>(null); return new Option<>(mapper.apply(held)); } @Override public IHolder transform(UnaryOperator transformer) { - if (held != null) { + if(held != null) { held = transformer.apply(held); } @@ -60,9 +56,7 @@ public class Option implements IHolder { @Override public UnwrappedType unwrap(Function unwrapper) { - if (held == null) { - return null; - } + if(held == null) return null; return unwrapper.apply(held); } 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 b22fd28..77afa4a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java @@ -5,7 +5,7 @@ import java.util.function.Function; /** * A pair of values, with nothing special about them. - * + * * @author ben * * @param @@ -29,7 +29,7 @@ public class Pair implements IPair { /** * Create a new pair with both sides set to the specified values - * + * * @param left * The value of the left side * @param right @@ -43,9 +43,7 @@ public class Pair implements IPair { @Override public IPair bind( BiFunction> binder) { - if (binder == null) { - throw new NullPointerException("Binder must not be null."); - } + if(binder == null) throw new NullPointerException("Binder must not be null."); return binder.apply(leftValue, rightValue); } @@ -53,9 +51,7 @@ public class Pair implements IPair { @Override public IPair bindLeft( Function> leftBinder) { - if (leftBinder == null) { - throw new NullPointerException("Binder must not be null"); - } + if(leftBinder == null) throw new NullPointerException("Binder must not be null"); return leftBinder.apply(leftValue); } @@ -63,9 +59,7 @@ public class Pair implements IPair { @Override public IPair bindRight( Function> rightBinder) { - if (rightBinder == null) { - throw new NullPointerException("Binder must not be null"); - } + if(rightBinder == null) throw new NullPointerException("Binder must not be null"); return rightBinder.apply(rightValue); } @@ -83,27 +77,21 @@ public class Pair implements IPair { @Override public IPair mapLeft(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(mapper.apply(leftValue), rightValue); } @Override public IPair mapRight(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(leftValue, mapper.apply(rightValue)); } @Override public MergedType merge(BiFunction merger) { - if (merger == null) { - throw new NullPointerException("Merger must not be null"); - } + if(merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftValue, rightValue); } 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 fde1197..4d79b92 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleIterator.java @@ -13,10 +13,12 @@ public class SingleIterator implements Iterator { yielded = false; } + @Override public boolean hasNext() { return !yielded; } + @Override public T next() { yielded = true; 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 bf8b0a0..76c9be2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java @@ -4,9 +4,9 @@ import java.util.function.Supplier; /** * A supplier that can only supply one value. - * + * * Attempting to retrieve another value will cause an exception to be thrown. - * + * * @author ben * * @param @@ -26,7 +26,7 @@ public class SingleSupplier implements Supplier { /** * Create a new single supplier from an existing value - * + * * @param supp * The supplier to give a single value from */ @@ -40,7 +40,7 @@ public class SingleSupplier implements Supplier { @Override public T get() { - if (gotten == true) { + if(gotten == true) { IllegalStateException isex = new IllegalStateException("Attempted to get value more than once" + " from single supplier #" + id + ". Previous instantiation below."); @@ -53,7 +53,7 @@ public class SingleSupplier implements Supplier { try { throw new IllegalStateException("Previous instantiation here."); - } catch (IllegalStateException isex) { + } catch(IllegalStateException isex) { instSite = isex; } 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 8a24512..2463df9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java @@ -8,25 +8,25 @@ import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; -import static bjc.utils.data.TopDownTransformResult.*; +import static bjc.utils.data.TopDownTransformResult.RTRANSFORM; public class TopDownTransformIterator implements Iterator> { - private Function picker; - private BiFunction, Consumer>>, ITree> transform; + private Function picker; + private BiFunction, Consumer>>, ITree> transform; - private ITree preParent; - private ITree postParent; + private ITree preParent; + private ITree postParent; - private Deque> preChildren; - private Deque> postChildren; + private Deque> preChildren; + private Deque> postChildren; private TopDownTransformIterator curChild; - private boolean done; - private boolean initial; + private boolean done; + private boolean initial; - private Deque>> toYield; - private Iterator> curYield; + private Deque>> toYield; + private Iterator> curYield; public TopDownTransformIterator(Function pickr, BiFunction, Consumer>>, ITree> transfrm, @@ -45,69 +45,67 @@ public class TopDownTransformIterator implements Iterator> src) { - if (curYield != null) { + if(curYield != null) { toYield.push(curYield); } curYield = src; } + @Override public boolean hasNext() { return !done; } public ITree flushYields(ITree val) { - if (curYield != null) { + if(curYield != null) { toYield.add(new SingleIterator<>(val)); - if (curYield.hasNext()) { + if(curYield.hasNext()) return curYield.next(); - } else { - while (toYield.size() != 0 && !curYield.hasNext()) { + else { + 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 { + } else return curYield.next(); - } } - } else { + } else return val; - } } + @Override public ITree 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()) { + else { + while(toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if (toYield.size() == 0 && !curYield.hasNext()) { + if(toYield.size() == 0 && !curYield.hasNext()) { curYield = null; - } else { + } else return curYield.next(); - } } } - if (initial) { + if(initial) { 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)); } @@ -127,8 +125,8 @@ public class TopDownTransformIterator implements Iterator implements Iterator(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)); } @@ -159,12 +157,13 @@ public class TopDownTransformIterator implements Iterator(picker, transform, preChildren.pop()); ITree res = curChild.next(); @@ -175,12 +174,12 @@ public class TopDownTransformIterator implements Iterator 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 child : postChildren) { + for(ITree child : postChildren) { res.addChild(child); } @@ -190,7 +189,7 @@ public class TopDownTransformIterator implements Iterator child : postChildren) { + for(ITree child : postChildren) { res.addChild(child); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java index 0db9482..ed41eae 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java @@ -2,7 +2,7 @@ package bjc.utils.data; /** * Represents the results for doing a top-down transform of a tree - * + * * @author ben * */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java index 742a73b..80de96f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java @@ -13,10 +13,12 @@ public class TransformedIterator implements Iterator @@ -19,16 +19,16 @@ import bjc.utils.funcdata.bst.TreeLinearizationMethod; public class Tree implements ITree { private ContainedType data; - private IList> children; - private boolean hasChildren; - private int childCount = 0; + private IList> children; + private boolean hasChildren; + private int childCount = 0; - private int ID; - private static int nextID = 0; + private int ID; + private static int nextID = 0; /** * Create a new leaf node in a tree - * + * * @param leaf * The data to store as a leaf node */ @@ -42,7 +42,7 @@ public class Tree implements ITree { /** * Create a new tree node with the specified children - * + * * @param leaf * The data to hold in this node * @param childrn @@ -58,7 +58,7 @@ public class Tree implements ITree { /** * Create a new tree node with the specified children - * + * * @param leaf * The data to hold in this node * @param childrn @@ -74,7 +74,7 @@ public class Tree implements ITree { children = new FunctionalList<>(); - for (ITree child : childrn) { + for(ITree child : childrn) { children.add(child); childCount++; @@ -83,7 +83,7 @@ public class Tree implements ITree { @Override public void addChild(ITree child) { - if (hasChildren == false) { + if(hasChildren == false) { hasChildren = true; children = new FunctionalList<>(); @@ -109,7 +109,7 @@ public class Tree implements ITree { @Override public ITree flatMapTree(Function> mapper) { - if (hasChildren) { + if(hasChildren) { ITree flatMappedData = mapper.apply(data); children.map((child) -> child.flatMapTree(mapper)) @@ -128,10 +128,10 @@ public class Tree implements ITree { protected NewType internalCollapse(Function leafTransform, Function, NewType>> nodeCollapser) { - if (hasChildren) { + if(hasChildren) { Function, NewType> nodeTransformer = nodeCollapser.apply(data); - IList collapsedChildren = (IList) children.map((child) -> { + IList collapsedChildren = children.map((child) -> { return child.collapse(leafTransform, nodeCollapser, (subTreeVal) -> subTreeVal); }); @@ -142,7 +142,7 @@ public class Tree implements ITree { } protected void internalToString(StringBuilder builder, int indentLevel, boolean initial) { - for (int i = 0; i < indentLevel; i++) { + for(int i = 0; i < indentLevel; i++) { builder.append(">\t"); } @@ -152,7 +152,7 @@ public class Tree implements ITree { builder.append(data == null ? "(null)" : data.toString()); builder.append("\n"); - if (hasChildren) { + if(hasChildren) { children.forEach((child) -> { ((Tree) child).internalToString(builder, indentLevel + 1, false); }); @@ -162,7 +162,7 @@ public class Tree implements ITree { @Override public ITree rebuildTree(Function leafTransformer, Function operatorTransformer) { - if (hasChildren) { + if(hasChildren) { IList> mappedChildren = children.map((child) -> { return child.rebuildTree(leafTransformer, operatorTransformer); }); @@ -175,7 +175,7 @@ public class Tree implements ITree { @Override public void selectiveTransform(Predicate nodePicker, UnaryOperator transformer) { - if (hasChildren) { + if(hasChildren) { children.forEach((child) -> child.selectiveTransform(nodePicker, transformer)); } else { data = transformer.apply(data); @@ -187,11 +187,11 @@ public class Tree implements ITree { UnaryOperator> transformer) { TopDownTransformResult transformResult = transformPicker.apply(data); - switch (transformResult) { + switch(transformResult) { case PASSTHROUGH: ITree result = new Tree<>(data); - if (hasChildren) { + if(hasChildren) { children.forEach((child) -> { result.addChild(child.topDownTransform(transformPicker, transformer)); }); @@ -207,7 +207,7 @@ public class Tree implements ITree { case PUSHDOWN: result = new Tree<>(data); - if (hasChildren) { + if(hasChildren) { children.forEach((child) -> { result.addChild(child.topDownTransform(transformPicker, transformer)); }); @@ -244,9 +244,8 @@ public class Tree implements ITree { @Override public TransformedType transformChild(int childNo, Function, TransformedType> transformer) { - if (childNo < 0 || childNo > (childCount - 1)) { + if(childNo < 0 || childNo > childCount - 1) throw new IllegalArgumentException("Child index #" + childNo + " is invalid"); - } return transformer.apply(children.getByIndex(childNo)); } @@ -258,7 +257,7 @@ public class Tree implements ITree { @Override public ITree transformTree(Function transformer) { - if (hasChildren) { + if(hasChildren) { IList> transformedChildren = children .map((child) -> child.transformTree(transformer)); @@ -270,13 +269,11 @@ public class Tree implements ITree { @Override public void traverse(TreeLinearizationMethod linearizationMethod, Consumer action) { - if (hasChildren) { - switch (linearizationMethod) { + if(hasChildren) { + switch(linearizationMethod) { case INORDER: - if (childCount != 2) { - throw new IllegalArgumentException( - "Can only do in-order traversal for binary trees."); - } + if(childCount != 2) throw new IllegalArgumentException( + "Can only do in-order traversal for binary trees."); children.getByIndex(0).traverse(linearizationMethod, action); @@ -303,32 +300,26 @@ public class Tree implements ITree { } } + @Override public boolean equals(Object other) { - if (!(other instanceof Tree)) - return false; + if(!(other instanceof Tree)) return false; @SuppressWarnings("unchecked") Tree otr = (Tree) other; - if (!otr.data.equals(data)) - return false; + if(!otr.data.equals(data)) return false; - if (children == null && otr.children == null) - return true; + if(children == null && otr.children == null) return true; - if (children == null && otr.children != null) - return false; - if (children != null && otr.children == null) - return false; + if(children == null && otr.children != null) return false; + if(children != null && otr.children == null) return false; - if (children.getSize() != otr.children.getSize()) - return false; + if(children.getSize() != otr.children.getSize()) return false; int childNo = 0; - for (ITree child : children) { - if (!otr.children.getByIndex(childNo).equals(child)) - return false; + for(ITree child : children) { + if(!otr.children.getByIndex(childNo).equals(child)) return false; childNo += 1; } 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 57bf006..0ec69f0 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 */ @@ -48,9 +48,7 @@ public class BoundLazy implements IHolder IHolder bind(Function> bindr) { - if (bindr == null) { - throw new NullPointerException("Binder must not be null"); - } + if(bindr == null) throw new NullPointerException("Binder must not be null"); /* * Prepare a list of pending actions @@ -67,7 +65,7 @@ public class BoundLazy implements IHolder implements IHolder Function> lift( Function func) { - if (func == null) { - throw new NullPointerException("Function to lift must not be null"); - } + if(func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { return new Lazy<>(func.apply(val)); @@ -96,9 +92,7 @@ public class BoundLazy implements IHolder IHolder map(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); // Prepare a list of pending actions IList> pendingActions = new FunctionalList<>(); @@ -109,7 +103,7 @@ public class BoundLazy implements IHolder oldHolder = boundHolder; // Bound the value if it hasn't been bound - if (!holderBound) { + if(!holderBound) { oldHolder = oldSupplier.get().unwrap(binder); } @@ -123,18 +117,14 @@ public class BoundLazy implements IHolder transform(UnaryOperator transformer) { - if (transformer == null) { - throw new NullPointerException("Transformer must not be null"); - } + if(transformer == null) throw new NullPointerException("Transformer must not be null"); actions.add(transformer); @@ -143,11 +133,9 @@ public class BoundLazy implements IHolder UnwrappedType unwrap(Function unwrapper) { - if (unwrapper == null) { - throw new NullPointerException("Unwrapper must not be null"); - } + if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); - if (!holderBound) { + if(!holderBound) { boundHolder = oldSupplier.get().unwrap(binder::apply); } 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 d425d99..6ab8121 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 */ @@ -47,15 +47,13 @@ public class BoundLazyPair implements IPai @Override public IPair bind( BiFunction> bindr) { - if (bindr == null) { - throw new NullPointerException("Binder must not be null"); - } + if(bindr == null) throw new NullPointerException("Binder must not be null"); IHolder> newPair = new Identity<>(boundPair); IHolder newPairMade = new Identity<>(pairBound); Supplier leftSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); @@ -65,7 +63,7 @@ public class BoundLazyPair implements IPai }; Supplier rightSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); @@ -80,14 +78,12 @@ public class BoundLazyPair implements IPai @Override public IPair bindLeft( Function> leftBinder) { - if (leftBinder == null) { - throw new NullPointerException("Left binder must not be null"); - } + if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); Supplier leftSupp = () -> { IPair newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -100,14 +96,12 @@ public class BoundLazyPair implements IPai @Override public IPair bindRight( Function> rightBinder) { - if (rightBinder == null) { - throw new NullPointerException("Right binder must not be null"); - } + if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); Supplier rightSupp = () -> { IPair newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -122,13 +116,11 @@ public class BoundLazyPair implements IPai IPair otherPair, BiFunction leftCombiner, BiFunction rightCombiner) { - if (otherPair == null) { + 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) -> { @@ -140,12 +132,10 @@ public class BoundLazyPair implements IPai @Override public IPair mapLeft(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); Supplier leftSupp = () -> { - if (!pairBound) { + if(!pairBound) { NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return mapper.apply(leftVal); @@ -155,9 +145,7 @@ public class BoundLazyPair implements IPai }; Supplier rightSupp = () -> { - if (!pairBound) { - return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); - } + if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return boundPair.getRight(); }; @@ -167,20 +155,16 @@ public class BoundLazyPair implements IPai @Override public IPair mapRight(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); Supplier leftSupp = () -> { - if (!pairBound) { - return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); - } + if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return boundPair.getLeft(); }; Supplier rightSupp = () -> { - if (!pairBound) { + if(!pairBound) { NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return mapper.apply(rightVal); @@ -194,11 +178,9 @@ public class BoundLazyPair implements IPai @Override public MergedType merge(BiFunction merger) { - if (merger == null) { - throw new NullPointerException("Merger must not be null"); - } + if(merger == null) throw new NullPointerException("Merger must not be null"); - if (!pairBound) { + if(!pairBound) { boundPair = binder.apply(leftSupplier.get(), rightSupplier.get()); pairBound = true; @@ -209,9 +191,7 @@ public class BoundLazyPair 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 f363b7e..467d55d 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,12 +1,12 @@ 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 */ @@ -19,9 +19,7 @@ public class BoundListHolder implements IHolder { @Override public IHolder bind(Function> binder) { - if (binder == null) { - throw new NullPointerException("Binder must not be null"); - } + if(binder == null) throw new NullPointerException("Binder must not be null"); IList> boundHolders = heldHolders.map((containedHolder) -> { return containedHolder.bind(binder); @@ -32,9 +30,7 @@ public class BoundListHolder implements IHolder { @Override public Function> lift(Function func) { - if (func == null) { - throw new NullPointerException("Function to lift must not be null"); - } + if(func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { return new ListHolder<>(func.apply(val)); @@ -43,9 +39,7 @@ public class BoundListHolder implements IHolder { @Override public IHolder map(Function mapper) { - if (mapper == null) { - throw new NullPointerException("Mapper must not be null"); - } + if(mapper == null) throw new NullPointerException("Mapper must not be null"); IList> mappedHolders = heldHolders.map((containedHolder) -> { return containedHolder.map(mapper); @@ -56,9 +50,7 @@ public class BoundListHolder implements IHolder { @Override public IHolder transform(UnaryOperator transformer) { - if (transformer == null) { - throw new NullPointerException("Transformer must not be null"); - } + if(transformer == null) throw new NullPointerException("Transformer must not be null"); heldHolders.forEach((containedHolder) -> { containedHolder.transform(transformer); @@ -69,9 +61,7 @@ public class BoundListHolder implements IHolder { @Override public UnwrappedType unwrap(Function unwrapper) { - if (unwrapper == null) { - throw new NullPointerException("Unwrapper must not be null"); - } + 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 a8bdb6a..c5e9c9f 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,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; + /* * A lazy pair, with only one side bound */ @@ -17,8 +17,8 @@ public class HalfBoundLazyPair implements IPair> binder; - private IPair boundPair; - private boolean pairBound; + private IPair boundPair; + private boolean pairBound; public HalfBoundLazyPair(Supplier oldSupp, Function> bindr) { oldSupplier = oldSupp; @@ -32,7 +32,7 @@ public class HalfBoundLazyPair implements IPair newPairMade = new Identity<>(pairBound); Supplier leftSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } @@ -41,7 +41,7 @@ public class HalfBoundLazyPair implements IPair rightSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } @@ -58,7 +58,7 @@ public class HalfBoundLazyPair implements IPair leftSupp = () -> { IPair newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -74,7 +74,7 @@ public class HalfBoundLazyPair implements IPair rightSupp = () -> { IPair newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -100,9 +100,7 @@ public class HalfBoundLazyPair implements IPair IPair mapLeft(Function mapper) { Supplier leftSupp = () -> { - if (pairBound) { - return mapper.apply(boundPair.getLeft()); - } + if(pairBound) return mapper.apply(boundPair.getLeft()); NewLeft leftVal = binder.apply(oldSupplier.get()).getLeft(); @@ -110,9 +108,7 @@ public class HalfBoundLazyPair implements IPair rightSupp = () -> { - if (pairBound) { - return boundPair.getRight(); - } + if(pairBound) return boundPair.getRight(); return binder.apply(oldSupplier.get()).getRight(); }; @@ -123,17 +119,13 @@ public class HalfBoundLazyPair implements IPair IPair mapRight(Function mapper) { Supplier leftSupp = () -> { - if (pairBound) { - return boundPair.getLeft(); - } + if(pairBound) return boundPair.getLeft(); return binder.apply(oldSupplier.get()).getLeft(); }; Supplier rightSupp = () -> { - if (pairBound) { - return mapper.apply(boundPair.getRight()); - } + if(pairBound) return mapper.apply(boundPair.getRight()); NewRight rightVal = binder.apply(oldSupplier.get()).getRight(); @@ -145,7 +137,7 @@ public class HalfBoundLazyPair implements IPair MergedType merge(BiFunction merger) { - if (!pairBound) { + 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 7f0b8db..f400345 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,11 +1,11 @@ package bjc.utils.data.internals; -import java.util.function.Function; -import java.util.function.UnaryOperator; - import bjc.utils.data.IHolder; import bjc.utils.data.Lazy; +import java.util.function.Function; +import java.util.function.UnaryOperator; + public class WrappedLazy implements IHolder { private IHolder> held; 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 2b03f62..1639351 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,11 +1,11 @@ package bjc.utils.data.internals; -import java.util.function.Function; -import java.util.function.UnaryOperator; - import bjc.utils.data.IHolder; import bjc.utils.data.Option; +import java.util.function.Function; +import java.util.function.UnaryOperator; + public class WrappedOption implements IHolder { private IHolder> held; @@ -21,9 +21,7 @@ public class WrappedOption implements IHolder { public IHolder bind(Function> binder) { IHolder> 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); }); @@ -43,9 +41,7 @@ public class WrappedOption implements IHolder { public IHolder map(Function mapper) { IHolder> newHolder = held.map((containedHolder) -> { return containedHolder.map((containedValue) -> { - if (containedValue == null) { - return null; - } + if(containedValue == null) return null; return mapper.apply(containedValue); }); @@ -58,9 +54,7 @@ public class WrappedOption implements IHolder { public IHolder transform(UnaryOperator transformer) { held.transform((containedHolder) -> { return containedHolder.transform((containedValue) -> { - if (containedValue == null) { - return null; - } + if(containedValue == null) return null; return transformer.apply(containedValue); }); @@ -73,9 +67,7 @@ public class WrappedOption implements IHolder { public UnwrappedType unwrap(Function 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/Directory.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java index 6fdfe16..79ae031 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java @@ -37,17 +37,17 @@ public interface Directory { /** * Insert a sub-directory into the dictionary. - * + * * @param key * The name of the new sub-directory * @param value * The sub-directory to insert - * + * * @return The old sub-directory attached to this key, or null if such a * sub-directory didn't exist */ Directory putSubdirectory(K key, Directory value); - + /** * Create a new sub-directory. * @@ -60,14 +60,12 @@ public interface Directory { * exists. */ default Directory newSubdirectory(K key) { - if(hasSubdirectory(key)) { - return null; - } - + if(hasSubdirectory(key)) return null; + Directory dir = new SimpleDirectory<>(); - + putSubdirectory(key, dir); - + return 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 85abbdc..6e256b6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java @@ -16,7 +16,7 @@ package bjc.utils.esodata; * * All operations that refer to the tape refer to the currently active side of * the tape, except for flip. - * + * * Flip refers to the entire tape for 'obvious' reasons. * * @param T @@ -24,8 +24,8 @@ package bjc.utils.esodata; * @author bjculkin */ public class DoubleTape implements Tape { - private Tape front; - private Tape back; + private Tape front; + private Tape back; /** * Create a new empty double-sided tape that doesn't autoextend. @@ -52,6 +52,7 @@ public class DoubleTape implements Tape { * * @return The item the tape is on. */ + @Override public T item() { return front.item(); } @@ -62,6 +63,7 @@ public class DoubleTape implements Tape { * @param itm * The new value for the tape item. */ + @Override public void item(T itm) { front.item(itm); } @@ -71,6 +73,7 @@ public class DoubleTape implements Tape { * * @return The current number of elements in the tape. */ + @Override public int size() { return front.size(); } @@ -81,6 +84,7 @@ public class DoubleTape implements Tape { * @param itm * The item to add. */ + @Override public void insertBefore(T itm) { front.insertBefore(itm); back.insertAfter(null); @@ -89,6 +93,7 @@ public class DoubleTape implements Tape { /** * Insert an element after the current item. */ + @Override public void insertAfter(T itm) { front.insertAfter(itm); back.insertBefore(itm); @@ -96,12 +101,13 @@ public class DoubleTape implements Tape { /** * Remove the current element. - * + * * Also moves the cursor back one step if possible to maintain relative * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ + @Override public T remove() { back.remove(); @@ -111,6 +117,7 @@ public class DoubleTape implements Tape { /** * Move the cursor to the left-most position. */ + @Override public void first() { front.first(); back.last(); @@ -119,6 +126,7 @@ public class DoubleTape implements Tape { /** * Move the cursor the right-most position. */ + @Override public void last() { front.last(); back.first(); @@ -131,6 +139,7 @@ public class DoubleTape implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left() { return left(1); } @@ -146,11 +155,13 @@ public class DoubleTape implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left(int amt) { boolean succ = front.left(amt); - if (succ) + if(succ) { back.right(amt); + } return succ; } @@ -162,6 +173,7 @@ public class DoubleTape implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right() { return right(1); } @@ -176,11 +188,13 @@ public class DoubleTape implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right(int amt) { boolean succ = front.right(amt); - if (succ) + if(succ) { back.left(amt); + } return succ; } 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 22a7e56..3c1ced5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleDirectory.java @@ -5,13 +5,15 @@ import bjc.utils.funcdata.IMap; /** * Simple implementation of {@link Directory}. - * + * * Has a split namespace for data and children. - * + * * @author EVE * - * @param The key type of the directory. - * @param The value type of the directory. + * @param + * The key type of the directory. + * @param + * The value type of the directory. */ public class SimpleDirectory implements Directory { private IMap> children; 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 a323ba4..22b869e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java @@ -19,8 +19,8 @@ import java.util.ArrayList; * @author bjculkin */ public class SingleTape implements Tape { - protected ArrayList backing; - protected int pos; + protected ArrayList backing; + protected int pos; protected boolean autoExtend; @@ -50,6 +50,7 @@ public class SingleTape implements Tape { * * @return The item the tape is on. */ + @Override public T item() { return backing.get(pos); } @@ -60,6 +61,7 @@ public class SingleTape implements Tape { * @param itm * The new value for the tape item. */ + @Override public void item(T itm) { backing.set(pos, itm); } @@ -69,6 +71,7 @@ public class SingleTape implements Tape { * * @return The current number of elements in the tape. */ + @Override public int size() { return backing.size(); } @@ -79,6 +82,7 @@ public class SingleTape implements Tape { * @param itm * The item to add. */ + @Override public void insertBefore(T itm) { backing.add(pos, itm); } @@ -86,31 +90,36 @@ public class SingleTape implements Tape { /** * Insert an element after the current item. */ + @Override public void insertAfter(T itm) { - if (pos == (backing.size() - 1)) + if(pos == backing.size() - 1) { backing.add(itm); - else + } else { backing.add(pos + 1, itm); + } } /** * Remove the current element. - * + * * Also moves the cursor back one step if possible to maintain relative * position. * * @return The removed item. */ + @Override public T remove() { T res = backing.remove(pos); - if (pos != 0) + if(pos != 0) { pos -= 1; + } return res; } /** * Move the cursor to the left-most position. */ + @Override public void first() { pos = 0; } @@ -118,6 +127,7 @@ public class SingleTape implements Tape { /** * Move the cursor the right-most position. */ + @Override public void last() { pos = backing.size() - 1; } @@ -129,6 +139,7 @@ public class SingleTape implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left() { return left(1); } @@ -144,9 +155,9 @@ public class SingleTape implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left(int amt) { - if ((pos - amt) < 0) - return false; + if(pos - amt < 0) return false; pos -= amt; return true; @@ -159,6 +170,7 @@ public class SingleTape implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right() { return right(1); } @@ -173,15 +185,15 @@ public class SingleTape implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right(int amt) { - if ((pos + amt) >= (backing.size() - 1)) { - if (autoExtend) { - while ((pos + amt) >= (backing.size() - 1)) { + if(pos + amt >= backing.size() - 1) { + if(autoExtend) { + while(pos + amt >= backing.size() - 1) { backing.add(null); } - } else { + } else return false; - } } pos += amt; 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 c650cdc..c5e338b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java @@ -31,18 +31,14 @@ class SpaghettiStack extends Stack { @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(); } 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 21a922d..5f7be6c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java @@ -65,7 +65,7 @@ public abstract class Stack { * The number of items to drop. */ public void drop(int n) { - for (int i = 0; i < n; i++) { + for(int i = 0; i < n; i++) { pop(); } } @@ -109,12 +109,12 @@ public abstract class Stack { public void multidup(int n, int m) { List lst = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for (int i = 0; i < m; i++) { - for (T elm : lst) { + for(int i = 0; i < m; i++) { + for(T elm : lst) { push(elm); } } @@ -150,17 +150,17 @@ public abstract class Stack { T elm = pop(); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for (T nelm : lst) { + for(T nelm : lst) { push(nelm); } push(elm); - for (int i = 1; i < m; i++) { - for (T nelm : lst) { + for(int i = 1; i < m; i++) { + for(T nelm : lst) { push(nelm); } } @@ -273,13 +273,13 @@ public abstract class Stack { public void dip(int n, Consumer> cons) { List elms = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { elms.set(i - 1, pop()); } cons.accept(this); - for (T elm : elms) { + for(T elm : elms) { push(elm); } } @@ -319,12 +319,12 @@ public abstract class Stack { public void multicleave(int n, List>> conses) { List elms = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { elms.set(i - 1, pop()); } - for (Consumer> cons : conses) { - for (T elm : elms) { + for(Consumer> cons : conses) { + for(T elm : elms) { push(elm); } @@ -353,10 +353,10 @@ public abstract class Stack { public void multispread(int n, List>> conses) { List> nelms = new ArrayList<>(conses.size()); - for (int i = conses.size(); i > 0; i--) { + for(int i = conses.size(); i > 0; i--) { List elms = new ArrayList<>(n); - for (int j = n; j > 0; j--) { + for(int j = n; j > 0; j--) { elms.set(j, pop()); } @@ -364,8 +364,8 @@ public abstract class Stack { } int i = 0; - for (List elms : nelms) { - for (T elm : elms) { + for(List elms : nelms) { + for(T elm : elms) { push(elm); } @@ -396,7 +396,7 @@ public abstract class Stack { public void multiapply(int n, int m, Consumer> cons) { List>> conses = new ArrayList<>(m); - for (int i = 0; i < m; i++) { + for(int i = 0; i < m; i++) { conses.add(cons); } 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 3d4e0b1..3b3a9a7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java @@ -49,7 +49,7 @@ public interface Tape { /** * Remove the current element. - * + * * Also moves the cursor back one step if possible to maintain relative * position. * 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 4030960..fa3e61c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java @@ -5,7 +5,7 @@ package bjc.utils.esodata; * * It has a current tape that you can do operations to, but also operations to * add/remove other tapes. - * + * * If there is no tape currently loaded into the changer, all the methods will * either return null/false. * @@ -13,8 +13,8 @@ package bjc.utils.esodata; * The element type of the tapes. */ public class TapeChanger implements Tape { - private Tape> tapes; - private Tape currentTape; + private Tape> tapes; + private Tape currentTape; /** * Create a new empty tape changer. @@ -37,7 +37,7 @@ public class TapeChanger implements Tape { tapes.insertBefore(current); - for (Tape tp : others) { + for(Tape tp : others) { tapes.insertAfter(tp); tapes.right(); } @@ -51,9 +51,9 @@ public class TapeChanger implements Tape { * * @return The item the tape is on. */ + @Override public T item() { - if (currentTape == null) - return null; + if(currentTape == null) return null; return currentTape.item(); } @@ -64,9 +64,9 @@ public class TapeChanger implements Tape { * @param itm * The new value for the tape item. */ + @Override public void item(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.item(itm); } @@ -76,9 +76,9 @@ public class TapeChanger implements Tape { * * @return The current number of elements in the tape. */ + @Override public int size() { - if (currentTape == null) - return 0; + if(currentTape == null) return 0; return currentTape.size(); } @@ -89,9 +89,9 @@ public class TapeChanger implements Tape { * @param itm * The item to add. */ + @Override public void insertBefore(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.insertBefore(itm); } @@ -99,24 +99,24 @@ public class TapeChanger implements Tape { /** * Insert an element after the current item. */ + @Override public void insertAfter(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.insertAfter(itm); } /** * Remove the current element. - * + * * Also moves the cursor back one step if possible to maintain relative * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ + @Override public T remove() { - if (currentTape == null) - return null; + if(currentTape == null) return null; return currentTape.remove(); } @@ -124,9 +124,9 @@ public class TapeChanger implements Tape { /** * Move the cursor to the left-most position. */ + @Override public void first() { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.first(); } @@ -134,9 +134,9 @@ public class TapeChanger implements Tape { /** * Move the cursor the right-most position. */ + @Override public void last() { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.last(); } @@ -148,6 +148,7 @@ public class TapeChanger implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left() { return left(1); } @@ -163,9 +164,9 @@ public class TapeChanger implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left(int amt) { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.left(amt); } @@ -177,6 +178,7 @@ public class TapeChanger implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right() { return right(1); } @@ -191,9 +193,9 @@ public class TapeChanger implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right(int amt) { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.right(amt); } @@ -207,18 +209,16 @@ public class TapeChanger implements Tape { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) - return; + if(currentTape == null) return; - if (currentTape.isDoubleSided()) { + if(currentTape.isDoubleSided()) { ((DoubleTape) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -243,8 +243,9 @@ public class TapeChanger implements Tape { public boolean nextTape() { boolean succ = tapes.right(); - if (succ) + if(succ) { currentTape = tapes.item(); + } return succ; } @@ -260,8 +261,9 @@ public class TapeChanger implements Tape { public boolean prevTape() { boolean succ = tapes.left(); - if (succ) + if(succ) { currentTape = tapes.item(); + } return succ; } @@ -293,8 +295,7 @@ public class TapeChanger implements Tape { * @return The removed tape. */ public Tape removeTape() { - if (currentTape == null) - return null; + if(currentTape == null) return null; Tape tp = tapes.remove(); currentTape = tapes.item(); 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 3a49175..732f579 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java @@ -8,7 +8,7 @@ import java.util.Map; * * It has a current tape that you can do operations to, but also operations to * add/remove other tapes. - * + * * If there is no tape currently loaded into the changer, all the methods will * either return null/false. * @@ -16,8 +16,8 @@ import java.util.Map; * The element type of the tapes. */ public class TapeLibrary implements Tape { - private Map> tapes; - private Tape currentTape; + private Map> tapes; + private Tape currentTape; /** * Create a new empty tape library. @@ -31,9 +31,9 @@ public class TapeLibrary implements Tape { * * @return The item the tape is on. */ + @Override public T item() { - if (currentTape == null) - return null; + if(currentTape == null) return null; return currentTape.item(); } @@ -44,9 +44,9 @@ public class TapeLibrary implements Tape { * @param itm * The new value for the tape item. */ + @Override public void item(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.item(itm); } @@ -56,9 +56,9 @@ public class TapeLibrary implements Tape { * * @return The current number of elements in the tape. */ + @Override public int size() { - if (currentTape == null) - return 0; + if(currentTape == null) return 0; return currentTape.size(); } @@ -69,9 +69,9 @@ public class TapeLibrary implements Tape { * @param itm * The item to add. */ + @Override public void insertBefore(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.insertBefore(itm); } @@ -79,24 +79,24 @@ public class TapeLibrary implements Tape { /** * Insert an element after the current item. */ + @Override public void insertAfter(T itm) { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.insertAfter(itm); } /** * Remove the current element. - * + * * Also moves the cursor back one step if possible to maintain relative * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ + @Override public T remove() { - if (currentTape == null) - return null; + if(currentTape == null) return null; return currentTape.remove(); } @@ -104,9 +104,9 @@ public class TapeLibrary implements Tape { /** * Move the cursor to the left-most position. */ + @Override public void first() { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.first(); } @@ -114,9 +114,9 @@ public class TapeLibrary implements Tape { /** * Move the cursor the right-most position. */ + @Override public void last() { - if (currentTape == null) - return; + if(currentTape == null) return; currentTape.last(); } @@ -128,6 +128,7 @@ public class TapeLibrary implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left() { return left(1); } @@ -143,9 +144,9 @@ public class TapeLibrary implements Tape { * * @return True if the cursor was moved left. */ + @Override public boolean left(int amt) { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.left(amt); } @@ -157,6 +158,7 @@ public class TapeLibrary implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right() { return right(1); } @@ -171,9 +173,9 @@ public class TapeLibrary implements Tape { * * @return Whether the cursor was moved right. */ + @Override public boolean right(int amt) { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.right(amt); } @@ -187,18 +189,16 @@ public class TapeLibrary implements Tape { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) - return; + if(currentTape == null) return; - if (currentTape.isDoubleSided()) { + if(currentTape.isDoubleSided()) { ((DoubleTape) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if (currentTape == null) - return false; + if(currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -224,7 +224,7 @@ public class TapeLibrary implements Tape { * @return Whether or not the next tape was loaded. */ public boolean switchTape(String label) { - if (tapes.containsKey(label)) { + if(tapes.containsKey(label)) { currentTape = tapes.get(label); 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 187474c..d4c5081 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/UnifiedDirectory.java @@ -5,9 +5,9 @@ import bjc.utils.funcdata.IMap; /** * Simple implementation of {@link Directory}. - * + * * Has a unified namespace for data and children. - * + * * @author EVE * * @param @@ -40,9 +40,8 @@ public class UnifiedDirectory implements Directory { @Override public Directory putSubdirectory(K key, Directory val) { - if(data.containsKey(key)) { + if(data.containsKey(key)) throw new IllegalArgumentException("Key " + key + " is already used for data."); - } return children.put(key, val); } @@ -59,10 +58,9 @@ public class UnifiedDirectory implements Directory { @Override public V putKey(K key, V val) { - if(children.containsKey(key)) { + if(children.containsKey(key)) throw new IllegalArgumentException("Key " + key + " is already used for sub-directories."); - } - + return data.put(key, val); } } \ No newline at end of file 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 d70b5bd..c60d95c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java @@ -4,7 +4,7 @@ import java.io.IOException; /** * Represents the user failing to choose a file. - * + * * @author ben * */ @@ -21,7 +21,7 @@ public class FileNotChosenException extends IOException { /** * Create a new exception with the given cause - * + * * @param cause * The cause of why the exception was thrown */ 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 f6ad517..088b7eb 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java @@ -4,7 +4,7 @@ import java.util.InputMismatchException; /** * The exception to throw whenever a pragma is used with invalid syntax - * + * * @author ben * */ @@ -21,7 +21,7 @@ public class PragmaFormatException extends InputMismatchException { /** * Create a new exception with the given message - * + * * @param message * The message to explain why the exception was thrown */ 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 7164bea..ad399cb 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java @@ -4,7 +4,7 @@ import java.util.InputMismatchException; /** * Represents a error from encountering a unknown pragma - * + * * @author ben * */ @@ -14,7 +14,7 @@ public class UnknownPragmaException extends InputMismatchException { /** * Create a new exception with the given cause - * + * * @param cause * The cause for throwing this exception */ 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 7e6c23b..7db6cea 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java @@ -1,11 +1,11 @@ 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 implements IMap { private IMap delegate; @@ -23,9 +23,7 @@ class ExtendedMap implements IMap { @Override public boolean containsKey(KeyType key) { - if (store.containsKey(key)) { - return true; - } + if(store.containsKey(key)) return true; return delegate.containsKey(key); } @@ -58,9 +56,7 @@ class ExtendedMap implements IMap { @Override public ValueType get(KeyType key) { - if (store.containsKey(key)) { - return store.get(key); - } + if(store.containsKey(key)) return store.get(key); return delegate.get(key); } 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 f98f32c..1e52d05 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -1,5 +1,10 @@ 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; @@ -12,18 +17,13 @@ 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. * * Differs from a stream in every way except for the fact that they both provide * functional operations. - * + * * @author ben * * @param @@ -44,9 +44,9 @@ public class FunctionalList implements Cloneable, IList { /** * Create a new functional list containing the specified items. - * + * * Takes O(n) time, where n is the number of items specified - * + * * @param items * The items to put into this functional list. */ @@ -54,14 +54,14 @@ public class FunctionalList implements Cloneable, IList { public FunctionalList(E... items) { wrapped = new ArrayList<>(items.length); - for (E item : items) { + for(E item : items) { wrapped.add(item); } } /** * Create a new functional list with the specified size. - * + * * @param size * The size of the backing list . */ @@ -71,16 +71,14 @@ public class FunctionalList implements Cloneable, IList { /** * Create a new functional list as a wrapper of a existing list. - * + * * Takes O(1) time, since it doesn't copy the list. - * + * * @param backing * The list to use as a backing list. */ public FunctionalList(List backing) { - if (backing == null) { - throw new NullPointerException("Backing list must be non-null"); - } + if(backing == null) throw new NullPointerException("Backing list must be non-null"); wrapped = backing; } @@ -92,15 +90,12 @@ public class FunctionalList implements Cloneable, IList { @Override public boolean allMatch(Predicate predicate) { - if (predicate == null) { - throw new NullPointerException("Predicate must be non-null"); - } + if(predicate == null) throw new NullPointerException("Predicate must be non-null"); - for (E item : wrapped) { - if (!predicate.test(item)) { - // We've found a non-matching item + for(E item : wrapped) { + if(!predicate.test(item)) // We've found a non-matching + // item return false; - } } // All of the items matched @@ -109,15 +104,11 @@ public class FunctionalList implements Cloneable, IList { @Override public boolean anyMatch(Predicate predicate) { - if (predicate == null) { - throw new NullPointerException("Predicate must be not null"); - } + if(predicate == null) throw new NullPointerException("Predicate must be not null"); - for (E item : wrapped) { - if (predicate.test(item)) { - // We've found a matching item + for(E item : wrapped) { + if(predicate.test(item)) // We've found a matching item return true; - } } // We didn't find a matching item @@ -126,16 +117,16 @@ public class FunctionalList implements Cloneable, IList { /** * Clone this list into a new one, and clone the backing list as well - * + * * Takes O(n) time, where n is the number of elements in the list - * + * * @return A list */ @Override public IList clone() { IList cloned = new FunctionalList<>(); - for (E element : wrapped) { + for(E element : wrapped) { cloned.add(element); } @@ -144,19 +135,16 @@ public class FunctionalList implements Cloneable, IList { @Override public IList combineWith(IList rightList, BiFunction itemCombiner) { - if (rightList == null) { + 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 returned = new FunctionalList<>(); // Get the iterator for the other list Iterator rightIterator = rightList.toIterable().iterator(); - for (Iterator leftIterator = wrapped.iterator(); leftIterator.hasNext() - && rightIterator.hasNext();) { + for(Iterator leftIterator = wrapped.iterator(); leftIterator.hasNext() && rightIterator.hasNext();) { // Add the transformed items to the result list E leftVal = leftIterator.next(); T rightVal = rightIterator.next(); @@ -175,27 +163,21 @@ public class FunctionalList implements Cloneable, IList { @Override public E first() { - if (wrapped.size() < 1) { - throw new NoSuchElementException("Attempted to get first element of empty list"); - } + if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to get first element of empty list"); return wrapped.get(0); } @Override public IList flatMap(Function> expander) { - if (expander == null) { - throw new NullPointerException("Expander must not be null"); - } + if(expander == null) throw new NullPointerException("Expander must not be null"); IList returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { IList 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); @@ -204,19 +186,16 @@ public class FunctionalList implements Cloneable, IList { return returned; } + @Override public void forEach(Consumer action) { - if (action == null) { - throw new NullPointerException("Action is null"); - } + if(action == null) throw new NullPointerException("Action is null"); wrapped.forEach(action); } @Override public void forEachIndexed(BiConsumer indexedAction) { - if (indexedAction == null) { - throw new NullPointerException("Action must not be null"); - } + if(indexedAction == null) throw new NullPointerException("Action must not be null"); // This is held b/c ref'd variables must be final/effectively // final @@ -238,7 +217,7 @@ public class FunctionalList implements Cloneable, IList { /** * Get the internal backing list. - * + * * @return The backing list this list is based off of. */ public List getInternal() { @@ -247,14 +226,12 @@ public class FunctionalList implements Cloneable, IList { @Override public IList getMatching(Predicate predicate) { - if (predicate == null) { - throw new NullPointerException("Predicate must not be null"); - } + if(predicate == null) throw new NullPointerException("Predicate must not be null"); IList returned = new FunctionalList<>(); wrapped.forEach((element) -> { - if (predicate.test(element)) { + if(predicate.test(element)) { // The item matches, so add it to the returned // list returned.add(element); @@ -283,9 +260,7 @@ public class FunctionalList implements Cloneable, IList { @Override public IList map(Function elementTransformer) { - if (elementTransformer == null) { - throw new NullPointerException("Transformer must be not null"); - } + if(elementTransformer == null) throw new NullPointerException("Transformer must be not null"); IList returned = new FunctionalList<>(this.wrapped.size()); @@ -304,10 +279,9 @@ public class FunctionalList implements Cloneable, IList { @Override public IList> partition(int numberPerPartition) { - if (numberPerPartition < 1 || numberPerPartition > wrapped.size()) { + if(numberPerPartition < 1 || numberPerPartition > wrapped.size()) throw new IllegalArgumentException("" + numberPerPartition + " is an invalid partition size. Must be between 1 and " + wrapped.size()); - } IList> returned = new FunctionalList<>(); @@ -315,7 +289,7 @@ public class FunctionalList implements Cloneable, IList { IHolder> currentPartition = new Identity<>(new FunctionalList<>()); this.forEach((element) -> { - if (isPartitionFull(numberPerPartition, currentPartition)) { + if(isPartitionFull(numberPerPartition, currentPartition)) { // Add the partition to the list returned.add(currentPartition.unwrap((partition) -> partition)); @@ -337,9 +311,7 @@ public class FunctionalList implements Cloneable, IList { @Override public E randItem(Function rnd) { - if (rnd == null) { - throw new NullPointerException("Random source must not be null"); - } + if(rnd == null) throw new NullPointerException("Random source must not be null"); int randomIndex = rnd.apply(wrapped.size()); @@ -349,11 +321,9 @@ public class FunctionalList implements Cloneable, IList { @Override public F reduceAux(T initialValue, BiFunction stateAccumulator, Function resultTransformer) { - if (stateAccumulator == null) { + 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 currentState = new Identity<>(initialValue); @@ -369,9 +339,7 @@ public class FunctionalList implements Cloneable, IList { @Override public boolean removeIf(Predicate removePredicate) { - if (removePredicate == null) { - throw new NullPointerException("Predicate must be non-null"); - } + if(removePredicate == null) throw new NullPointerException("Predicate must be non-null"); return wrapped.removeIf(removePredicate); } @@ -391,10 +359,8 @@ public class FunctionalList implements Cloneable, IList { // Search our internal list int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); - if (foundIndex >= 0) { - // We found a matching element + if(foundIndex >= 0) // We found a matching element return wrapped.get(foundIndex); - } // We didn't find an element return null; @@ -425,22 +391,19 @@ public class FunctionalList implements Cloneable, IList { public String toString() { int lSize = getSize(); - if (lSize == 0) - return "()"; + if(lSize == 0) return "()"; StringBuilder sb = new StringBuilder("("); Iterator itr = toIterable().iterator(); E itm = itr.next(); int i = 0; - if (lSize == 1) { - return "(" + itm + ")"; - } + if(lSize == 1) return "(" + itm + ")"; - for (E item : toIterable()) { + for(E item : toIterable()) { sb.append(item.toString()); - if (i < lSize - 1) { + if(i < lSize - 1) { sb.append(", "); } 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 3d3fed1..10a727c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java @@ -1,16 +1,16 @@ 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} - * + * * @author ben * * @param @@ -30,7 +30,7 @@ public class FunctionalMap implements IMap implements IMap... entries) { this(); - for (IPair entry : entries) { + for(IPair entry : entries) { entry.doWith((key, val) -> { wrappedMap.put(key, val); }); @@ -47,14 +47,12 @@ public class FunctionalMap implements IMap wrap) { - if (wrap == null) { - throw new NullPointerException("Map to wrap must not be null"); - } + if(wrap == null) throw new NullPointerException("Map to wrap must not be null"); wrappedMap = wrap; } @@ -91,13 +89,10 @@ public class FunctionalMap implements IMap implements IMap IMap mapValues(Function transformer) { - if (transformer == null) { - throw new NullPointerException("Transformer must not be null"); - } + 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"); - } + if(key == null) throw new NullPointerException("Key must not be null"); return wrappedMap.put(key, val); } 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 93f2dca..b7e3f30 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -6,22 +6,20 @@ import java.util.function.Function; /** * A string tokenizer that exposes a functional interface - * + * * @author ben * */ public class FunctionalStringTokenizer { /** * Create a new tokenizer from the specified string. - * + * * @param strang * 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"); - } + if(strang == null) throw new NullPointerException("String to tokenize must be non-null"); return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); } @@ -33,14 +31,12 @@ public class FunctionalStringTokenizer { /** * Create a functional string tokenizer from a given string - * + * * @param inp * The string to tokenize */ public FunctionalStringTokenizer(String inp) { - if (inp == null) { - throw new NullPointerException("String to tokenize must be non-null"); - } + if(inp == null) throw new NullPointerException("String to tokenize must be non-null"); this.input = new StringTokenizer(inp); } @@ -48,55 +44,49 @@ public class FunctionalStringTokenizer { /** * Create a functional string tokenizer from a given string and set of * separators - * + * * @param input * The string to tokenize * @param seperators * The set of separating tokens to use for splitting */ public FunctionalStringTokenizer(String input, String seperators) { - if (input == null) { + 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); } /** * Create a functional string tokenizer from a non-functional one - * + * * @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"); - } + if(toWrap == null) throw new NullPointerException("Wrapped tokenizer must not be null"); this.input = toWrap; } /** * Execute a provided action for each of the remaining tokens - * + * * @param action * The action to execute for each token */ public void forEachToken(Consumer action) { - if (action == null) { - throw new NullPointerException("Action must not be null"); - } + if(action == null) throw new NullPointerException("Action must not be null"); - while (input.hasMoreTokens()) { + while(input.hasMoreTokens()) { action.accept(input.nextToken()); } } /** * Get the string tokenizer encapsulated by this tokenizer - * + * * @return The encapsulated tokenizer */ public StringTokenizer getInternal() { @@ -105,7 +95,7 @@ public class FunctionalStringTokenizer { /** * Check if this tokenizer has more tokens - * + * * @return Whether or not this tokenizer has more tokens */ public boolean hasMoreTokens() { @@ -116,14 +106,12 @@ public class FunctionalStringTokenizer { * Return the next token from the tokenizer. * * Returns null if no more tokens are available - * + * * @return The next token from the tokenizer */ public String nextToken() { - if (input.hasMoreTokens()) { - // Return the next available token + if(input.hasMoreTokens()) // Return the next available token return input.nextToken(); - } // Return no token return null; @@ -131,7 +119,7 @@ public class FunctionalStringTokenizer { /** * Convert this tokenizer into a list of strings - * + * * @return This tokenizer, converted into a list of strings */ public IList toList() { @@ -141,18 +129,16 @@ public class FunctionalStringTokenizer { /** * Convert the contents of this tokenizer into a list. Consumes all of * the input from this tokenizer. - * + * * @param * The type of the converted tokens - * + * * @param transformer * The function to use to convert tokens. * @return A list containing all of the converted tokens. */ public IList toList(Function transformer) { - if (transformer == null) { - throw new NullPointerException("Transformer must not be null"); - } + if(transformer == null) throw new NullPointerException("Transformer must not be null"); IList returned = new FunctionalList<>(); 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 0feaf06..95f4813 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java @@ -1,5 +1,7 @@ package bjc.utils.funcdata; +import bjc.utils.data.IPair; + import java.util.Comparator; import java.util.Iterator; import java.util.function.BiConsumer; @@ -9,11 +11,9 @@ 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. - * + * * @author ben * * @param @@ -22,7 +22,7 @@ import bjc.utils.data.IPair; public interface IList extends Iterable { /** * Add an item to this list - * + * * @param item * The item to add to this list. * @return Whether the item was added to the list successfully. @@ -31,7 +31,7 @@ public interface IList extends Iterable { /** * Add all of the elements in the provided list to this list - * + * * @param items * The list of items to add * @return True if every item was successfully added to the list, false @@ -44,7 +44,7 @@ public interface IList extends Iterable { /** * Check if all of the elements of this list match the specified * predicate. - * + * * @param matcher * The predicate to use for checking. * @return Whether all of the elements of the list match the specified @@ -54,7 +54,7 @@ public interface IList extends Iterable { /** * Check if any of the elements in this list match the specified list. - * + * * @param matcher * The predicate to use for checking. * @return Whether any element in the list matches the provided @@ -64,7 +64,7 @@ public interface IList extends Iterable { /** * Reduce the contents of this list using a collector - * + * * @param * The intermediate accumulation type * @param @@ -90,15 +90,15 @@ public interface IList extends Iterable { * * Works sort of like a combined zip/map over resulting pairs. Does not * change the underlying list. - * + * * NOTE: The returned list will have the length of the shorter of this * list and the combined one. - * + * * @param * The type of the second list * @param * The type of the combined list - * + * * @param list * The list to combine with * @param combiner @@ -110,7 +110,7 @@ public interface IList extends Iterable { /** * Check if the list contains the specified item - * + * * @param item * The item to see if it is contained * @return Whether or not the specified item is in the list @@ -119,7 +119,7 @@ public interface IList extends Iterable { /** * Get the first element in the list - * + * * @return The first element in this list. */ ContainedType first(); @@ -129,10 +129,10 @@ public interface IList extends Iterable { * results. * * Does not change the underlying list. - * + * * @param * The type of the flattened list - * + * * @param expander * The function to apply to each member of the list. * @return A new list containing the flattened results of applying the @@ -142,15 +142,16 @@ public interface IList extends Iterable { /** * Apply a given action for each member of the list - * + * * @param action * The action to apply to each member of the list. */ + @Override void forEach(Consumer action); /** * Apply a given function to each element in the list and its index. - * + * * @param action * The function to apply to each element in the list and * its index. @@ -159,7 +160,7 @@ public interface IList extends Iterable { /** * Retrieve a value in the list by its index. - * + * * @param index * The index to retrieve a value from. * @return The value at the specified index in the list. @@ -168,7 +169,7 @@ public interface IList extends Iterable { /** * Retrieve a list containing all elements matching a predicate - * + * * @param predicate * The predicate to match by * @return A list containing all elements that match the predicate @@ -177,14 +178,14 @@ public interface IList extends Iterable { /** * Retrieve the size of the wrapped list - * + * * @return The size of the wrapped list */ int getSize(); /** * Check if this list is empty. - * + * * @return Whether or not this list is empty. */ boolean isEmpty(); @@ -194,10 +195,10 @@ public interface IList extends Iterable { * the list. * * Does not change the underlying list. - * + * * @param * The type of the transformed list - * + * * @param transformer * The function to apply to each element in the list * @return A new list containing the mapped elements of this list. @@ -206,10 +207,10 @@ public interface IList extends Iterable { /** * Zip two lists into a list of pairs - * + * * @param * The type of the second list - * + * * @param list * The list to use as the left side of the pair * @return A list containing pairs of this element and the specified @@ -219,7 +220,7 @@ public interface IList extends Iterable { /** * Partition this list into a list of sublists - * + * * @param partitionSize * The size of elements to put into each one of the * sublists @@ -229,7 +230,7 @@ public interface IList extends Iterable { /** * Prepend an item to the list - * + * * @param item * The item to prepend to the list */ @@ -238,7 +239,7 @@ public interface IList extends Iterable { /** * Select a random item from the list, using a default random number * generator - * + * * @return A random item from the list */ default ContainedType randItem() { @@ -248,7 +249,7 @@ public interface IList extends Iterable { /** * Select a random item from this list, using the provided random number * generator. - * + * * @param rnd * The random number generator to use. * @return A random element from this list. @@ -257,12 +258,12 @@ public interface IList extends Iterable { /** * Reduce this list to a single value, using a accumulative approach. - * + * * @param * The in-between type of the values * @param * The final value type - * + * * @param initial * The initial value of the accumulative state. * @param accumulator @@ -280,7 +281,7 @@ public interface IList extends Iterable { /** * Remove all elements that match a given predicate - * + * * @param predicate * The predicate to use to determine elements to delete * @return Whether there was anything that satisfied the predicate @@ -289,7 +290,7 @@ public interface IList extends Iterable { /** * Remove all parameters that match a given parameter - * + * * @param element * The object to remove all matching copies of */ @@ -306,7 +307,7 @@ public interface IList extends Iterable { * * Since this IS a binary search, the list must have been sorted before * hand. - * + * * @param key * The key to search for. * @param comparator @@ -321,7 +322,7 @@ public interface IList extends Iterable { * elements. * * Does change the underlying list. - * + * * @param comparator * The way to compare elements for sorting. Pass null to * use E's natural ordering @@ -330,14 +331,14 @@ public interface IList extends Iterable { /** * Get the tail of this list (the list without the first element - * + * * @return The list without the first element */ IList tail(); /** * Convert this list into an array - * + * * @param type * The type of array to return * @return The list, as an array @@ -346,7 +347,7 @@ public interface IList extends Iterable { /** * Convert the list into a Iterable - * + * * @return An iterable view onto the list */ Iterable toIterable(); 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 ff8f973..d83b5c2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java @@ -6,9 +6,9 @@ import java.util.function.Function; /** * Functional wrapper over map providing some useful things - * + * * @author ben - * + * * @param * The type of this map's keys * @param @@ -23,7 +23,7 @@ public interface IMap { /** * Check if this map contains the specified key - * + * * @param key * The key to check * @return Whether or not the map contains the key @@ -33,14 +33,14 @@ public interface IMap { /** * Extends this map, creating a new map that will delegate queries to * the map, but store any added values itself - * + * * @return An extended map */ IMap extend(); /** * Execute an action for each entry in the map - * + * * @param action * the action to execute for each entry in the map */ @@ -48,7 +48,7 @@ public interface IMap { /** * Perform an action for each key in the map - * + * * @param action * The action to perform on each key in the map */ @@ -56,7 +56,7 @@ public interface IMap { /** * Perform an action for each value in the map - * + * * @param action * The action to perform on each value in the map */ @@ -64,19 +64,19 @@ public interface IMap { /** * Get the value assigned to the given key - * + * * @param key * The key to look for a value under * @return The value of the key - * - * + * + * */ ValueType get(KeyType key); /** * Get a value from the map, and return a default value if the key * doesn't exist - * + * * @param key * The key to attempt to retrieve * @param defaultValue @@ -87,7 +87,7 @@ public interface IMap { default ValueType getOrDefault(KeyType key, ValueType defaultValue) { try { return get(key); - } catch (IllegalArgumentException iaex) { + } catch(IllegalArgumentException iaex) { // We don't care about this, because it indicates a key // is // missing @@ -97,25 +97,25 @@ public interface IMap { /** * Get the number of entries in this map - * + * * @return The number of entries in this map */ int getSize(); /** * Get a list of all the keys in this map - * + * * @return A list of all the keys in this map */ IList keyList(); /** * Transform the values returned by this map. - * + * * NOTE: This transform is applied once for each lookup of a value, so * the transform passed should be a proper function, or things will * likely not work as expected. - * + * * @param * The new type of returned values * @param transformer @@ -126,7 +126,7 @@ public interface IMap { /** * Add an entry to the map - * + * * @param key * The key to put the value under * @param val @@ -134,7 +134,7 @@ public interface IMap { * @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. - * + * * @throws UnsupportedOperationException * if the map implementation doesn't support modifying * the map @@ -143,7 +143,7 @@ public interface IMap { /** * Remove the value bound to the key - * + * * @param key * The key to remove from the map * @return The previous value for the key in the map, or null if the key @@ -155,7 +155,7 @@ public interface IMap { /** * Get a list of the values in this map - * + * * @return A list of values in this map */ IList valueList(); 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 32ec7cd..060f69e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java @@ -11,11 +11,13 @@ public class SentryList extends FunctionalList { super(backing); } + @Override public boolean add(T item) { boolean val = super.add(item); - if (val) + if(val) { System.out.println("Added item (" + item + ") to list"); + } return val; } 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 36bfaab..d4e1762 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java @@ -6,7 +6,7 @@ import java.util.function.Function; /** * A map that transforms values from one type to another - * + * * @author ben * * @param @@ -17,8 +17,8 @@ import java.util.function.Function; * The type of the transformed values */ final class TransformedValueMap implements IMap { - private IMap backing; - private Function transformer; + private IMap backing; + private Function transformer; public TransformedValueMap(IMap backingMap, Function transform) { backing = backingMap; 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 b3772a4..060b3f5 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,16 +1,16 @@ 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. - * + * * @author ben * * @param @@ -34,14 +34,12 @@ public class BinarySearchTree { /** * Create a new tree using the specified way to compare elements. - * + * * @param cmp * The thing to use for comparing elements */ public BinarySearchTree(Comparator cmp) { - if (cmp == null) { - throw new NullPointerException("Comparator must not be null"); - } + if(cmp == null) throw new NullPointerException("Comparator must not be null"); elementCount = 0; comparator = cmp; @@ -49,14 +47,14 @@ public class BinarySearchTree { /** * Add a node to the binary search tree. - * + * * @param element * The data to add to the binary search tree. */ public void addNode(T element) { elementCount++; - if (root == null) { + if(root == null) { root = new BinarySearchTreeNode<>(element, null, null); } else { root.add(element, comparator); @@ -65,7 +63,7 @@ public class BinarySearchTree { /** * Check if an adjusted pivot falls with the bounds of a list - * + * * @param elements * The list to get bounds from * @param pivot @@ -75,7 +73,7 @@ public class BinarySearchTree { * @return Whether the adjusted pivot is with the list */ private boolean adjustedPivotInBounds(IList elements, int pivot, int pivotAdjustment) { - return (pivot - pivotAdjustment) >= 0 && (pivot + pivotAdjustment) < elements.getSize(); + return pivot - pivotAdjustment >= 0 && pivot + pivotAdjustment < elements.getSize(); } /** @@ -97,8 +95,8 @@ public class BinarySearchTree { int pivotAdjustment = 0; // Add elements until there aren't any left - while (adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { - if (root == null) { + while(adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { + if(root == null) { // Create a new root element root = new BinarySearchTreeNode<>(elements.getByIndex(pivot), null, null); } else { @@ -114,9 +112,9 @@ public class BinarySearchTree { } // Add any trailing unbalanced elements - if ((pivot - pivotAdjustment) >= 0) { + if(pivot - pivotAdjustment >= 0) { root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); - } else if ((pivot + pivotAdjustment) < elements.getSize()) { + } else if(pivot + pivotAdjustment < elements.getSize()) { root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); } } @@ -126,7 +124,7 @@ public class BinarySearchTree { * * Soft-deleted nodes stay in the tree until trim()/balance() is * invoked, and are not included in traversals/finds. - * + * * @param element * The node to delete */ @@ -138,7 +136,7 @@ public class BinarySearchTree { /** * Get the root of the tree. - * + * * @return The root of the tree. */ public ITreePart getRoot() { @@ -147,7 +145,7 @@ public class BinarySearchTree { /** * Check if a node is in the tree - * + * * @param element * The node to check the presence of for the tree. * @return Whether or not the node is in the tree. @@ -158,18 +156,16 @@ public class BinarySearchTree { /** * Traverse the tree in a specified way until the function fails - * + * * @param linearizationMethod * The way to linearize the tree for traversal * @param traversalPredicate * The function to use until it fails */ public void traverse(TreeLinearizationMethod linearizationMethod, Predicate traversalPredicate) { - if (linearizationMethod == null) { + 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); } 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 04765b4..2696577 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 @@ -7,7 +7,7 @@ import java.util.function.Predicate; /** * A leaf in a tree. - * + * * @author ben * * @param @@ -26,7 +26,7 @@ public class BinarySearchTreeLeaf implements ITreePart { /** * Create a new leaf holding the specified data. - * + * * @param element * The data for the leaf to hold. */ @@ -41,9 +41,7 @@ public class BinarySearchTreeLeaf implements ITreePart { @Override public E collapse(Function leafTransformer, BiFunction branchCollapser) { - if (leafTransformer == null) { - throw new NullPointerException("Transformer must not be null"); - } + if(leafTransformer == null) throw new NullPointerException("Transformer must not be null"); return leafTransformer.apply(data); } @@ -60,18 +58,16 @@ public class BinarySearchTreeLeaf implements ITreePart { @Override public void delete(T element, Comparator comparator) { - if (data.equals(element)) { + if(data.equals(element)) { isDeleted = true; } } @Override public boolean directedWalk(DirectedWalkFunction treeWalker) { - if (treeWalker == null) { - throw new NullPointerException("Tree walker must not be null"); - } + if(treeWalker == null) throw new NullPointerException("Tree walker must not be null"); - switch (treeWalker.walk(data)) { + switch(treeWalker.walk(data)) { case SUCCESS: return true; // We don't have any children to care about @@ -85,9 +81,7 @@ public class BinarySearchTreeLeaf implements ITreePart { @Override public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate traversalPredicate) { - if (traversalPredicate == null) { - throw new NullPointerException("Predicate must not be null"); - } + if(traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); return traversalPredicate.test(data); } 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 46a89f2..4fe9de3 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,18 +1,18 @@ package bjc.utils.funcdata.bst; -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; +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; + /** * A binary node in a tree. - * + * * @author ben * * @param @@ -31,7 +31,7 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { /** * Create a new node with the specified data and children. - * + * * @param element * The data to store in this node. * @param lft @@ -47,27 +47,24 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public void add(T element, Comparator comparator) { - if (comparator == null) { - throw new NullPointerException("Comparator must not be null"); - } + if(comparator == null) throw new NullPointerException("Comparator must not be null"); - switch (comparator.compare(data, element)) { + switch(comparator.compare(data, element)) { case -1: - if (left == null) { + if(left == null) { left = new BinarySearchTreeNode<>(element, null, null); } else { left.add(element, comparator); } break; case 0: - if (isDeleted) { + if(isDeleted) { isDeleted = false; - } else { + } else throw new IllegalArgumentException("Can't add duplicate values"); - } break; case 1: - if (right == null) { + if(right == null) { right = new BinarySearchTreeNode<>(element, null, null); } else { right.add(element, comparator); @@ -80,16 +77,15 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public E collapse(Function nodeCollapser, BiFunction branchCollapser) { - if (nodeCollapser == null || branchCollapser == null) { + if(nodeCollapser == null || branchCollapser == null) throw new NullPointerException("Collapser must not be null"); - } E collapsedNode = nodeCollapser.apply(data); - if (left != null) { + if(left != null) { E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); - if (right != null) { + if(right != null) { E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, collapsedRightBranch); @@ -100,7 +96,7 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { return branchCollapser.apply(collapsedNode, collapsedLeftBranch); } - if (right != null) { + if(right != null) { E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); return branchCollapser.apply(collapsedNode, collapsedRightBranch); @@ -111,12 +107,10 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public boolean contains(T element, Comparator comparator) { - if (comparator == null) { - throw new NullPointerException("Comparator must not be null"); - } + if(comparator == null) throw new NullPointerException("Comparator must not be null"); return directedWalk(currentElement -> { - switch (comparator.compare(element, currentElement)) { + switch(comparator.compare(element, currentElement)) { case -1: return LEFT; case 0: @@ -131,12 +125,10 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public void delete(T element, Comparator comparator) { - if (comparator == null) { - throw new NullPointerException("Comparator must not be null"); - } + if(comparator == null) throw new NullPointerException("Comparator must not be null"); directedWalk(currentElement -> { - switch (comparator.compare(data, element)) { + switch(comparator.compare(data, element)) { case -1: return left == null ? FAILURE : LEFT; case 0: @@ -152,11 +144,9 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public boolean directedWalk(DirectedWalkFunction treeWalker) { - if (treeWalker == null) { - throw new NullPointerException("Walker must not be null"); - } + if(treeWalker == null) throw new NullPointerException("Walker must not be null"); - switch (treeWalker.walk(data)) { + switch(treeWalker.walk(data)) { case SUCCESS: return true; case LEFT: @@ -172,13 +162,11 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { @Override public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate traversalPredicate) { - if (linearizationMethod == null) { + 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) { + switch(linearizationMethod) { case PREORDER: return preorderTraverse(linearizationMethod, traversalPredicate); case INORDER: @@ -192,51 +180,33 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { } private boolean inorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { - return false; - } + 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 traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { - return false; - } + 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 traversalPredicate) { - if (!traverseElement(traversalPredicate)) { - return false; - } + 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; } @@ -244,7 +214,7 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { private boolean traverseElement(Predicate traversalPredicate) { boolean nodeSuccesfullyTraversed; - if (isDeleted) { + if(isDeleted) { nodeSuccesfullyTraversed = true; } else { nodeSuccesfullyTraversed = traversalPredicate.test(data); @@ -257,7 +227,7 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { Predicate traversalPredicate) { boolean leftSuccesfullyTraversed; - if (left == null) { + if(left == null) { leftSuccesfullyTraversed = true; } else { leftSuccesfullyTraversed = left.forEach(linearizationMethod, traversalPredicate); @@ -270,7 +240,7 @@ public class BinarySearchTreeNode extends BinarySearchTreeLeaf { Predicate traversalPredicate) { boolean rightSuccesfullyTraversed; - if (right == null) { + if(right == null) { rightSuccesfullyTraversed = true; } else { rightSuccesfullyTraversed = right.forEach(linearizationMethod, traversalPredicate); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java index e68bef6..e11524a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java @@ -2,7 +2,7 @@ package bjc.utils.funcdata.bst; /** * Represents a function for doing a directed walk of a binary tree. - * + * * @author ben * * @param @@ -12,7 +12,7 @@ package bjc.utils.funcdata.bst; public interface DirectedWalkFunction { /** * Represents the results used to direct a walk in a binary tree. - * + * * @author ben * */ @@ -33,14 +33,14 @@ public interface DirectedWalkFunction { RIGHT, /** * Specifies that the function has succesfully completed - * + * */ SUCCESS } /** * Perform a directed walk on a node of a tree. - * + * * @param element * The data stored in the node currently being visited * @return The way the function wants the walk to go next. diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java index c648001..3aa8880 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java @@ -7,7 +7,7 @@ import java.util.function.Predicate; /** * A interface for the fundamental things that want to be part of a tree. - * + * * @author ben * * @param @@ -16,7 +16,7 @@ import java.util.function.Predicate; public interface ITreePart { /** * Add a element below this tree part somewhere. - * + * * @param element * The element to add below this tree part * @param comparator @@ -28,10 +28,10 @@ public interface ITreePart { /** * Collapses this tree part into a single value. Does not change the * underlying tree. - * + * * @param * The type of the final collapsed value - * + * * @param nodeCollapser * The function to use to transform data into mapped * form. @@ -44,7 +44,7 @@ public interface ITreePart { /** * Check if this tre part or below it contains the specified data item - * + * * @param element * The data item to look for. * @param comparator @@ -56,14 +56,14 @@ public interface ITreePart { /** * Get the data associated with this tree part. - * + * * @return The data associated with this tree part. */ public T data(); /** * Remove the given node from this tree part and any of its children. - * + * * @param element * The data item to remove. * @param comparator @@ -73,7 +73,7 @@ public interface ITreePart { /** * Execute a directed walk through the tree. - * + * * @param walker * The function to use to direct the walk through the * tree. @@ -84,7 +84,7 @@ public interface ITreePart { /** * Execute a provided function for each element of tree it succesfully * completes for - * + * * @param linearizationMethod * The way to linearize the tree for executing * @param predicate diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java index f7d6280..0c83867 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java @@ -2,7 +2,7 @@ package bjc.utils.funcdata.bst; /** * Represents the ways to linearize a tree for traversal. - * + * * @author ben * */ 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 fa69f31..d6da637 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 @@ -4,7 +4,7 @@ import java.util.function.Function; /** * A functor over a pair of heterogenous types - * + * * @author ben * @param * The type stored on the 'left' of the pair @@ -16,7 +16,7 @@ public interface Bifunctor { /** * Lift a pair of functions to a single function that maps over both * parts of a pair - * + * * @param * The old left type of the pair * @param @@ -49,7 +49,7 @@ public interface Bifunctor { /** * Lift a function to operate over the left part of this pair - * + * * @param * The old left type of the pair * @param @@ -66,7 +66,7 @@ public interface Bifunctor { /** * Lift a function to operate over the right part of this pair - * + * * @param * The old left type of the pair * @param @@ -83,14 +83,14 @@ public interface Bifunctor { /** * Get the value contained on the left of this bifunctor - * + * * @return The value on the left side of this bifunctor */ public LeftType getLeft(); /** * Get the value contained on the right of this bifunctor - * + * * @return The value on the right of this bifunctor */ public RightType getRight(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java index a5007f1..1c53284 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java @@ -5,7 +5,7 @@ import java.util.function.Function; /** * Represents a container or context some sort usually, but the precise * definition is that it represents exactly what it is defined as - * + * * @author ben * @param * The value inside the functor @@ -13,11 +13,11 @@ import java.util.function.Function; public interface Functor { /** * Converts a normal function to operate over values in a functor. - * + * * N.B: Even though the type signature implies that you can apply the * resulting function to any type of functor, it is only safe to call it * on instances of the type of functor you called fmap on. - * + * * @param * The argument of the function * @param @@ -32,7 +32,7 @@ public interface Functor { /** * Retrieve the thing inside this functor - * + * * @return The thing inside this functor */ public ContainedType getValue(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/package-info.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/package-info.java index 33c80d6..713eb9f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/package-info.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/package-info.java @@ -1,6 +1,6 @@ /** * Random functional type things that don't belong elsewhere - * + * * @author ben * */ 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 1e5d7de..9a8cca3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -1,20 +1,20 @@ 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} - * + * * @author ben * */ public class CollectorUtils { /** * Create a collector that applies two collectors at once - * + * * @param * The type of the collection to collect from * @param 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 1f73d0a..7e7b003 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -1,5 +1,10 @@ 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; @@ -7,18 +12,13 @@ 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 implements Collector>, IPair> { private Set characteristicSet; - private Collector first; - private Collector second; + private Collector first; + private Collector second; public CompoundCollector(Collector first, Collector second) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java index 747b39f..8d0715d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java @@ -8,8 +8,8 @@ import java.util.regex.Pattern; * Uses a regex from the javadoc for Double.valueOf() */ class DoubleMatcher { - private static final String Digits = "(\\p{Digit}+)"; - private static final String HexDigits = "(\\p{XDigit}+)"; + private static final String Digits = "(\\p{Digit}+)"; + private static final String HexDigits = "(\\p{XDigit}+)"; /* * an exponent is 'e' or 'E' followed by an optionally signed decimal @@ -17,7 +17,7 @@ class DoubleMatcher { */ private static final String Exp = "[eE][+-]?" + Digits; - private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional + private static final String fpRegex = "[\\x00-\\x20]*" + // Optional // leading // "whitespace" "[+-]?(" + // Optional sign character @@ -64,7 +64,7 @@ class DoubleMatcher { */ "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + - ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*"); // Optional + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*"; // Optional // trailing // "whitespace" 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 82a29a2..cab444d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -1,21 +1,21 @@ package bjc.utils.funcutils; -import java.util.Random; -import java.util.function.Consumer; - import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; +import java.util.Random; +import java.util.function.Consumer; + /** * Utility methods on enums - * + * * @author ben * */ public class EnumUtils { /** * Do an action for a random number of enum values - * + * * @param * The type of the enum * @param clasz @@ -35,7 +35,7 @@ public class EnumUtils { int randomValueCount = enumValues.length - nValues; - for (int i = 0; i <= randomValueCount; i++) { + for(int i = 0; i <= randomValueCount; i++) { E rDir = valueList.randItem(rnd::nextInt); valueList.removeMatching(rDir); @@ -46,7 +46,7 @@ public class EnumUtils { /** * Get a random value from an enum - * + * * @param * The type of the enum * @param clasz 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 35a6b3d..4c9c525 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -8,15 +8,15 @@ import java.util.function.BiPredicate; /** * Utilities for doing things with files - * + * * @author ben * */ public class FileUtils { /** * Traverse a directory recursively. This is a depth-first traversal - * - * + * + * * @param root * The directory to start the traversal at * @param predicate @@ -28,7 +28,7 @@ public class FileUtils { * returning false stops it * @throws IOException * if the walk throws an exception - * + * * TODO If it becomes necessary, write another overload * for this with all the buttons and knobs from * walkFileTree 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 3eb086b..cb15d40 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -6,7 +6,7 @@ import java.util.function.Function; /** * Utility things for functions - * + * * @author ben * */ @@ -14,7 +14,7 @@ public class FuncUtils { /** * Convert a binary function into a unary function that returns a * function - * + * * @param * The initial type of the function * @param @@ -34,14 +34,14 @@ public class FuncUtils { /** * Do the specified action the specified number of times - * + * * @param nTimes * The number of times to do the action * @param cons * The action to perform */ public static void doTimes(int nTimes, Consumer cons) { - for (int i = 0; i < nTimes; i++) { + 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 f1240cf..c806d50 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -8,8 +8,8 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.function.BiPredicate; final class FunctionalFileVisitor extends SimpleFileVisitor { - private BiPredicate predicate; - private BiPredicate action; + private BiPredicate predicate; + private BiPredicate action; public FunctionalFileVisitor(BiPredicate predicate, BiPredicate action) { @@ -19,18 +19,14 @@ final class FunctionalFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - if (predicate.test(dir, attrs)) { - return FileVisitResult.CONTINUE; - } + 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; - } + 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 2330a40..f736dcb 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -1,14 +1,14 @@ package bjc.utils.funcutils; -import java.util.function.Consumer; -import java.util.function.Function; - import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; +import java.util.function.Consumer; +import java.util.function.Function; + /** * Implements a single group partitioning pass on a list - * + * * @author ben * * @param @@ -17,11 +17,11 @@ import bjc.utils.funcdata.IList; final class GroupPartIteration implements Consumer { private IList> returnedList; - public IList currentPartition; - private IList rejectedItems; + public IList currentPartition; + private IList rejectedItems; - private int numberInCurrentPartition; - private int numberPerPartition; + private int numberInCurrentPartition; + private int numberPerPartition; private Function elementCounter; @@ -40,7 +40,7 @@ final class GroupPartIteration implements Consumer { public void accept(E value) { boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition; - if (shouldStartPartition) { + if(shouldStartPartition) { returnedList.add(currentPartition); currentPartition = new FunctionalList<>(); @@ -48,9 +48,9 @@ final class GroupPartIteration implements Consumer { } else { int currentElementCount = elementCounter.apply(value); - boolean shouldReject = (numberInCurrentPartition + currentElementCount) >= numberPerPartition; + boolean shouldReject = numberInCurrentPartition + currentElementCount >= numberPerPartition; - if (shouldReject) { + if(shouldReject) { rejectedItems.add(value); } else { currentPartition.add(value); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java index 357ce70..a96a4d6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java @@ -2,7 +2,7 @@ package bjc.utils.funcutils; /** * Generic interface for objects that implement the builder pattern - * + * * @author ben * * @param @@ -11,7 +11,7 @@ package bjc.utils.funcutils; public interface IBuilder { /** * Build the object this builder is building - * + * * @return The built object * @throws IllegalStateException * if the data in the builder cannot be built into its @@ -21,7 +21,7 @@ public interface IBuilder { /** * Reset the state of this builder to its initial state - * + * * @throws UnsupportedOperationException * if the builder doesn't support resetting its state */ 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 4e4ce80..483b47d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -1,19 +1,19 @@ package bjc.utils.funcutils; +import bjc.utils.data.IPair; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; + import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.function.Function; import java.util.function.Supplier; -import bjc.utils.data.IPair; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.IList; - /** * Utilities for manipulating FunctionalLists that don't belong in the class * itself - * + * * @author ben * */ @@ -23,15 +23,13 @@ public class ListUtils { /** * Collapse a string of tokens into a single string without adding any * spaces - * + * * @param input * The list of tokens to collapse * @return The collapsed string of tokens */ public static String collapseTokens(IList input) { - if (input == null) { - throw new NullPointerException("Input must not be null"); - } + if(input == null) throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); } @@ -39,7 +37,7 @@ public class ListUtils { /** * Collapse a string of tokens into a single string, adding the desired * seperator after each token - * + * * @param input * The list of tokens to collapse * @param seperator @@ -47,24 +45,22 @@ public class ListUtils { * @return The collapsed string of tokens */ public static String collapseTokens(IList input, String seperator) { - if (input == null) { + 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 { + else { StringBuilder state = new StringBuilder(); int i = 1; - for (String itm : input.toIterable()) { + for(String itm : input.toIterable()) { state.append(itm); - if (i != input.getSize()) { + if(i != input.getSize()) { state.append(seperator); } @@ -77,24 +73,22 @@ public class ListUtils { /** * Split off affixes from tokens - * + * * @param input * The tokens to deaffix * @param operators * The affixes to remove * @return The tokens that have been deaffixed - * + * */ public static IList deAffixTokens(IList input, Deque> operators) { - if (input == null) { + if(input == null) throw new NullPointerException("Input must not be null"); - } else if (operators == null) { - throw new NullPointerException("Set of operators must not be null"); - } + else if(operators == null) throw new NullPointerException("Set of operators must not be null"); IList returned = input; - for (IPair op : operators) { + for(IPair op : operators) { returned = returned.flatMap(token -> { return op.merge(new TokenDeaffixer(token)); }); @@ -105,7 +99,7 @@ public class ListUtils { /** * Select a number of random items from the list without replacement - * + * * @param * The type of items to select * @param list @@ -127,7 +121,7 @@ public class ListUtils { Iterator itr = list.toIterable().iterator(); E element = null; - for (int index = 0; itr.hasNext(); element = itr.next()) { + for(int index = 0; itr.hasNext(); element = itr.next()) { int winningChance = number - selected.getSize(); // n - m @@ -135,7 +129,7 @@ public class ListUtils { // N - t // Probability of selecting the t+1'th element - if (NumberUtils.isProbable(winningChance, totalChance, rng)) { + if(NumberUtils.isProbable(winningChance, totalChance, rng)) { selected.add(element); } } @@ -145,7 +139,7 @@ public class ListUtils { /** * Select a number of random items from the list, with replacement - * + * * @param * The type of items to select * @param list @@ -161,7 +155,7 @@ public class ListUtils { public static IList drawWithReplacement(IList list, int number, Function rng) { IList 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)); } @@ -171,10 +165,10 @@ public class ListUtils { /** * Partition a list into a list of lists, where each element can count * for more than one element in a partition - * + * * @param * The type of elements in the list to partition - * + * * @param input * The list to partition * @param counter @@ -182,19 +176,18 @@ public class ListUtils { * for * @param partitionSize * The number of elements to put in each partition - * + * * @return A list partitioned according to the above rules */ public static IList> groupPartition(IList input, Function counter, int partitionSize) { - if (input == null) { + 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()) { + else if(partitionSize < 1 || partitionSize > input.getSize()) throw new IllegalArgumentException("" + partitionSize + " is not a valid" + " partition size. Must be between 1 and " + input.getSize()); - } /* * List that holds our results @@ -211,14 +204,13 @@ public class ListUtils { /* * 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 we're done + if(rejected.isEmpty()) // Nothing was rejected, so we're + // done return returned; - } } throw new IllegalArgumentException("Heuristic (more than " + MAX_NTRIESPART @@ -230,7 +222,7 @@ public class ListUtils { /** * Merge the contents of a bunch of lists together into a single list - * + * * @param * The type of value in this lists * @param lists @@ -241,8 +233,8 @@ public class ListUtils { public static IList mergeLists(IList... lists) { IList returned = new FunctionalList<>(); - for (IList list : lists) { - for (E itm : list.toIterable()) { + for(IList list : lists) { + for(E itm : list.toIterable()) { returned.add(itm); } } @@ -252,7 +244,7 @@ public class ListUtils { /** * Pad the provided list out to the desired size - * + * * @param * The type of elements in the list * @param list @@ -272,22 +264,22 @@ public class ListUtils { IList returned = new FunctionalList<>(); - for (E itm : list.toIterable()) { + for(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) { + while(needed > 0 && threshold <= MAX_NTRIESPART) { E val = padder.get(); int newCount = counter.apply(val); - if (newCount <= needed) { + if(newCount <= needed) { returned.add(val); threshold = 0; @@ -298,10 +290,9 @@ 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 "); - } } return returned; @@ -309,28 +300,26 @@ public class ListUtils { /** * Split tokens in a list of tokens into multiple tokens. - * + * * The intended use is for expression parsers so that you can enter * something like 1+1 instead of 1 + 1. - * + * * @param input * The tokens to split * @param operators * Pairs of operators to split on and regexes that match * those operators * @return A list of tokens split on all the operators - * + * */ public static IList splitTokens(IList input, Deque> operators) { - if (input == null) { + if(input == null) throw new NullPointerException("Input must not be null"); - } else if (operators == null) { - throw new NullPointerException("Set of operators must not be null"); - } + else if(operators == null) throw new NullPointerException("Set of operators must not be null"); IList returned = input; - for (IPair op : operators) { + for(IPair op : operators) { returned = returned.flatMap(token -> { return op.merge(new TokenSplitter(token)); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java index 09c3ef7..6007429 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java @@ -29,11 +29,11 @@ public class NeoTokenSplitter { */ private static String WITH_MULTI_DELIM = "((?<=%1$s+)(?!%1$s)|(? * The type in the deque * @param queue @@ -94,16 +92,23 @@ public class StringUtils { /* * This regex matches java-style string escapes */ - private static String escapeString = "\\\\([btnfr\"'\\\\]" // Match - // shortform - // escape - // sequences - // like - // \t or - // \" - + "|[0-3]?[0-7]{1,2}" // Match octal escape sequences - + "|u[0-9a-fA-F]{4})"; // Match unicode escape sequences - private static Pattern escapePatt = Pattern.compile(escapeString); + private static String escapeString = "\\\\([btnfr\"'\\\\]" // Match + // shortform + // escape + // sequences + // like + // \t + // or + // \" + + "|[0-3]?[0-7]{1,2}" // Match + // octal + // escape + // sequences + + "|u[0-9a-fA-F]{4})"; // Match + // unicode + // escape + // sequences + private static Pattern escapePatt = Pattern.compile(escapeString); /* * This regular expression matches java style double quoted strings @@ -139,7 +144,7 @@ public class StringUtils { Matcher mt = doubleQuotePatt.matcher(inp); - while (mt.find()) { + while(mt.find()) { mt.appendReplacement(work, ""); res.add(work.toString()); @@ -166,11 +171,11 @@ public class StringUtils { StringBuffer work = new StringBuffer(); Matcher escapeFinder = escapePatt.matcher(inp); - while (escapeFinder.find()) { + while(escapeFinder.find()) { String escapeSeq = escapeFinder.group(); String escapeRep = ""; - switch (escapeSeq) { + switch(escapeSeq) { case "\\b": escapeRep = "\b"; break; @@ -196,7 +201,7 @@ public class StringUtils { escapeRep = "\\"; break; default: - if (escapeSeq.startsWith("u")) { + if(escapeSeq.startsWith("u")) { escapeRep = handleUnicodeEscape(escapeSeq.substring(1)); } else { escapeRep = handleOctalEscape(escapeSeq); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java index 151b7e2..f550b65 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java @@ -1,10 +1,10 @@ package bjc.utils.funcutils; -import java.util.function.BiFunction; - import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; +import java.util.function.BiFunction; + final class TokenDeaffixer implements BiFunction> { private String token; @@ -14,38 +14,34 @@ final class TokenDeaffixer implements BiFunction> @Override public IList apply(String operatorName, String operatorRegex) { - if (operatorName == null) { + if(operatorName == null) throw new NullPointerException("Operator name must not be null"); - } else if (operatorRegex == null) { - throw new NullPointerException("Operator regex must not be null"); - } + else if(operatorRegex == null) throw new NullPointerException("Operator regex must not be null"); - if (StringUtils.containsOnly(token, operatorRegex)) { + if(StringUtils.containsOnly(token, operatorRegex)) return new FunctionalList<>(token); - } else if (token.startsWith(operatorName)) { - if (token.endsWith(operatorName)) { + else if(token.startsWith(operatorName)) { + if(token.endsWith(operatorName)) return new FunctionalList<>(operatorName, token.split(operatorRegex)[1], operatorName); - } return new FunctionalList<>(operatorName, token.split(operatorRegex)[1]); - } else if (token.endsWith(operatorName)) { + } else if(token.endsWith(operatorName)) return new FunctionalList<>(token.split(operatorRegex)[0], operatorName); - } else if (token.contains(operatorName)) { + else if(token.contains(operatorName)) { String[] tokenParts = token.split(operatorRegex); IList returned = new FunctionalList<>(); - for (int i = 0; i < tokenParts.length; i++) { + for(int i = 0; i < tokenParts.length; i++) { returned.add(tokenParts[i]); - if (i < tokenParts.length - 1) { + if(i < tokenParts.length - 1) { returned.add(operatorName); } } return returned; - } else { + } else return new FunctionalList<>(token); - } } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java index 4176088..84f5270 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java @@ -1,11 +1,11 @@ package bjc.utils.funcutils; -import java.util.Iterator; -import java.util.function.BiFunction; - import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; +import java.util.Iterator; +import java.util.function.BiFunction; + final class TokenSplitter implements BiFunction> { private String tokenToSplit; @@ -15,16 +15,13 @@ final class TokenSplitter implements BiFunction> { @Override public IList apply(String operatorName, String operatorRegex) { - if (operatorName == null) { + if(operatorName == null) throw new NullPointerException("Operator name must not be null"); - } else if (operatorRegex == null) { - throw new NullPointerException("Operator regex must not be null"); - } + else if(operatorRegex == null) throw new NullPointerException("Operator regex must not be null"); - if (tokenToSplit.contains(operatorName)) { - if (StringUtils.containsOnly(tokenToSplit, operatorRegex)) { + if(tokenToSplit.contains(operatorName)) { + if(StringUtils.containsOnly(tokenToSplit, operatorRegex)) return new FunctionalList<>(tokenToSplit); - } IList splitTokens = new FunctionalList<>(tokenToSplit.split(operatorRegex)); IList result = new FunctionalList<>(); @@ -34,10 +31,10 @@ final class TokenSplitter implements BiFunction> { String elm = itr.next(); - for (int i = 0; itr.hasNext(); elm = itr.next()) { + for(int i = 0; itr.hasNext(); elm = itr.next()) { result.add(elm); - if (i != tokenExpansionSize) { + if(i != tokenExpansionSize) { result.add(operatorName); } } 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 5d054cf..4153e7d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -5,7 +5,7 @@ import bjc.utils.funcdata.IList; /** * A weighted grammar where all the rules have a equal chance of occuring. - * + * * @author ben * * @param @@ -21,7 +21,7 @@ public class RandomGrammar extends WeightedGrammar { /** * Add cases to a specified rule. - * + * * @param rule * The name of the rule to add cases to. * @param cases @@ -29,14 +29,14 @@ public class RandomGrammar extends WeightedGrammar { */ @SafeVarargs public final void addCases(E rule, IList... cases) { - for (IList currentCase : cases) { + for(IList currentCase : cases) { super.addCase(rule, 1, currentCase); } } /** * Create a rule with the specified name and cases. - * + * * @param rule * The name of the rule to add. * @param cases @@ -46,23 +46,21 @@ public class RandomGrammar extends WeightedGrammar { public final void makeRule(E rule, IList... cases) { super.addRule(rule); - for (IList currentCase : cases) { + for(IList currentCase : cases) { super.addCase(rule, 1, currentCase); } } /** * Create a rule with the specified name and cases. - * + * * @param rule * The name of the rule to add. * @param cases * The cases to add for this rule. */ public void makeRule(E rule, IList> cases) { - if (cases == null) { - throw new NullPointerException("Cases must not be null"); - } + 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 c266c7c..6179850 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -1,11 +1,5 @@ package bjc.utils.gen; -import java.util.Random; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.function.Predicate; - import bjc.utils.data.IPair; import bjc.utils.data.Pair; import bjc.utils.funcdata.FunctionalList; @@ -13,9 +7,15 @@ 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. - * + * * @author ben * * @param @@ -70,16 +70,14 @@ public class WeightedGrammar { /** * Create a new weighted grammar that uses the specified source of * randomness. - * + * * @param source * The source of randomness to use */ public WeightedGrammar(Random source) { this(); - if (source == null) { - throw new NullPointerException("Source of randomness must be non-null"); - } + if(source == null) throw new NullPointerException("Source of randomness must be non-null"); rng = source; } @@ -90,18 +88,16 @@ public class WeightedGrammar { } public void addSpecialRule(E ruleName, Supplier> cse) { - if (ruleName == null) { + if(ruleName == null) throw new NullPointerException("Rule name must not be null"); - } else if (cse == null) { - throw new NullPointerException("Case must not be null"); - } + else if(cse == null) throw new NullPointerException("Case must not be null"); specialRules.put(ruleName, cse); } /** * Add a case to an already existing rule. - * + * * @param ruleName * The rule to add a case to. * @param probability @@ -110,18 +106,16 @@ public class WeightedGrammar { * The case being added. */ public void addCase(E ruleName, int probability, IList cse) { - if (ruleName == null) { + 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"); - } + else if(cse == null) throw new NullPointerException("Case body must not be null"); rules.get(ruleName).addProbability(probability, cse); } /** * Add a alias for an existing subgrammar - * + * * @param name * The name of the subgrammar to alias * @param alias @@ -129,17 +123,13 @@ public class WeightedGrammar { * @return Whether the alias was succesfully created */ public boolean addGrammarAlias(E name, E alias) { - if (name == null) { + 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"); - } + else if(alias == null) throw new NullPointerException("Subgrammar alias must not be null"); - if (subgrammars.containsKey(alias)) { - return false; - } + if(subgrammars.containsKey(alias)) return false; - if (subgrammars.containsKey(name)) { + if(subgrammars.containsKey(name)) { subgrammars.put(alias, subgrammars.get(name)); return true; } @@ -149,26 +139,24 @@ public class WeightedGrammar { /** * Add a new rule with no cases. - * + * * @param name * The name of the rule to add. * @return Whether or not the rule was succesfully added. */ public boolean addRule(E name) { - if (rng == null) { + if(rng == null) { rng = new Random(); } - if (name == null) { - throw new NullPointerException("Rule name must not be null"); - } + if(name == null) throw new NullPointerException("Rule name must not be null"); return addRule(name, new WeightedRandom<>(rng)); } /** * Add a new rule with a set of cases. - * + * * @param name * The name of the rule to add. * @param cases @@ -176,15 +164,11 @@ public class WeightedGrammar { * @return Whether or not the rule was succesfully added. */ public boolean addRule(E name, WeightedRandom> cases) { - if (name == null) { + if(name == null) throw new NullPointerException("Name must not be null"); - } else if (cases == null) { - throw new NullPointerException("Cases must not be null"); - } + else if(cases == null) throw new NullPointerException("Cases must not be null"); - if (rules.containsKey(name)) { - return false; - } + if(rules.containsKey(name)) return false; rules.put(name, cases); return true; @@ -192,7 +176,7 @@ public class WeightedGrammar { /** * Add a subgrammar. - * + * * @param name * The name of the subgrammar. * @param subgrammar @@ -200,15 +184,11 @@ public class WeightedGrammar { * @return Whether or not the subgrammar was succesfully added. */ public boolean addSubgrammar(E name, WeightedGrammar subgrammar) { - if (name == null) { + if(name == null) throw new NullPointerException("Subgrammar name must not be null"); - } else if (subgrammar == null) { - throw new NullPointerException("Subgrammar must not be null"); - } + else if(subgrammar == null) throw new NullPointerException("Subgrammar must not be null"); - if (subgrammars.containsKey(name)) { - return false; - } + if(subgrammars.containsKey(name)) return false; subgrammars.put(name, subgrammar); return true; @@ -216,28 +196,24 @@ public class WeightedGrammar { /** * Remove a rule with the specified name. - * + * * @param name * The name of the rule to remove. */ public void deleteRule(E name) { - if (name == null) { - throw new NullPointerException("Rule name must not be null"); - } + if(name == null) throw new NullPointerException("Rule name must not be null"); rules.remove(name); } /** * Remove a subgrammar with the specified name. - * + * * @param name * The name of the subgrammar to remove. */ public void deleteSubgrammar(E name) { - if (name == null) { - throw new NullPointerException("Rule name must not be null"); - } + if(name == null) throw new NullPointerException("Rule name must not be null"); subgrammars.remove(name); } @@ -246,21 +222,19 @@ public class WeightedGrammar { * Generate a set of debug sentences for the specified rule. * * Only generates sentances one layer deep. - * + * * @param ruleName * The rule to test. * @return A set of sentances generated by the specified rule. */ public IList> generateDebugValues(E ruleName) { - if (ruleName == null) { - throw new NullPointerException("Rule name must not be null"); - } + if(ruleName == null) throw new NullPointerException("Rule name must not be null"); IList> returnedList = new FunctionalList<>(); WeightedRandom> ruleGenerator = rules.get(ruleName); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) { returnedList.add(ruleGenerator.generateValue()); } @@ -269,10 +243,10 @@ public class WeightedGrammar { /** * Generate a generic sentance from a initial rule. - * + * * @param * The type of the transformed output - * + * * @param initRule * The initial rule to start with. * @param tokenTransformer @@ -284,51 +258,49 @@ public class WeightedGrammar { * rule. */ public IList generateGenericValues(E initRules, Function tokenTransformer, T spacer) { - if (initRules == null) { + if(initRules == null) throw new NullPointerException("Initial rule must not be null"); - } else if (tokenTransformer == 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"); - } + else if(spacer == null) throw new NullPointerException("Spacer must not be null"); IList returnedList = new FunctionalList<>(); IList genRules = new FunctionalList<>(initRules); - if (specialMarker != null) { - if (specialMarker.test(initRules)) { + if(specialMarker != null) { + if(specialMarker.test(initRules)) { genRules = specialAction.apply(initRules, this); } } - for (E initRule : genRules.toIterable()) { - if (specialRules.containsKey(initRule)) { - for (E rulePart : specialRules.get(initRule).get().toIterable()) { + for(E initRule : genRules.toIterable()) { + if(specialRules.containsKey(initRule)) { + for(E rulePart : specialRules.get(initRule).get().toIterable()) { Iterable generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (T generatedRulePart : generatedRuleParts) { + for(T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } } - } else if (subgrammars.containsKey(initRule)) { + } else if(subgrammars.containsKey(initRule)) { Iterable ruleParts = subgrammars.get(initRule) .generateGenericValues(initRule, tokenTransformer, spacer).toIterable(); - for (T rulePart : ruleParts) { + for(T rulePart : ruleParts) { returnedList.add(rulePart); returnedList.add(spacer); } - } else if (rules.containsKey(initRule)) { + } else if(rules.containsKey(initRule)) { Iterable ruleParts = rules.get(initRule).generateValue().toIterable(); - for (E rulePart : ruleParts) { + for(E rulePart : ruleParts) { Iterable generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (T generatedRulePart : generatedRuleParts) { + for(T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } @@ -336,9 +308,8 @@ public class WeightedGrammar { } else { T transformedToken = tokenTransformer.apply(initRule); - if (transformedToken == null) { + if(transformedToken == null) throw new NullPointerException("Transformer created null token"); - } returnedList.add(transformedToken); returnedList.add(spacer); @@ -350,7 +321,7 @@ public class WeightedGrammar { /** * Generate a random list of grammar elements from a given initial rule. - * + * * @param initRule * The initial rule to start with. * @param spacer @@ -366,7 +337,7 @@ public class WeightedGrammar { /** * Get the initial rule of this grammar - * + * * @return The initial rule of this grammar */ public String getInitialRule() { @@ -375,7 +346,7 @@ public class WeightedGrammar { /** * Returns the number of rules in this grammar - * + * * @return The number of rules in this grammar */ public int getRuleCount() { @@ -384,7 +355,7 @@ public class WeightedGrammar { /** * Returns a set containing all of the rules in this grammar - * + * * @return The set of all rule names in this grammar */ public IList getRuleNames() { @@ -398,22 +369,20 @@ public class WeightedGrammar { /** * Get the subgrammar with the specified name. - * + * * @param name * The name of the subgrammar to get. * @return The subgrammar with the specified name. */ public WeightedGrammar getSubgrammar(E name) { - if (name == null) { - throw new NullPointerException("Subgrammar name must not be null"); - } + if(name == null) throw new NullPointerException("Subgrammar name must not be null"); return subgrammars.get(name); } /** * Check if this grammar has an initial rule - * + * * @return Whether or not this grammar has an initial rule */ public boolean hasInitialRule() { @@ -426,7 +395,7 @@ public class WeightedGrammar { /** * Prefix a given rule with a token multiple times - * + * * @param ruleName * The name of the rule to prefix * @param prefixToken @@ -437,13 +406,12 @@ public class WeightedGrammar { * The number of times to prefix the token */ public void multiPrefixRule(E ruleName, E prefixToken, int additionalProbability, int numberOfTimes) { - if (ruleName == null) { + if(ruleName == null) throw new NullPointerException("Rule name must not be null"); - } else if (prefixToken == null) { + else if(prefixToken == null) throw new NullPointerException("Prefix token must not be null"); - } else if (numberOfTimes < 1) { + else if(numberOfTimes < 1) throw new IllegalArgumentException("Number of times to prefix must be positive."); - } WeightedRandom> rule = rules.get(ruleName); @@ -452,18 +420,18 @@ public class WeightedGrammar { rule.getValues().forEach((pair) -> { IList> newRule = new FunctionalList<>(); - for (int i = 1; i <= numberOfTimes; i++) { + for(int i = 1; i <= numberOfTimes; i++) { IList newCase = pair.merge((left, right) -> { IList returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for(E val : right.toIterable()) { returnVal.add(val); } return returnVal; }); - for (int j = 1; j <= i; j++) { + for(int j = 1; j <= i; j++) { newCase.prepend(prefixToken); } @@ -487,7 +455,7 @@ public class WeightedGrammar { /** * Create a series of alternatives for a rule by prefixing them with a * given token - * + * * @param additionalProbability * The amount to adjust the probability by * @param ruleName @@ -496,11 +464,9 @@ public class WeightedGrammar { * The token to prefix to the rule */ public void prefixRule(E ruleName, E prefixToken, int additionalProbability) { - if (ruleName == null) { + 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"); - } + else if(prefixToken == null) throw new NullPointerException("Prefix token must not be null"); WeightedRandom> rule = rules.get(ruleName); @@ -510,7 +476,7 @@ public class WeightedGrammar { IList newCase = pair.merge((left, right) -> { IList returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for(E val : right.toIterable()) { returnVal.add(val); } @@ -527,7 +493,7 @@ public class WeightedGrammar { /** * Set the initial rule of the graphic - * + * * @param initRule * The initial rule of this grammar */ @@ -537,7 +503,7 @@ public class WeightedGrammar { /** * Suffix a token to a rule - * + * * @param ruleName * The rule to suffix * @param suffixToken @@ -546,11 +512,9 @@ public class WeightedGrammar { * Additional probability of the prefixed rule */ public void suffixRule(E ruleName, E suffixToken, int additionalProbability) { - if (ruleName == null) { + 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"); - } + else if(suffixToken == null) throw new NullPointerException("Prefix token must not be null"); WeightedRandom> rule = rules.get(ruleName); @@ -560,7 +524,7 @@ public class WeightedGrammar { IList newCase = par.merge((left, right) -> { IList returnVal = new FunctionalList<>(); - for (E val : right.toIterable()) { + for(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 d5256ee..88f623e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -1,17 +1,17 @@ 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. - * + * * @author ben * * @param @@ -38,7 +38,7 @@ public class WeightedRandom { /** * Create a new weighted random generator with the specified source of * randomness - * + * * @param src * The source of randomness to use. */ @@ -46,16 +46,14 @@ public class WeightedRandom { 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; } /** * Add a probability for a specific result to be given. - * + * * @param chance * The chance to get this result. * @param result @@ -70,7 +68,7 @@ public class WeightedRandom { /** * Generate a weighted random value. - * + * * @return A random value selected in a weighted fashion. */ public E generateValue() { @@ -79,8 +77,8 @@ public class WeightedRandom { IHolder 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); @@ -95,7 +93,7 @@ public class WeightedRandom { /** * Return a list of values that can be generated by this generator - * + * * @return A list of all the values that can be generated */ public IList getResults() { @@ -105,7 +103,7 @@ public class WeightedRandom { /** * Return a list containing values that can be generated paired with the * probability of those values being generated - * + * * @return A list of pairs of values and value probabilities */ public IList> getValues() { 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 5640ab6..9d415b1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -1,11 +1,5 @@ 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; @@ -14,9 +8,15 @@ 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 - * + * * @author ben * * @param @@ -25,20 +25,18 @@ import bjc.utils.funcutils.FuncUtils; public class AdjacencyMap { /** * Create an adjacency map from a stream of text - * + * * @param stream * The stream of text to read in * @return An adjacency map defined by the text */ public static AdjacencyMap fromStream(InputStream stream) { - if (stream == null) { - throw new NullPointerException("Input source must not be null"); - } + if(stream == null) throw new NullPointerException("Input source must not be null"); // Create the adjacency map AdjacencyMap adjacency; - try (Scanner input = new Scanner(stream)) { + try(Scanner input = new Scanner(stream)) { input.useDelimiter("\n"); int vertexCount; @@ -48,7 +46,7 @@ public class AdjacencyMap { try { // First, read in number of vertices vertexCount = Integer.parseInt(possible); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { InputMismatchException imex = new InputMismatchException( "The first line must contain the number of vertices. " + possible + " is not a valid number"); @@ -58,9 +56,8 @@ public class AdjacencyMap { throw imex; } - if (vertexCount <= 0) { + if(vertexCount <= 0) throw new InputMismatchException("The number of vertices must be greater than 0"); - } IList vertices = new FunctionalList<>(); @@ -82,18 +79,17 @@ public class AdjacencyMap { String strang) { 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(String part : parts) { int weight; try { weight = Integer.parseInt(part); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { InputMismatchException imex = new InputMismatchException( "" + part + " is not a valid weight."); @@ -117,14 +113,12 @@ public class AdjacencyMap { /** * Create a new map from a set of vertices - * + * * @param vertices * The set of vertices to create a map from */ public AdjacencyMap(IList vertices) { - if (vertices == null) { - throw new NullPointerException("Vertices must not be null"); - } + if(vertices == null) throw new NullPointerException("Vertices must not be null"); vertices.forEach(vertex -> { IMap row = new FunctionalMap<>(); @@ -139,7 +133,7 @@ public class AdjacencyMap { /** * Check if the graph is directed - * + * * @return Whether or not the graph is directed */ public boolean isDirected() { @@ -149,7 +143,7 @@ public class AdjacencyMap { sourceValue.forEach((targetKey, targetValue) -> { int inverseValue = adjacency.get(targetKey).get(sourceKey); - if (targetValue != inverseValue) { + if(targetValue != inverseValue) { result.replace(false); } }); @@ -160,7 +154,7 @@ public class AdjacencyMap { /** * Set the weight of an edge - * + * * @param source * The source node of the edge * @param target @@ -169,24 +163,21 @@ public class AdjacencyMap { * The weight of the edge */ public void setWeight(T source, T target, int weight) { - if (source == null) { + 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); } /** * Convert this to a different graph representation - * + * * @return The new representation of this graph */ public Graph toGraph() { @@ -203,14 +194,12 @@ public class AdjacencyMap { /** * Convert an adjacency map back into a stream - * + * * @param sink * The stream to convert to */ public void toStream(OutputStream sink) { - if (sink == null) { - throw new NullPointerException("Output source must not be null"); - } + if(sink == null) throw new NullPointerException("Output source must not be null"); PrintStream outputPrinter = new PrintStream(sink); 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 c77c0ba..37aff29 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java @@ -2,7 +2,7 @@ package bjc.utils.graph; /** * An edge in a weighted graph - * + * * @author ben * * @param @@ -21,7 +21,7 @@ public class Edge { /** * Create a new edge with set parameters - * + * * @param initial * The initial node of the edge * @param terminal @@ -30,11 +30,9 @@ public class Edge { * The distance between initial and terminal edge */ public Edge(T initial, T terminal, int distance) { - if (initial == null) { + 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; @@ -43,30 +41,24 @@ public class Edge { @Override public boolean equals(Object obj) { - if (this == 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 { + else { Edge other = (Edge) obj; - if (distance != other.distance) { - return false; - } else if (source == null) { - if (other.source != null) { - return false; - } - } else if (!source.equals(other.source)) { + if(distance != other.distance) return false; - } else if (target == null) { - if (other.target != null) { - return false; - } - } else if (!target.equals(other.target)) { + 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; return true; } @@ -74,7 +66,7 @@ public class Edge { /** * Get the distance in this edge - * + * * @return The distance between the initial and terminal nodes of this * edge */ @@ -84,7 +76,7 @@ public class Edge { /** * Get the initial node of an edge - * + * * @return The initial node of this edge */ public T getSource() { @@ -93,7 +85,7 @@ public class Edge { /** * Get the target node of an edge - * + * * @return The target node of this edge */ public T getTarget() { @@ -107,8 +99,8 @@ public class Edge { int result = 1; result = prime * result + distance; - result = prime * result + ((source == null) ? 0 : source.hashCode()); - result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + (source == null ? 0 : source.hashCode()); + result = prime * result + (target == null ? 0 : target.hashCode()); return result; } 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 70fb555..694aa02 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java @@ -1,5 +1,11 @@ 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; @@ -10,15 +16,9 @@ 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 - * + * * @author ben * * @param @@ -27,10 +27,10 @@ import bjc.utils.funcdata.IMap; public class Graph { /** * Create a graph from a list of edges - * + * * @param * The type of data stored in the edges - * + * * @param edges * The list of edges to build from * @return A graph built from the provided edge-list @@ -59,7 +59,7 @@ public class Graph { /** * Add a edge to the graph - * + * * @param source * The source vertex for this edge * @param target @@ -72,14 +72,12 @@ public class Graph { */ public void addEdge(T source, T target, int distance, boolean directed) { // Can't add edges with a null source or target - if (source == null) { + if(source == null) throw new NullPointerException("The source vertex cannot be null"); - } else if (target == null) { - throw new NullPointerException("The target vertex cannot be null"); - } + else if(target == null) throw new NullPointerException("The target vertex cannot be null"); // Initialize adjacency list for vertices if necessary - if (!backing.containsKey(source)) { + if(!backing.containsKey(source)) { backing.put(source, new FunctionalMap()); } @@ -87,8 +85,8 @@ public class Graph { backing.get(source).put(target, distance); // Handle possible directed edges - if (!directed) { - if (!backing.containsKey(target)) { + if(!directed) { + if(!backing.containsKey(target)) { backing.put(target, new FunctionalMap()); } @@ -99,7 +97,7 @@ public class Graph { /** * Execute an action for all edges of a specific vertex matching * conditions - * + * * @param source * The vertex to test edges for * @param matcher @@ -108,14 +106,12 @@ public class Graph { * The action to execute for matching edges */ public void forAllEdgesMatchingAt(T source, BiPredicate matcher, BiConsumer action) { - if (matcher == null) { + if(matcher == null) throw new NullPointerException("Matcher must not be null"); - } else if (action == null) { - throw new NullPointerException("Action must not be null"); - } + else if(action == null) throw new NullPointerException("Action must not be null"); getEdges(source).forEach((target, weight) -> { - if (matcher.test(target, weight)) { + if(matcher.test(target, weight)) { action.accept(target, weight); } }); @@ -123,25 +119,24 @@ public class Graph { /** * Get all the edges that begin at a particular source vertex - * + * * @param source * The vertex to use as a source * @return All of the edges with the specified vertex as a source */ public IMap getEdges(T source) { // Can't find edges for a null source - if (source == null) { + if(source == null) throw new NullPointerException("The source cannot be null."); - } else if (!backing.containsKey(source)) { + else if(!backing.containsKey(source)) throw new IllegalArgumentException("Vertex " + source + " is not in graph"); - } return backing.get(source); } /** * Get the initial vertex of the graph - * + * * @return The initial vertex of the graph */ public T getInitial() { @@ -153,7 +148,7 @@ public class Graph { * * If the graph is non-connected, this will lead to unpredictable * results. - * + * * @return a list of edges that constitute the MST */ public List> getMinimumSpanningTree() { @@ -173,7 +168,7 @@ public class Graph { visited.add(source.getValue()); // Make sure we visit all the nodes - while (visited.size() != getVertexCount()) { + while(visited.size() != getVertexCount()) { // Grab all edges adjacent to the provided edge forAllEdgesMatchingAt(source.getValue(), (target, weight) -> { @@ -188,7 +183,7 @@ public class Graph { // Only consider edges where we haven't visited the // target of // the edge - while (visited.contains(minimum.getValue())) { + while(visited.contains(minimum.getValue())) { minimum.transform((edge) -> available.poll()); } @@ -207,7 +202,7 @@ public class Graph { /** * Get the count of the vertices in this graph - * + * * @return A count of the vertices in this graph */ public int getVertexCount() { @@ -216,7 +211,7 @@ public class Graph { /** * Get all of the vertices in this graph. - * + * * @return A unmodifiable set of all the vertices in the graph. */ public IList getVertices() { @@ -225,7 +220,7 @@ public class Graph { /** * Remove the edge starting at the source and ending at the target - * + * * @param source * The source vertex for the edge * @param target @@ -233,20 +228,16 @@ public class Graph { */ public void removeEdge(T source, T target) { // Can't remove things w/ null vertices - if (source == null) { + if(source == null) throw new NullPointerException("The source vertex cannot be null"); - } else if (target == null) { - throw new NullPointerException("The target vertex cannot be null"); - } + else if(target == null) throw new NullPointerException("The target vertex cannot be null"); // Can't remove if one vertice doesn't exists - if (!backing.containsKey(source)) { + if(!backing.containsKey(source)) throw new NoSuchElementException("vertex " + source + " does not exist."); - } - if (!backing.containsKey(target)) { + if(!backing.containsKey(target)) throw new NoSuchElementException("vertex " + target + " does not exist."); - } backing.get(source).remove(target); @@ -256,7 +247,7 @@ public class Graph { /** * Convert a graph into a adjacency map/matrix - * + * * @return A adjacency map representing this graph */ public AdjacencyMap toAdjacencyMap() { 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 6a5e676..8662f4e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -1,18 +1,18 @@ 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. - * + * * Built for Swing. - * + * * @author ben * */ @@ -24,7 +24,7 @@ public class ExtensionFileFilter extends FileFilter { /** * Create a new filter only showing files with the specified extensions. - * + * * @param exts * The extensions to show in this filter. */ @@ -34,7 +34,7 @@ public class ExtensionFileFilter extends FileFilter { /** * Create a new filter only showing files with the specified extensions. - * + * * @param exts * The extensions to show in this filter. */ @@ -44,9 +44,7 @@ public class ExtensionFileFilter extends FileFilter { @Override public boolean accept(File pathname) { - if (pathname == null) { - throw new NullPointerException("Pathname must not be null"); - } + 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 7e3cdfd..bb14327 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -1,5 +1,7 @@ package bjc.utils.gui; +import bjc.utils.gui.layout.VLayout; + import java.awt.Component; import java.awt.Frame; import java.util.function.Function; @@ -12,18 +14,16 @@ 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. - * + * * @author ben * */ public class SimpleDialogs { /** * Get a bounded integer from the user. - * + * * @param parent * The parent component for the dialogs. * @param title @@ -41,8 +41,8 @@ public class SimpleDialogs { try { int value = Integer.parseInt(strang); - return (value < upperBound) && (value > lowerBound); - } catch (NumberFormatException nfex) { + return value < upperBound && value > lowerBound; + } catch(NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -53,10 +53,10 @@ public class SimpleDialogs { /** * Asks the user to pick an option from a series of choices. - * + * * @param * The type of choices for the user to pick - * + * * @param parent * The parent frame for this dialog * @param title @@ -69,13 +69,11 @@ public class SimpleDialogs { */ @SuppressWarnings("unchecked") public static E getChoice(Frame parent, String title, String question, E... choices) { - if (parent == null) { + 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); chooser.setLayout(new VLayout(2)); @@ -110,7 +108,7 @@ public class SimpleDialogs { /** * Get a integer from the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -124,7 +122,7 @@ public class SimpleDialogs { try { Integer.parseInt(strang); return true; - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -135,7 +133,7 @@ public class SimpleDialogs { /** * Get a string from the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -145,23 +143,21 @@ public class SimpleDialogs { * @return A string. */ public static String getString(Component parent, String title, String prompt) { - if (parent == null) { + 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); } /** * Get a value parsable from a string from the user. - * + * * @param * The type of the value parsed from the string - * + * * @param parent * The parent component for dialogs. * @param title @@ -176,15 +172,13 @@ public class SimpleDialogs { */ public static E getValue(Component parent, String title, String prompt, Predicate validator, Function transformer) { - if (validator == null) { + 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); @@ -195,7 +189,7 @@ public class SimpleDialogs { /** * Get a whole number from the user. - * + * * @param parent * The parent component for dialogs. * @param title @@ -210,7 +204,7 @@ public class SimpleDialogs { /** * Ask the user a Yes/No question. - * + * * @param parent * The parent component for dialogs. * @param title @@ -220,22 +214,20 @@ public class SimpleDialogs { * @return True if the user said yes, false otherwise. */ public static boolean getYesNo(Component parent, String title, String question) { - if (parent == null) { + 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); - return (result == JOptionPane.YES_OPTION ? true : false); + return result == JOptionPane.YES_OPTION ? true : false; } /** * Show a error message to the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -244,20 +236,18 @@ public class SimpleDialogs { * The error to show the user. */ public static void showError(Component parent, String title, String message) { - if (parent == null) { + 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); } /** * Show an informative message to the user - * + * * @param parent * The parent for this dialog * @param title @@ -266,13 +256,11 @@ public class SimpleDialogs { * Show the message for this dialog */ public static void showMessage(Component parent, String title, String message) { - if (parent == null) { + 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 ec4b784..cd7c180 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -1,36 +1,34 @@ 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. - * + * * Built for Swing. - * + * * @author ben * */ public class SimpleFileChooser { private static File doOpenFile(Component parent, String title, JFileChooser files) { - if (title == null) { - throw new NullPointerException("Title must not be null"); - } + 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(FileNotChosenException fncx) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open"); } @@ -40,20 +38,18 @@ public class SimpleFileChooser { } private static File doSaveFile(Component parent, String title, JFileChooser files) { - if (title == null) { - throw new NullPointerException("Title must not be null"); - } + if(title == null) throw new NullPointerException("Title must not be null"); files.setDialogTitle(title); boolean success = false; - while (!success) { + while(!success) { try { maybeDoSaveFile(parent, files); return files.getSelectedFile(); - } catch (FileNotChosenException fncex) { + } catch(FileNotChosenException fncex) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to"); } @@ -65,7 +61,7 @@ public class SimpleFileChooser { /** * Prompt the user with a "Open File..." dialog. Keeps prompting them * until they pick a file. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -81,7 +77,7 @@ public class SimpleFileChooser { /** * Prompt the user with a "Open File..." dialog. Keeps prompting them * until they pick a file. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -100,7 +96,7 @@ public class SimpleFileChooser { /** * Prompt the user with a "Save File..." dialog. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -115,7 +111,7 @@ public class SimpleFileChooser { /** * Prompt the user with a "Save File..." dialog. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -133,36 +129,28 @@ public class SimpleFileChooser { } private static void maybeDoOpenFile(Component parent, JFileChooser files) throws FileNotChosenException { - if (parent == null) { + 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); - 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) { + 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); - if (result != JFileChooser.APPROVE_OPTION) { - throw new FileNotChosenException(); - } + if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); } /** * Prompt the user with a "Open File..." dialog. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -170,16 +158,14 @@ public class SimpleFileChooser { * @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"); - } + if(title == null) throw new NullPointerException("Title must not be null"); JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoOpenFile(parent, files); - } catch (FileNotChosenException fncex) { + } catch(FileNotChosenException fncex) { // We don't care about specifics } @@ -188,7 +174,7 @@ public class SimpleFileChooser { /** * Prompt the user with a "Save File..." dialog. - * + * * @param parent * The component to use as the parent for the dialog. * @param title @@ -196,16 +182,14 @@ public class SimpleFileChooser { * @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"); - } + if(title == null) throw new NullPointerException("Title must not be null"); JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoSaveFile(parent, files); - } catch (FileNotChosenException fncex) { + } catch(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 b5f0d6c..d7bb700 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java @@ -10,14 +10,14 @@ import javax.swing.JOptionPane; * Utility class for getting simple input from the user. * * Modified to work with JDesktopPanes - * + * * @author ben * */ public class SimpleInternalDialogs { /** * Get a bounded integer from the user. - * + * * @param parent * The parent component for the dialogs. * @param title @@ -35,8 +35,8 @@ public class SimpleInternalDialogs { try { int value = Integer.parseInt(strang); - return (value < upperBound) && (value > lowerBound); - } catch (NumberFormatException nfex) { + return value < upperBound && value > lowerBound; + } catch(NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -47,7 +47,7 @@ public class SimpleInternalDialogs { /** * Get a integer from the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -61,7 +61,7 @@ public class SimpleInternalDialogs { try { Integer.parseInt(strang); return true; - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -72,7 +72,7 @@ public class SimpleInternalDialogs { /** * Get a string from the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -82,23 +82,21 @@ public class SimpleInternalDialogs { * @return A string. */ public static String getString(Component parent, String title, String prompt) { - if (parent == null) { + 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); } /** * Get a value parsable from a string from the user. - * + * * @param * The type of the value parsed from the string - * + * * @param parent * The parent component for dialogs. * @param title @@ -113,15 +111,13 @@ public class SimpleInternalDialogs { */ public static E getValue(Component parent, String title, String prompt, Predicate validator, Function transformer) { - if (validator == null) { + 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); @@ -132,7 +128,7 @@ public class SimpleInternalDialogs { /** * Get a whole number from the user. - * + * * @param parent * The parent component for dialogs. * @param title @@ -147,7 +143,7 @@ public class SimpleInternalDialogs { /** * Ask the user a Yes/No question. - * + * * @param parent * The parent component for dialogs. * @param title @@ -157,22 +153,20 @@ public class SimpleInternalDialogs { * @return True if the user said yes, false otherwise. */ public static boolean getYesNo(Component parent, String title, String question) { - if (parent == null) { + 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); - return (result == JOptionPane.YES_OPTION ? true : false); + return result == JOptionPane.YES_OPTION ? true : false; } /** * Show a error message to the user - * + * * @param parent * The parent component for dialogs. * @param title @@ -181,20 +175,18 @@ public class SimpleInternalDialogs { * The error to show the user. */ public static void showError(Component parent, String title, String message) { - if (parent == null) { + 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); } /** * Show an informative message to the user - * + * * @param parent * The parent for this dialog * @param title @@ -203,13 +195,11 @@ public class SimpleInternalDialogs { * Show the message for this dialog */ public static void showMessage(Component parent, String title, String message) { - if (parent == null) { + 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 4fe23e1..9fdf18f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java @@ -4,7 +4,7 @@ import javax.swing.JInternalFrame; /** * A simple internal frame class - * + * * @author ben * */ @@ -20,7 +20,7 @@ public class SimpleInternalFrame extends JInternalFrame { /** * Create a new blank internal frame with a specific title - * + * * @param title * The title of the internal frame */ 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 0cac1c9..e469f2f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java @@ -6,43 +6,39 @@ import javax.swing.ListModel; /** * Utility class for making JLists and their models. - * + * * @author ben * */ public class SimpleJList { /** * Create a new JList from a given list. - * + * * @param * The type of data in the JList - * + * * @param source * The list to populate the JList with. * @return A JList populated with the elements from ls. */ public static JList buildFromList(Iterable source) { - if (source == null) { - throw new NullPointerException("Source must not be null"); - } + if(source == null) throw new NullPointerException("Source must not be null"); return new JList<>(buildModel(source)); } /** * Create a new list model from a given list. - * + * * @param * The type of data in the list model - * + * * @param source * The list to fill the list model from. * @return A list model populated with the elements from ls. */ public static ListModel buildModel(Iterable source) { - if (source == null) { - throw new NullPointerException("Source must not be null"); - } + if(source == null) throw new NullPointerException("Source must not be null"); DefaultListModel defaultModel = new DefaultListModel<>(); 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 75d89e7..723fad0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java @@ -5,7 +5,7 @@ import javax.swing.border.TitledBorder; /** * A simple border with a title attached to it. - * + * * @author ben * */ @@ -15,7 +15,7 @@ public class SimpleTitledBorder extends TitledBorder { /** * Create a new border with the specified title. - * + * * @param title * The title for the border. */ 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 2fab8be..c63abfd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java @@ -16,7 +16,7 @@ public class TextAreaOutputStream extends OutputStream { /** * Create a new output stream attached to a textarea - * + * * @param console * The textarea to write to */ @@ -28,7 +28,7 @@ public class TextAreaOutputStream extends OutputStream { public void write(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 0990f4f..68978e7 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,17 +1,17 @@ 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. - * + * * Built for AWT - * + * * @author ben * */ @@ -23,21 +23,19 @@ public class ExtensionFileFilter implements FilenameFilter { /** * Create a new filter only showing files with the specified extensions. - * + * * @param exts * The extensions to show in this filter. */ public ExtensionFileFilter(List exts) { - if (exts == null) { - throw new NullPointerException("Extensions must not be null"); - } + if(exts == null) throw new NullPointerException("Extensions must not be null"); extensions = new FunctionalList<>(exts); } /** * Create a new filter only showing files with the specified extensions. - * + * * @param exts * The extensions to show in this filter. */ 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 041a9a2..47f76b8 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,24 +1,24 @@ 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 - * + * * Built for AWT. - * + * * @author ben * */ public class SimpleFileDialog { /** * Prompt the user to pick a file to open - * + * * @param parent * The parent of the file picker * @param title @@ -31,7 +31,7 @@ public class SimpleFileDialog { /** * Prompt the user to pick a file to open - * + * * @param parent * The parent of the file picker * @param title @@ -41,22 +41,20 @@ public class SimpleFileDialog { * @return The file the user picked */ public static File getOpenFile(Frame parent, String title, String... extensions) { - if (parent == null) { + 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); - if (extensions != null) { + if(extensions != null) { 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); } @@ -66,7 +64,7 @@ public class SimpleFileDialog { /** * Prompt the user to pick a file to open - * + * * @param parent * The parent of the file picker * @param title @@ -76,15 +74,13 @@ public class SimpleFileDialog { * @return The file the user picked */ public static File[] getOpenFiles(Frame parent, String title, String... extensions) { - if (parent == null) { + 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); - if (extensions != null) { + if(extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } @@ -92,7 +88,7 @@ public class SimpleFileDialog { 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); } @@ -102,7 +98,7 @@ public class SimpleFileDialog { /** * Prompt the user to pick a file to save - * + * * @param parent * The parent of the file picker * @param title @@ -115,7 +111,7 @@ public class SimpleFileDialog { /** * Prompt the user to pick a file to save - * + * * @param parent * The parent of the file picker * @param title @@ -125,22 +121,20 @@ public class SimpleFileDialog { * @return The file the user picked */ public static File getSaveFile(Frame parent, String title, String... extensions) { - if (parent == null) { + 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); - if (extensions != null) { + if(extensions != null) { 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/AutosizeLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java index 07acd56..6f384f2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java @@ -5,7 +5,7 @@ import java.awt.GridLayout; /** * A layout that simply holds one component that it auto-resizes whenever it is * resized. - * + * * @author ben * */ 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 3380321..be2116a 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 @@ -5,7 +5,7 @@ import java.awt.GridLayout; /** * A layout manager that lays out its components horizontally, evenly sizing * them. - * + * * @author ben * */ @@ -15,7 +15,7 @@ public class HLayout extends GridLayout { /** * Create a new horizontal layout with the specified number of columns. - * + * * @param columns * The number of columns in this layout. */ 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 fdae31e..9c5a563 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 @@ -5,7 +5,7 @@ import java.awt.GridLayout; /** * A layout that lays out its components vertically, evenly sharing space among * them. - * + * * @author ben * */ @@ -15,7 +15,7 @@ public class VLayout extends GridLayout { /** * Create a new vertical layout with the specified number of rows. - * + * * @param rows * The number of rows. */ 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 f2d7f7b..6e6be02 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,5 +1,9 @@ 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; @@ -9,13 +13,9 @@ 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 - * + * * @author ben * */ @@ -24,7 +24,7 @@ public class DropdownListPanel extends JPanel { /** * Create a new dropdown list panel - * + * * @param * The type of items in the dropdown list * @param type 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 ae62a43..877f308 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,5 +1,7 @@ package bjc.utils.gui.panels; +import bjc.utils.gui.layout.HLayout; + import java.util.function.Consumer; import javax.swing.JFormattedTextField; @@ -7,11 +9,9 @@ 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 - * + * * @author ben * * @param @@ -24,7 +24,7 @@ public class FormattedInputPanel extends JPanel { /** * Create a new formatted input panel - * + * * @param label * The label for this panel * @param length @@ -55,7 +55,7 @@ public class FormattedInputPanel extends JPanel { /** * Reset the value in this panel to a specified value - * + * * @param value * The value to set the panel to */ 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 b6fc807..054eb38 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,29 +1,29 @@ 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} - * + * * @author ben * */ public class HolderOutputPanel extends JPanel { private static final long serialVersionUID = 166573313903782080L; - private Timer updater; - private JLabel value; - private int nDelay; - private IHolder val; + private Timer updater; + private JLabel value; + private int nDelay; + private IHolder val; /** * Create a new display panel, backed by a holder - * + * * @param lab * The label to attach to this field * @param valueHolder 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 29ede89..8f68571 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,5 +1,10 @@ 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; @@ -9,14 +14,9 @@ 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 - * + * * @author ben * * @param @@ -28,7 +28,7 @@ public class ListParameterPanel extends JPanel { /** * Create a new panel using the specified actions for doing things - * + * * @param add * The action that provides items * @param edit @@ -42,7 +42,7 @@ public class ListParameterPanel extends JPanel { /** * Create a new panel using the specified actions for doing things - * + * * @param add * The action that provides items * @param edit @@ -57,7 +57,7 @@ public class ListParameterPanel extends JPanel { JList list; - if (defaults != null) { + if(defaults != null) { list = SimpleJList.buildFromList(defaults.toIterable()); } else { list = new JList<>(new DefaultListModel<>()); @@ -69,15 +69,15 @@ public class ListParameterPanel extends 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,7 +85,7 @@ public class ListParameterPanel extends JPanel { JButton addParam = null; - if (add != null) { + if(add != null) { addParam = new JButton("Add..."); addParam.addActionListener((event) -> { DefaultListModel model = (DefaultListModel) list.getModel(); @@ -96,7 +96,7 @@ public class ListParameterPanel extends JPanel { JButton editParam = null; - if (edit != null) { + if(edit != null) { editParam = new JButton("Edit..."); editParam.addActionListener((event) -> { edit.accept(list.getSelectedValue()); @@ -105,7 +105,7 @@ public class ListParameterPanel extends JPanel { JButton removeParam = null; - if (remove != null) { + if(remove != null) { removeParam = new JButton("Remove..."); removeParam.addActionListener((event) -> { DefaultListModel model = (DefaultListModel) list.getModel(); @@ -114,15 +114,15 @@ public class ListParameterPanel extends JPanel { }); } - 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 b90e25c..d0881c5 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 @@ -8,7 +8,7 @@ import javax.swing.JTextField; /** * A simple component for text input - * + * * @author ben * */ @@ -22,7 +22,7 @@ public class SimpleInputPanel extends JPanel { /** * Create a new input panel - * + * * @param label * The label for the field * @param columns @@ -33,7 +33,7 @@ public class SimpleInputPanel extends JPanel { 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 11b209f..b4fcfe1 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,5 +1,8 @@ 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; @@ -12,12 +15,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 - * + * * @author ben * */ @@ -28,7 +28,7 @@ public class SimpleListPanel extends JPanel { Consumer onFailure, JTextField addItemField) { String potentialItem = addItemField.getText(); - if (verifier == null || verifier.test(potentialItem)) { + if(verifier == null || verifier.test(potentialItem)) { model.addElement(potentialItem); } else { onFailure.accept(potentialItem); @@ -39,7 +39,7 @@ public class SimpleListPanel extends JPanel { /** * Create a new list panel - * + * * @param type * The type of things in the list * @param model 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 e9e94d5..a573bea 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 @@ -9,7 +9,7 @@ import javax.swing.SpinnerModel; /** * A simple spinner control - * + * * @author ben * */ @@ -23,7 +23,7 @@ public class SimpleSpinnerPanel extends JPanel { /** * Create a new spinner panel - * + * * @param label * The label for the spinner * @param 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 53bff32..71eaf33 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,5 +1,7 @@ package bjc.utils.gui.panels; +import bjc.utils.gui.layout.HLayout; + import java.text.ParseException; import java.util.function.Consumer; @@ -8,12 +10,10 @@ 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 - * + * * @author ben * */ @@ -21,8 +21,8 @@ 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 int minValue; + private int maxValue; private int initValue; @@ -38,14 +38,13 @@ public class SliderInputPanel extends JPanel { try { 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 { + else return val; - } - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { ParseException pex = new ParseException("Value must be a valid integer", 0); pex.initCause(nfex); @@ -56,9 +55,7 @@ public class SliderInputPanel extends JPanel { @Override public String valueToString(Object value) throws ParseException { - if (value == null) { - return Integer.toString(initValue); - } + if(value == null) return Integer.toString(initValue); return Integer.toString((Integer) value); } @@ -66,7 +63,7 @@ public class SliderInputPanel extends JPanel { /** * Represents the settings for a slider - * + * * @author ben * */ @@ -74,11 +71,11 @@ public class SliderInputPanel extends JPanel { /** * The minimum value of the slider */ - public final int minValue; + public final int minValue; /** * The maximum value of the slider */ - public final int maxValue; + public final int maxValue; /** * The initial value of the slider @@ -88,7 +85,7 @@ public class SliderInputPanel extends JPanel { /** * Create a new slider settings, with the initial value in the * middle - * + * * @param min * The minimum value of the slider * @param max @@ -100,7 +97,7 @@ public class SliderInputPanel extends JPanel { /** * Create a new set of slider sttings - * + * * @param min * The minimum slider value * @param max @@ -116,13 +113,13 @@ public class SliderInputPanel extends JPanel { } } - private static final long serialVersionUID = 2956394160569961404L; - private JSlider slider; - private JFormattedTextField field; + private static final long serialVersionUID = 2956394160569961404L; + private JSlider slider; + private JFormattedTextField field; /** * Create a new slider input panel - * + * * @param lab * The label for the field * @param settings @@ -149,7 +146,7 @@ public class SliderInputPanel extends JPanel { slider.setPaintLabels(true); slider.addChangeListener((event) -> { - if (slider.getValueIsAdjusting()) { + if(slider.getValueIsAdjusting()) { // Do nothing } else { int val = slider.getValue(); @@ -165,7 +162,7 @@ public class SliderInputPanel extends JPanel { field.addPropertyChangeListener("value", (event) -> { Object value = field.getValue(); - if (value == null) { + if(value == null) { // Do nothing } else { slider.setValue((Integer) value); @@ -179,7 +176,7 @@ public class SliderInputPanel extends JPanel { /** * Reset the values in this panel to a specified value - * + * * @param value * The value to reset the fields to */ 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 a9efe9b..bb6ebac 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -2,7 +2,7 @@ package bjc.utils.parserutils; /** * Represents something that has a set precedence - * + * * @author ben * */ @@ -10,7 +10,7 @@ package bjc.utils.parserutils; public interface IPrecedent { /** * Create a new object with set precedence - * + * * @param precedence * The precedence of the object to handle * @return A new object with set precedence @@ -21,7 +21,7 @@ public interface IPrecedent { /** * Get the precedence of the attached object - * + * * @return The precedence of the attached object */ public int getPrecedence(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java index 2da4f7e..b26030c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java @@ -1,11 +1,5 @@ package bjc.utils.parserutils; -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; @@ -15,15 +9,21 @@ 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 - * + * * @author ben * * @param * The type of the state object to use - * + * */ public class RuleBasedConfigReader { // Function to execute when starting a rule @@ -45,7 +45,7 @@ public class RuleBasedConfigReader { /** * Create a new rule-based config reader - * + * * @param start * The action to fire when starting a rule * @param continueRule @@ -64,29 +64,26 @@ public class RuleBasedConfigReader { /** * Add a pragma to this reader - * + * * @param name * The name of the pragma to add * @param action * The function to execute when this pragma is read */ public void addPragma(String name, BiConsumer action) { - if (name == null) { + 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) { // 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); @@ -94,12 +91,12 @@ public class RuleBasedConfigReader { private boolean endRule(E state, boolean isRuleOpen) { // Ignore blank line without an open rule - if (isRuleOpen == false) { + if(isRuleOpen == false) // Do nothing return false; - } else { + else { // Nothing happens on rule end - if (end != null) { + if(end != null) { // Process the rule ending end.accept(state); } @@ -111,7 +108,7 @@ public class RuleBasedConfigReader { /** * Run a stream through this reader - * + * * @param input * The stream to get input * @param initialState @@ -119,15 +116,13 @@ public class RuleBasedConfigReader { * @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"); - } + if(input == null) throw new NullPointerException("Input stream must not be null"); // Application state: We're giving this back later 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 isRuleOpen = new Identity<>(false); @@ -135,13 +130,13 @@ public class RuleBasedConfigReader { // 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 { @@ -158,7 +153,7 @@ public class RuleBasedConfigReader { /** * Set the action to execute when continuing a rule - * + * * @param continueRule * The action to execute on continuation of a rule */ @@ -168,7 +163,7 @@ public class RuleBasedConfigReader { /** * Set the action to execute when ending a rule - * + * * @param end * The action to execute on ending of a rule */ @@ -178,14 +173,12 @@ public class RuleBasedConfigReader { /** * Set the action to execute when starting a rule - * + * * @param start * The action to execute on starting of a rule */ public void setStartRule(BiConsumer> start) { - if (start == null) { - throw new NullPointerException("Action on rule start must be non-null"); - } + if(start == null) throw new NullPointerException("Action on rule start must be non-null"); this.start = start; } @@ -198,7 +191,7 @@ public class RuleBasedConfigReader { String nextToken = tokenizer.nextToken(); // Handle pragmas - if (nextToken.equals("pragma")) { + if(nextToken.equals("pragma")) { // Get the pragma name String token = tokenizer.nextToken(); @@ -208,9 +201,8 @@ public class RuleBasedConfigReader { }).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 start.accept(tokenizer, new Pair<>(nextToken, state)); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java index 6c660c6..65add27 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java @@ -1,14 +1,14 @@ package bjc.utils.parserutils; -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 - * + * * @author ben * */ @@ -16,7 +16,7 @@ public class RuleBasedReaderPragmas { /** * Creates a pragma that takes a single integer argument - * + * * @param * The type of state that goes along with this pragma * @param name @@ -29,9 +29,8 @@ public class RuleBasedReaderPragmas { BiConsumer 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(); @@ -39,7 +38,7 @@ public class RuleBasedReaderPragmas { try { // Run the pragma consumer.accept(Integer.parseInt(token), state); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // Tell the user their argument isn't correct PragmaFormatException pfex = new PragmaFormatException( "Argument " + token + " to " + name + " pragma isn't a valid integer. " @@ -55,7 +54,7 @@ public class RuleBasedReaderPragmas { /** * Creates a pragma that takes any number of arguments and collapses * them all into a single string - * + * * @param * The type of state that goes along with this pragma * @param name @@ -68,10 +67,8 @@ public class RuleBasedReaderPragmas { BiConsumer consumer) { return (tokenizer, state) -> { // Check our input - if (!tokenizer.hasMoreTokens()) { - throw new PragmaFormatException( - "Pragma " + name + " requires one or more string arguments"); - } + if(!tokenizer.hasMoreTokens()) throw new PragmaFormatException( + "Pragma " + name + " requires one or more string arguments"); // Build our argument String collapsed = ListUtils.collapseTokens(tokenizer.toList()); 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 19c1971..2a0bdff 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -1,19 +1,19 @@ 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 - * + * * @author ben * * @param @@ -22,7 +22,7 @@ import bjc.utils.funcutils.StringUtils; public class ShuntingYard { /** * A enum representing the fundamental operator types - * + * * @author ben * */ @@ -58,9 +58,9 @@ public class ShuntingYard { } private final class TokenShunter implements Consumer { - private IList output; - private Deque stack; - private Function transformer; + private IList output; + private Deque stack; + private Function transformer; public TokenShunter(IList outpt, Deque stack, Function transformer) { @@ -72,26 +72,26 @@ public class ShuntingYard { @Override public void accept(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(')', '('); // Remove tokens up to a matching parenthesis - while (!stack.peek().equals(swappedToken)) { + while(!stack.peek().equals(swappedToken)) { output.add(transformer.apply(stack.pop())); } @@ -111,7 +111,7 @@ public class ShuntingYard { /** * Create a new shunting yard with a default set of operators - * + * * @param configureBasics * Whether or not basic math operators should be provided */ @@ -119,7 +119,7 @@ public class ShuntingYard { 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); @@ -129,7 +129,7 @@ public class ShuntingYard { /** * Add an operator to the list of shuntable operators - * + * * @param operatorToken * The token representing the operator * @param precedence @@ -144,7 +144,7 @@ public class ShuntingYard { /** * Add an operator to the list of shuntable operators - * + * * @param operatorToken * The token representing the operator * @param precedence @@ -152,11 +152,9 @@ public class ShuntingYard { */ public void addOp(String operator, 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 operators.put(operator, precedence); @@ -167,9 +165,7 @@ public class ShuntingYard { 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(); @@ -181,7 +177,7 @@ public class ShuntingYard { /** * Transform a string of tokens from infix notation to postfix - * + * * @param input * The string to transform * @param transformer @@ -190,11 +186,9 @@ public class ShuntingYard { */ public IList postfix(IList input, Function 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 output = new FunctionalList<>(); @@ -215,14 +209,14 @@ public class ShuntingYard { /** * Remove an operator from the list of shuntable operators - * + * * @param token * The token representing the operator. If null, remove * all operators */ public void removeOp(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 1a4a6c4..5f843a2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java @@ -1,17 +1,17 @@ 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.IPair; import bjc.utils.data.ITree; import bjc.utils.data.Pair; import bjc.utils.data.Tree; +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 implements Consumer { // Handle operators private final class OperatorHandler implements UnaryOperator>, ITree>> { @@ -37,18 +37,15 @@ final class TokenTransformer implements Consumer { ITree 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) { - throw new IllegalStateException( - "Attempted to parse binary operator without enough operands.\n" - + "Problem operator is " + element - + "\nPossible operand is: \n\t" - + queuedASTs.peek()); - } + if(queuedASTs.size() < 2) throw new IllegalStateException( + "Attempted to parse binary operator without enough operands.\n" + + "Problem operator is " + element + + "\nPossible operand is: \n\t" + queuedASTs.peek()); // Grab the two operands ITree right = queuedASTs.pop(); @@ -70,8 +67,8 @@ final class TokenTransformer implements Consumer { private Predicate operatorPredicate; - private Predicate isSpecialOperator; - private Function>, ITree>> handleSpecialOperator; + private Predicate isSpecialOperator; + private Function>, ITree>> handleSpecialOperator; // Create a new transformer public TokenTransformer(IHolder>, ITree>> initialState, @@ -86,7 +83,7 @@ final class TokenTransformer implements Consumer { @Override public void accept(TokenType element) { // Handle operators - if (operatorPredicate.test(element)) { + if(operatorPredicate.test(element)) { initialState.transform(new OperatorHandler(element)); } else { ITree newAST = new Tree<>(element); 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 6f4e384..82ded42 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -1,10 +1,5 @@ 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; @@ -12,18 +7,23 @@ 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 - * + * * @author ben * */ public class TreeConstructor { /** * Construct a tree from a list of tokens in postfix notation - * + * * Only binary operators are accepted. - * + * * @param * The elements of the parse tree * @param tokens @@ -41,10 +41,10 @@ public class TreeConstructor { /** * Construct a tree from a list of tokens in postfix notation - * + * * Only binary operators are accepted by default. Use the last two * parameters to handle non-binary operators - * + * * @param * The elements of the parse tree * @param tokens @@ -58,7 +58,7 @@ public class TreeConstructor { * @param handleSpecialOperator * The function to use to handle special case operators * @return A AST from the expression - * + * * FIXME The handleSpecialOp function seems like an ugly * interface. Maybe there's a better way to express how that * works. @@ -67,13 +67,12 @@ public class TreeConstructor { Predicate isOperator, Predicate isSpecialOperator, Function>, ITree>> 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>, ITree>> initialState = new Identity<>( -- cgit v1.2.3