summaryrefslogtreecommitdiff
path: root/base
diff options
context:
space:
mode:
Diffstat (limited to 'base')
-rw-r--r--base/src/main/java/bjc/utils/cli/CLICommander.java44
-rw-r--r--base/src/main/java/bjc/utils/cli/CommandHandler.java6
-rw-r--r--base/src/main/java/bjc/utils/cli/CommandHelp.java4
-rw-r--r--base/src/main/java/bjc/utils/cli/CommandMode.java24
-rw-r--r--base/src/main/java/bjc/utils/cli/DelegatingCommand.java2
-rw-r--r--base/src/main/java/bjc/utils/cli/GenericCommand.java19
-rw-r--r--base/src/main/java/bjc/utils/cli/GenericCommandMode.java170
-rw-r--r--base/src/main/java/bjc/utils/cli/GenericHelp.java14
-rw-r--r--base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java53
-rw-r--r--base/src/main/java/bjc/utils/cli/objects/Command.java144
-rw-r--r--base/src/main/java/bjc/utils/cli/objects/DefineCLI.java72
-rw-r--r--base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java47
-rw-r--r--base/src/main/java/bjc/utils/components/ComponentDescription.java71
-rw-r--r--base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java81
-rw-r--r--base/src/main/java/bjc/utils/components/FileComponentRepository.java107
-rw-r--r--base/src/main/java/bjc/utils/components/IComponentRepository.java7
-rw-r--r--base/src/main/java/bjc/utils/components/IDescribedComponent.java6
-rw-r--r--base/src/main/java/bjc/utils/components/MemoryComponentRepository.java17
-rw-r--r--base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java2
-rw-r--r--base/src/main/java/bjc/utils/exceptions/InvalidDirectionException.java9
-rw-r--r--base/src/main/java/bjc/utils/exceptions/InvalidToken.java5
-rw-r--r--base/src/main/java/bjc/utils/exceptions/OperandsRemaining.java9
-rw-r--r--base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java2
-rw-r--r--base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java2
-rw-r--r--base/src/main/java/bjc/utils/funcutils/CollectorUtils.java22
-rw-r--r--base/src/main/java/bjc/utils/funcutils/CompoundCollector.java34
-rw-r--r--base/src/main/java/bjc/utils/funcutils/EnumUtils.java25
-rw-r--r--base/src/main/java/bjc/utils/funcutils/FileUtils.java23
-rw-r--r--base/src/main/java/bjc/utils/funcutils/FuncUtils.java56
-rw-r--r--base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java16
-rw-r--r--base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java29
-rw-r--r--base/src/main/java/bjc/utils/funcutils/IBuilder.java12
-rw-r--r--base/src/main/java/bjc/utils/funcutils/Isomorphism.java30
-rw-r--r--base/src/main/java/bjc/utils/funcutils/IteratorUtils.java52
-rw-r--r--base/src/main/java/bjc/utils/funcutils/LambdaLock.java10
-rw-r--r--base/src/main/java/bjc/utils/funcutils/ListUtils.java108
-rw-r--r--base/src/main/java/bjc/utils/funcutils/NumberUtils.java25
-rw-r--r--base/src/main/java/bjc/utils/funcutils/SetUtils.java21
-rw-r--r--base/src/main/java/bjc/utils/funcutils/StringUtils.java199
-rw-r--r--base/src/main/java/bjc/utils/funcutils/TestUtils.java32
-rw-r--r--base/src/main/java/bjc/utils/funcutils/TreeUtils.java21
-rw-r--r--base/src/main/java/bjc/utils/funcutils/TriConsumer.java12
-rw-r--r--base/src/main/java/bjc/utils/gen/RandomGrammar.java21
-rw-r--r--base/src/main/java/bjc/utils/gen/WeightedGrammar.java255
-rw-r--r--base/src/main/java/bjc/utils/gen/WeightedRandom.java104
-rw-r--r--base/src/main/java/bjc/utils/graph/AdjacencyMap.java61
-rw-r--r--base/src/main/java/bjc/utils/graph/Edge.java43
-rw-r--r--base/src/main/java/bjc/utils/graph/Graph.java82
-rw-r--r--base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java7
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleDialogs.java160
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleFileChooser.java111
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java135
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java2
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleJList.java14
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java54
-rw-r--r--base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java2
-rw-r--r--base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java4
-rw-r--r--base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java7
-rw-r--r--base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java70
-rw-r--r--base/src/main/java/bjc/utils/gui/layout/HLayout.java2
-rw-r--r--base/src/main/java/bjc/utils/gui/layout/VLayout.java2
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java15
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java18
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java13
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java49
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java6
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java21
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java4
-rw-r--r--base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java49
-rw-r--r--base/src/main/java/bjc/utils/ioutils/LevelSplitter.java52
-rw-r--r--base/src/main/java/bjc/utils/ioutils/LineReader.java3
-rw-r--r--base/src/main/java/bjc/utils/ioutils/MirrorDB.java10
-rw-r--r--base/src/main/java/bjc/utils/ioutils/Prompter.java6
-rw-r--r--base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java98
-rw-r--r--base/src/main/java/bjc/utils/ioutils/ReportWriter.java137
-rw-r--r--base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java86
-rw-r--r--base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java39
-rw-r--r--base/src/main/java/bjc/utils/ioutils/SimpleProperties.java65
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/Block.java28
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java4
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java19
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/BoundBlockReader.java21
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/FilteredBlockReader.java35
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java14
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java10
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java10
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java14
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java32
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java26
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java17
-rw-r--r--base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java4
-rw-r--r--base/src/main/java/bjc/utils/ioutils/properties/Property.java4
-rw-r--r--base/src/main/java/bjc/utils/ioutils/properties/PropertyDB.java2
-rw-r--r--base/src/main/java/bjc/utils/math/CardinalState.java25
-rw-r--r--base/src/main/java/bjc/utils/math/Dual.java25
-rw-r--r--base/src/main/java/bjc/utils/math/DualExpr.java24
-rw-r--r--base/src/main/java/bjc/utils/math/DualExprParser.java19
-rw-r--r--base/src/main/java/bjc/utils/math/NumberUtils.java209
-rw-r--r--base/src/main/java/bjc/utils/misc/Direction.java154
-rw-r--r--base/src/main/java/bjc/utils/misc/PropertyDB.java57
-rw-r--r--base/src/main/java/bjc/utils/misc/RelativeDirection.java54
-rw-r--r--base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java15
-rw-r--r--base/src/main/java/bjc/utils/parserutils/IPrecedent.java2
-rw-r--r--base/src/main/java/bjc/utils/parserutils/ParserException.java6
-rw-r--r--base/src/main/java/bjc/utils/parserutils/ShuntingYard.java43
-rw-r--r--base/src/main/java/bjc/utils/parserutils/StringDescaper.java70
-rw-r--r--base/src/main/java/bjc/utils/parserutils/TokenTransformer.java56
-rw-r--r--base/src/main/java/bjc/utils/parserutils/TokenUtils.java99
-rw-r--r--base/src/main/java/bjc/utils/parserutils/TreeConstructor.java64
-rw-r--r--base/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java10
-rw-r--r--base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java4
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java2
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java194
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java2
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java8
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java45
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java138
-rw-r--r--base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java8
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java8
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java51
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java17
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java10
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java9
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java2
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java19
-rw-r--r--base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java10
126 files changed, 2738 insertions, 2412 deletions
diff --git a/base/src/main/java/bjc/utils/cli/CLICommander.java b/base/src/main/java/bjc/utils/cli/CLICommander.java
index ad3bea9..f27454e 100644
--- a/base/src/main/java/bjc/utils/cli/CLICommander.java
+++ b/base/src/main/java/bjc/utils/cli/CLICommander.java
@@ -24,20 +24,22 @@ public class CLICommander {
* Create a new CLI interface powered by streams.
*
* @param input
- * The stream to get user input from.
+ * The stream to get user input from.
*
* @param output
- * The stream to send normal output to.
+ * The stream to send normal output to.
*
* @param error
- * The stream to send error output to.
+ * The stream to send error output to.
*/
- public CLICommander(final InputStream input, final OutputStream output, final OutputStream error) {
- if(input == null)
+ public CLICommander(final InputStream input, final OutputStream output,
+ final OutputStream error) {
+ if (input == null)
throw new NullPointerException("Input stream must not be null");
- else if(output == null)
+ 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;
@@ -53,9 +55,8 @@ public class CLICommander {
/*
* Set up input streams.
*
- * We're suppressing the warning about a potentially leaked
- * resource because we might use the input stream multiple
- * times.
+ * We're suppressing the warning about a potentially leaked resource because we
+ * might use the input stream multiple times.
*/
@SuppressWarnings("resource")
final Scanner inputSource = new Scanner(input);
@@ -63,24 +64,23 @@ public class CLICommander {
/*
* The mode currently being used to handle commands.
*
- * Used to preserve the initial mode, so that a mode can be
- * invoked more than once.
+ * Used to preserve the initial mode, so that a mode can be invoked more than
+ * once.
*/
CommandMode currentMode = initialMode;
/* The number of the command we are executing. */
int comno = 1;
/*
- * Process commands until we're told to stop, by the mode being
- * set to null.
+ * Process commands until we're told to stop, by the mode being set to null.
*/
- while(currentMode != null) {
+ while (currentMode != null) {
/*
* Print out the command prompt.
*
* Use a custom prompt if one is specified.
*/
- if(currentMode.isCustomPromptEnabled()) {
+ if (currentMode.isCustomPromptEnabled()) {
normalOutput.print(currentMode.getCustomPrompt());
} else {
normalOutput.printf("%s (%d)>> ", currentMode.getName(), comno);
@@ -92,21 +92,22 @@ public class CLICommander {
final String currentLine = inputSource.nextLine();
/* Handle commands we can handle in this mode. */
- if(currentMode.canHandle(currentLine)) {
+ if (currentMode.canHandle(currentLine)) {
final String[] commandTokens = currentLine.split(" ");
String[] commandArgs = null;
final int argCount = commandTokens.length;
/* Parse args if they are present. */
- if(argCount > 1) {
+ if (argCount > 1) {
commandArgs = Arrays.copyOfRange(commandTokens, 1, argCount);
}
/* Process command. */
currentMode = currentMode.process(commandTokens[0], commandArgs);
} else {
- errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n", currentLine, comno);
+ errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n",
+ currentLine, comno);
}
}
@@ -117,10 +118,11 @@ public class CLICommander {
* Set the initial command mode to use.
*
* @param initialMode
- * The initial command mode to use.
+ * The initial command mode to use.
*/
public void setInitialCommandMode(final CommandMode initialMode) {
- if(initialMode == null) throw new NullPointerException("Initial mode must be non-null");
+ if (initialMode == null)
+ throw new NullPointerException("Initial mode must be non-null");
this.initialMode = initialMode;
}
diff --git a/base/src/main/java/bjc/utils/cli/CommandHandler.java b/base/src/main/java/bjc/utils/cli/CommandHandler.java
index 6cc2d68..2e78f1b 100644
--- a/base/src/main/java/bjc/utils/cli/CommandHandler.java
+++ b/base/src/main/java/bjc/utils/cli/CommandHandler.java
@@ -13,10 +13,10 @@ public interface CommandHandler extends Function<String[], CommandMode> {
* Execute this command.
*
* @param args
- * The arguments for this command.
+ * The arguments for this command.
*
- * @return The command mode to switch to after this command, or null to
- * stop executing commands.
+ * @return The command mode to switch to after this command, or null to stop
+ * executing commands.
*/
default CommandMode handle(final String[] args) {
return this.apply(args);
diff --git a/base/src/main/java/bjc/utils/cli/CommandHelp.java b/base/src/main/java/bjc/utils/cli/CommandHelp.java
index 97d7dad..d07c9d5 100644
--- a/base/src/main/java/bjc/utils/cli/CommandHelp.java
+++ b/base/src/main/java/bjc/utils/cli/CommandHelp.java
@@ -17,11 +17,11 @@ public interface CommandHelp {
* Get the summary line for a command.
*
* A summary line should consist of a string of the following format
- *
+ *
* <pre>
* "&lt;command-name&rt;\t&lt;command-summary&rt;"
* </pre>
- *
+ *
* where anything in angle brackets should be filled in.
*
* @return The summary line line for a command
diff --git a/base/src/main/java/bjc/utils/cli/CommandMode.java b/base/src/main/java/bjc/utils/cli/CommandMode.java
index b33077b..c145c1c 100644
--- a/base/src/main/java/bjc/utils/cli/CommandMode.java
+++ b/base/src/main/java/bjc/utils/cli/CommandMode.java
@@ -11,10 +11,10 @@ public interface CommandMode extends Comparable<CommandMode> {
* Check to see if this mode can handle the specified command.
*
* @param command
- * The command to check.
+ * The command to check.
*
- * @return Whether or not this mode can handle the command. It is
- * assumed not by default.
+ * @return Whether or not this mode can handle the command. It is assumed not by
+ * default.
*/
default boolean canHandle(final String command) {
return false;
@@ -26,17 +26,19 @@ public interface CommandMode extends Comparable<CommandMode> {
* @return The custom prompt for this mode.
*
* @throws UnsupportedOperationException
- * If this mode doesn't support a custom prompt.
+ * If this mode doesn't support a custom
+ * prompt.
*/
default String getCustomPrompt() {
- throw new UnsupportedOperationException("This mode doesn't support a custom prompt");
+ throw new UnsupportedOperationException(
+ "This mode doesn't support a custom prompt");
}
/**
* Get the name of this command mode.
*
- * @return The name of this command mode, or a default string if one
- * isn't specified.
+ * @return The name of this command mode, or a default string if one isn't
+ * specified.
*/
public default String getName() {
return "(anonymous)";
@@ -55,13 +57,13 @@ public interface CommandMode extends Comparable<CommandMode> {
* Process a command in this mode..
*
* @param command
- * The command to process.
+ * The command to process.
*
* @param args
- * A list of arguments to the command.
+ * A list of arguments to the command.
*
- * @return The command mode to use for the next command. Defaults to
- * doing nothing, and staying in the current mode.
+ * @return The command mode to use for the next command. Defaults to doing
+ * nothing, and staying in the current mode.
*/
default CommandMode process(final String command, final String[] args) {
return this;
diff --git a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java
index ff981bd..f17b6b5 100644
--- a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java
+++ b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java
@@ -13,7 +13,7 @@ class DelegatingCommand implements Command {
* Create a new command that delegates to another command.
*
* @param delegate
- * The command to delegate to.
+ * The command to delegate to.
*/
public DelegatingCommand(final Command delegate) {
this.delegate = delegate;
diff --git a/base/src/main/java/bjc/utils/cli/GenericCommand.java b/base/src/main/java/bjc/utils/cli/GenericCommand.java
index bb624cd..a847bea 100644
--- a/base/src/main/java/bjc/utils/cli/GenericCommand.java
+++ b/base/src/main/java/bjc/utils/cli/GenericCommand.java
@@ -16,22 +16,25 @@ public class GenericCommand implements Command {
* Create a new generic command.
*
* @param handler
- * The handler to use for the command.
+ * The handler to use for the command.
*
* @param description
- * The description of the command. May be null, in which case a
- * default is provided.
+ * The description of the command. May be null, in which case
+ * a default is provided.
*
* @param help
- * The detailed help message for the command. May be null, in
- * which case the description is repeated for the detailed help.
+ * The detailed help message for the command. May be null, in
+ * which case the description is repeated for the detailed
+ * help.
*/
- public GenericCommand(final CommandHandler handler, final String description, final String help) {
- if(handler == null) throw new NullPointerException("Command handler must not be null");
+ public GenericCommand(final CommandHandler handler, final String description,
+ final String help) {
+ if (handler == null)
+ throw new NullPointerException("Command handler must not be null");
this.handler = handler;
- if(description == null) {
+ if (description == null) {
this.help = new NullHelp();
} else {
this.help = new GenericHelp(description, help);
diff --git a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java
index 79e716f..5058af6 100644
--- a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java
+++ b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java
@@ -42,15 +42,17 @@ public class GenericCommandMode implements CommandMode {
* Create a new generic command mode
*
* @param normalOutput
- * The function to use for normal output.
+ * The function to use for normal output.
*
* @param errorOutput
- * The function to use for error output.
+ * The function to use for error output.
*/
- public GenericCommandMode(final Consumer<String> normalOutput, final Consumer<String> errorOutput) {
- if(normalOutput == null)
+ public GenericCommandMode(final Consumer<String> normalOutput,
+ final Consumer<String> errorOutput) {
+ if (normalOutput == null)
throw new NullPointerException("Normal output source must be non-null");
- else if(errorOutput == null) throw new NullPointerException("Error output source must be non-null");
+ else if (errorOutput == null)
+ throw new NullPointerException("Error output source must be non-null");
this.normalOutput = normalOutput;
this.errorOutput = errorOutput;
@@ -68,33 +70,38 @@ public class GenericCommandMode implements CommandMode {
* Add an alias to an existing command.
*
* @param commandName
- * The name of the command to add an alias for.
+ * The name of the command to add an alias for.
*
* @param aliasName
- * The new alias for the command.
+ * 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.
+ * If the specified command doesn't have a
+ * bound handler, or if the alias name already
+ * has a bound value.
*/
public void addCommandAlias(final String commandName, final 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) {
String msg = "Alias name must not be null";
throw new NullPointerException(msg);
- } else if(!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) {
- String msg = String.format("Cannot alias non-existant command '%s'", commandName);
+ } else if (!commandHandlers.containsKey(commandName)
+ && !defaultHandlers.containsKey(commandName)) {
+ String msg = String.format("Cannot alias non-existant command '%s'",
+ commandName);
throw new IllegalArgumentException(msg);
- } else if(commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) {
- String msg = String.format("Cannot bind alias '%s' to an already bound command.", aliasName);
+ } else if (commandHandlers.containsKey(aliasName)
+ || defaultHandlers.containsKey(aliasName)) {
+ String msg = String.format(
+ "Cannot bind alias '%s' to an already bound command.", aliasName);
throw new IllegalArgumentException(msg);
} else {
/* The command that will be aliased. */
Command aliasedCommand;
/* Get the alias. */
- if(defaultHandlers.containsKey(commandName)) {
+ if (defaultHandlers.containsKey(commandName)) {
aliasedCommand = defaultHandlers.get(commandName).aliased();
} else {
aliasedCommand = commandHandlers.get(commandName).aliased();
@@ -108,20 +115,21 @@ public class GenericCommandMode implements CommandMode {
* Add a command to this command mode.
*
* @param command
- * The name of the command to add.
+ * The name of the command to add.
*
* @param handler
- * The handler to use for the specified command.
+ * The handler to use for the specified command.
*
* @throws IllegalArgumentException
- * If the specified command already has a handler registered.
+ * If the specified command already has a
+ * handler registered.
*/
public void addCommandHandler(final String command, final Command 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)) {
String msg = String.format("Command '%s' already has a registered handler");
throw new IllegalArgumentException(msg);
} else {
@@ -133,10 +141,10 @@ public class GenericCommandMode implements CommandMode {
* Add a help topic to this command mode that isn't tied to a command.
*
* @param topicName
- * The name of the topic.
+ * The name of the topic.
*
* @param topic
- * The contents of the topic.
+ * The contents of the topic.
*/
public void addHelpTopic(final String topicName, final CommandHelp topic) {
helpTopics.put(topicName, topic);
@@ -146,8 +154,8 @@ public class GenericCommandMode implements CommandMode {
/*
* @TODO 10/09/17 Ben Culkin :CommandExtraction
*
- * These command messages should be extracted into some kind of
- * file-based abstraction.
+ * These command messages should be extracted into some kind of file-based
+ * abstraction.
*/
private GenericCommand buildAliasCommand() {
final String aliasShortHelp = "alias\tAlias one command to another";
@@ -155,7 +163,7 @@ public class GenericCommandMode implements CommandMode {
+ " Invoke with two arguments: the name of the command to alias"
+ "followed by the name of the alias to give that command.";
- return new GenericCommand((args) -> {
+ return new GenericCommand(args -> {
doAliasCommands(args);
return this;
@@ -164,9 +172,10 @@ public class GenericCommandMode implements CommandMode {
private GenericCommand buildClearCommands() {
final String clearShortHelp = "clear\tClear the screen";
- final String clearLongHelp = "Clears the screen of all the text on it," + " and prints a new prompt.";
+ final String clearLongHelp = "Clears the screen of all the text on it,"
+ + " and prints a new prompt.";
- return new GenericCommand((args) -> {
+ return new GenericCommand(args -> {
errorOutput.accept("ERROR: This console doesn't support screen clearing");
return this;
@@ -178,7 +187,7 @@ public class GenericCommandMode implements CommandMode {
final String exitLongHelp = "First prompts the user to make sure they want to"
+ " exit, then quits if they say they do";
- return new GenericCommand((args) -> {
+ return new GenericCommand(args -> {
errorOutput.accept("ERROR: This console doesn't support auto-exiting");
return this;
@@ -190,10 +199,11 @@ public class GenericCommandMode implements CommandMode {
final String helpLongHelp = "Consults the internal help system."
+ " Invoked in two different ways. Invoking with no arguments"
+ " causes all the topics you can ask for details on to be list,"
- + " while invoking with the name of a topic will print the entry" + " for that topic";
+ + " 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) {
+ return new GenericCommand(args -> {
+ if (args == null || args.length == 0) {
/* Invoke general help */
doHelpSummary();
} else {
@@ -210,7 +220,7 @@ public class GenericCommandMode implements CommandMode {
final String listLongHelp = "Lists all of the commands available in this mode,"
+ " as well as commands available in any mode";
- return new GenericCommand((args) -> {
+ return new GenericCommand(args -> {
doListCommands();
return this;
@@ -219,12 +229,13 @@ public class GenericCommandMode implements CommandMode {
@Override
public boolean canHandle(final String command) {
- return commandHandlers.containsKey(command) || defaultHandlers.containsKey(command);
+ return commandHandlers.containsKey(command)
+ || defaultHandlers.containsKey(command);
}
/* Implement default commands */
private void doAliasCommands(final String[] args) {
- if(args.length != 2) {
+ if (args.length != 2) {
String msg = String.format(
"ERROR: Alias requires two arguments. The command name, and the alias for that command. ");
errorOutput.accept(msg);
@@ -232,12 +243,14 @@ public class GenericCommandMode implements CommandMode {
final String commandName = args[0];
final String aliasName = args[1];
- if(!canHandle(commandName)) {
- String msg = String.format("ERROR: '%s' is not a valid command.", commandName);
+ if (!canHandle(commandName)) {
+ String msg = String.format("ERROR: '%s' is not a valid command.",
+ commandName);
errorOutput.accept(msg);
- } else if(canHandle(aliasName)) {
- String msg = String.format("ERROR: Cannot overwrite command '%s'", aliasName);
+ } else if (canHandle(aliasName)) {
+ String msg = String.format("ERROR: Cannot overwrite command '%s'",
+ aliasName);
errorOutput.accept(msg);
} else {
@@ -247,15 +260,17 @@ public class GenericCommandMode implements CommandMode {
}
private void doHelpCommand(final String commandName) {
- if(commandHandlers.containsKey(commandName)) {
- final String desc = commandHandlers.get(commandName).getHelp().getDescription();
+ if (commandHandlers.containsKey(commandName)) {
+ final String desc
+ = commandHandlers.get(commandName).getHelp().getDescription();
normalOutput.accept("\n" + desc);
- } else if(defaultHandlers.containsKey(commandName)) {
- final String desc = defaultHandlers.get(commandName).getHelp().getDescription();
+ } else if (defaultHandlers.containsKey(commandName)) {
+ final String desc
+ = defaultHandlers.get(commandName).getHelp().getDescription();
normalOutput.accept("\n" + desc);
- } else if(helpTopics.containsKey(commandName)) {
+ } else if (helpTopics.containsKey(commandName)) {
normalOutput.accept("\n" + helpTopics.get(commandName).getDescription());
} else {
String msg = String.format("ERROR: No help available for '%s'", commandName);
@@ -267,9 +282,9 @@ public class GenericCommandMode implements CommandMode {
private void doHelpSummary() {
normalOutput.accept("Help topics for this command mode are as follows:\n");
- if(commandHandlers.size() > 0) {
+ if (commandHandlers.size() > 0) {
commandHandlers.forEachValue(command -> {
- if(!command.isAlias()) {
+ if (!command.isAlias()) {
String comLine = command.getHelp().getSummary();
String msg = String.format("\t%s\n", comLine);
@@ -280,14 +295,14 @@ public class GenericCommandMode implements CommandMode {
normalOutput.accept("\tNone available\n");
}
- normalOutput.accept("\nHelp topics available in all command modes are as follows\n");
- if(defaultHandlers.size() > 0) {
+ normalOutput
+ .accept("\nHelp topics available in all command modes are as follows\n");
+ if (defaultHandlers.size() > 0) {
/*
- * @NOTE This block here should be abstracted out into a
- * method.
+ * @NOTE This block here should be abstracted out into a method.
*/
defaultHandlers.forEachValue(command -> {
- if(!command.isAlias()) {
+ if (!command.isAlias()) {
String comLine = command.getHelp().getSummary();
String msg = String.format("\t%s\n", comLine);
@@ -298,8 +313,9 @@ public class GenericCommandMode implements CommandMode {
normalOutput.accept("\tNone available\n");
}
- normalOutput.accept("\nHelp topics not associated with a command are as follows\n");
- if(helpTopics.size() > 0) {
+ normalOutput
+ .accept("\nHelp topics not associated with a command are as follows\n");
+ if (helpTopics.size() > 0) {
helpTopics.forEachValue(topic -> {
String msg = String.format("\t%s\n", topic.getSummary());
@@ -331,14 +347,16 @@ public class GenericCommandMode implements CommandMode {
@Override
public String getCustomPrompt() {
- if(customPrompt != null) return customPrompt;
+ if (customPrompt != null)
+ return customPrompt;
return CommandMode.super.getCustomPrompt();
}
@Override
public String getName() {
- if(modeName != null) return modeName;
+ if (modeName != null)
+ return modeName;
return CommandMode.super.getName();
}
@@ -352,15 +370,16 @@ public class GenericCommandMode implements CommandMode {
public CommandMode process(final String command, final String[] args) {
normalOutput.accept("\n");
- if(defaultHandlers.containsKey(command))
+ if (defaultHandlers.containsKey(command))
return defaultHandlers.get(command).getHandler().handle(args);
- else if(commandHandlers.containsKey(command))
+ else if (commandHandlers.containsKey(command))
return commandHandlers.get(command).getHandler().handle(args);
else {
- if(args != null) {
+ if (args != null) {
String argString = String.join(", ", args);
- String msg = String.format("ERROR: Unrecognized command %s (arguments %s)", command,
- argString);
+ String msg
+ = String.format("ERROR: Unrecognized command %s (arguments %s)",
+ command, argString);
errorOutput.accept(msg);
} else {
@@ -369,7 +388,7 @@ public class GenericCommandMode implements CommandMode {
errorOutput.accept(msg);
}
- if(unknownCommandHandler == null) {
+ if (unknownCommandHandler == null) {
String msg = String.format("Command %s is invalid", command);
throw new UnsupportedOperationException(msg);
@@ -385,8 +404,8 @@ public class GenericCommandMode implements CommandMode {
* Set the custom prompt for this mode
*
* @param prompt
- * The custom prompt for this mode, or null to disable the custom
- * prompt
+ * The custom prompt for this mode, or null to disable the custom
+ * prompt
*/
public void setCustomPrompt(final String prompt) {
customPrompt = prompt;
@@ -396,7 +415,7 @@ public class GenericCommandMode implements CommandMode {
* Set the name of this mode
*
* @param name
- * The desired name of this mode, or null to use the default name
+ * The desired name of this mode, or null to use the default name
*/
public void setModeName(final String name) {
modeName = name;
@@ -406,11 +425,12 @@ public class GenericCommandMode implements CommandMode {
* Set the handler to use for unknown commands
*
* @param handler
- * The handler to use for unknown commands, or null to throw on
- * unknown commands
+ * The handler to use for unknown commands, or null to throw on
+ * unknown commands
*/
public void setUnknownCommandHandler(final BiConsumer<String, String[]> 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;
}
@@ -426,8 +446,8 @@ public class GenericCommandMode implements CommandMode {
/* Add commands handled in a upper layer. */
/*
- * @NOTE Figure out a place to put commands that apply across
- * all modes, but only to a specific application.
+ * @NOTE Figure out a place to put commands that apply across all modes, but
+ * only to a specific application.
*/
defaultHandlers.put("clear", buildClearCommands());
defaultHandlers.put("exit", buildExitCommand());
@@ -443,30 +463,30 @@ public class GenericCommandMode implements CommandMode {
final StringBuilder builder = new StringBuilder();
builder.append("GenericCommandMode [");
- if(commandHandlers != null) {
+ if (commandHandlers != null) {
builder.append("commandHandlers=");
builder.append(commandHandlers);
}
- if(defaultHandlers != null) {
+ if (defaultHandlers != null) {
builder.append(", ");
builder.append("defaultHandlers=");
builder.append(defaultHandlers);
}
- if(helpTopics != null) {
+ if (helpTopics != null) {
builder.append(", ");
builder.append("helpTopics=");
builder.append(helpTopics);
}
- if(modeName != null) {
+ if (modeName != null) {
builder.append(", ");
builder.append("modeName=");
builder.append(modeName);
}
- if(customPrompt != null) {
+ if (customPrompt != null) {
builder.append(", ");
builder.append("customPrompt=");
builder.append(customPrompt);
diff --git a/base/src/main/java/bjc/utils/cli/GenericHelp.java b/base/src/main/java/bjc/utils/cli/GenericHelp.java
index 2e74a6c..45d3a88 100644
--- a/base/src/main/java/bjc/utils/cli/GenericHelp.java
+++ b/base/src/main/java/bjc/utils/cli/GenericHelp.java
@@ -14,14 +14,14 @@ public class GenericHelp implements CommandHelp {
* Create a new help topic.
*
* @param summary
- * The summary of this help topic.
+ * The summary of this help topic.
*
* @param description
- * The description of this help topic, or null if this help topic
- * doesn't have a more detailed description.
+ * The description of this help topic, or null if this help
+ * topic doesn't have a more detailed description.
*/
public GenericHelp(final String summary, final String description) {
- if(summary == null) {
+ if (summary == null) {
throw new NullPointerException("Help summary must be non-null");
}
@@ -31,7 +31,7 @@ public class GenericHelp implements CommandHelp {
@Override
public String getDescription() {
- if(description == null) {
+ if (description == null) {
return summary;
}
@@ -49,12 +49,12 @@ public class GenericHelp implements CommandHelp {
builder.append("GenericHelp [");
- if(summary != null) {
+ if (summary != null) {
builder.append("summary=");
builder.append(summary);
}
- if(description != null) {
+ if (description != null) {
builder.append(", ");
builder.append("description=");
builder.append(description);
diff --git a/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java b/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java
index 93d55d8..1c50df3 100644
--- a/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java
+++ b/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java
@@ -56,7 +56,8 @@ public class BlockReaderCLI {
* @param sources
* The set of configured I/O sources.
*/
- public BlockReaderState(Map<String, BlockReader> readers, Map<String, Reader> sources) {
+ public BlockReaderState(Map<String, BlockReader> readers,
+ Map<String, Reader> sources) {
this.readers = readers;
this.sources = sources;
}
@@ -83,7 +84,7 @@ public class BlockReaderCLI {
* Create a new CLI for configuring BlockReaders.
*
* @param srcs
- * The container of initial I/O sources.
+ * The container of initial I/O sources.
*/
public BlockReaderCLI(Map<String, Reader> srcs) {
stat = new BlockReaderState(srcs);
@@ -93,7 +94,7 @@ public class BlockReaderCLI {
* Create a new CLI for configuring BlockReaders.
*
* @param state
- * The state object to use.
+ * The state object to use.
*/
public BlockReaderCLI(BlockReaderState state) {
stat = state;
@@ -104,7 +105,7 @@ public class BlockReaderCLI {
* Run the command line interface
*
* @param args
- * Ignored CLI args.
+ * Ignored CLI args.
*/
public static void main(String[] args) {
/* Create/configure I/O sources. */
@@ -122,13 +123,13 @@ public class BlockReaderCLI {
* Run the CLI on an input source.
*
* @param input
- * The place to read input from.
+ * The place to read input from.
*
* @param srcName
- * The name of the place to read input from.
+ * The name of the place to read input from.
*
* @param interactive
- * Whether or not the source is interactive
+ * Whether or not the source is interactive
*/
public void run(Scanner input, String srcName, boolean interactive) {
int lno = 0;
@@ -146,12 +147,15 @@ public class BlockReaderCLI {
/* Parse the command. */
Command com = Command.fromString(ln, lno, srcName);
/* Ignore blank commands. */
- if (com == null) continue;
+ if (com == null)
+ continue;
/* Handle a command. */
CommandStatus sts = handleCommand(com, interactive);
/* Exit if we finished or encountered a fatal error. */
- if (sts == FINISH || sts == ERROR) { return; }
+ if (sts == FINISH || sts == ERROR) {
+ return;
+ }
} while (input.hasNextLine());
}
@@ -159,11 +163,10 @@ public class BlockReaderCLI {
* Handle a command.
*
* @param com
- * The command to handle
+ * The command to handle
*
* @param interactive
- * Whether the current input source is interactive or
- * not.
+ * Whether the current input source is interactive or not.
* @return The status of the executed command.
*/
public CommandStatus handleCommand(Command com, boolean interactive) {
@@ -186,7 +189,8 @@ public class BlockReaderCLI {
case "exit":
case "quit":
if (interactive)
- System.out.printf("Exiting reader-conf, %d readers configured in %d commands\n",
+ System.out.printf(
+ "Exiting reader-conf, %d readers configured in %d commands\n",
stat.readers.size(), com.lno);
return FINISH;
default:
@@ -244,18 +248,19 @@ public class BlockReaderCLI {
try {
Pattern pat = Pattern.compile(filter);
- Predicate<Block> pred = (block) -> {
+ Predicate<Block> pred = block -> {
Matcher mat = pat.matcher(block.contents);
return mat.matches();
};
- BlockReader reader = new FilteredBlockReader(stat.readers.get(readerName), pred);
+ BlockReader reader
+ = new FilteredBlockReader(stat.readers.get(readerName), pred);
stat.readers.put(blockName, reader);
} catch (PatternSyntaxException psex) {
- LOGGER.severe(com.error("Invalid regular expression '%s' for filter. (%s)\n", filter,
- psex.getMessage()));
+ LOGGER.severe(com.error("Invalid regular expression '%s' for filter. (%s)\n",
+ filter, psex.getMessage()));
return FAIL;
}
@@ -319,7 +324,8 @@ public class BlockReaderCLI {
return FAIL;
}
- BlockReader reader = new ToggledBlockReader(stat.readers.get(parts[1]), stat.readers.get(parts[2]));
+ BlockReader reader = new ToggledBlockReader(stat.readers.get(parts[1]),
+ stat.readers.get(parts[2]));
stat.readers.put(blockName, reader);
return SUCCESS;
@@ -355,7 +361,8 @@ public class BlockReaderCLI {
return FAIL;
}
- BlockReader reader = new LayeredBlockReader(stat.readers.get(parts[1]), stat.readers.get(parts[2]));
+ BlockReader reader = new LayeredBlockReader(stat.readers.get(parts[1]),
+ stat.readers.get(parts[2]));
stat.readers.put(blockName, reader);
return SUCCESS;
@@ -460,12 +467,14 @@ public class BlockReaderCLI {
/* Get the delimiter, and create the reader. */
try {
- BlockReader reader = new SimpleBlockReader(delim, stat.sources.get(sourceName));
+ BlockReader reader
+ = new SimpleBlockReader(delim, stat.sources.get(sourceName));
stat.readers.put(blockName, reader);
} catch (PatternSyntaxException psex) {
- LOGGER.severe(com.error("Invalid regular expression '%s' for delimiter. (%s)\n", delim,
- psex.getMessage()));
+ LOGGER.severe(
+ com.error("Invalid regular expression '%s' for delimiter. (%s)\n",
+ delim, psex.getMessage()));
return FAIL;
}
diff --git a/base/src/main/java/bjc/utils/cli/objects/Command.java b/base/src/main/java/bjc/utils/cli/objects/Command.java
index 2be7fcd..ce2a985 100644
--- a/base/src/main/java/bjc/utils/cli/objects/Command.java
+++ b/base/src/main/java/bjc/utils/cli/objects/Command.java
@@ -60,18 +60,19 @@ public class Command {
* Create a new command.
*
* @param ln
- * The string to get the command from.
+ * The string to get the command from.
*
* @param lno
- * The number of the line the command came from.
+ * The number of the line the command came from.
*
* @param ioSrc
- * The name of where the I/O came from.
+ * The name of where the I/O came from.
*/
public Command(String ln, int lno, String ioSrc) {
int idx = ln.indexOf(' ');
- if (idx == -1) idx = ln.length();
+ if (idx == -1)
+ idx = ln.length();
/* Grab command parts. */
full = ln;
@@ -86,15 +87,14 @@ public class Command {
/**
* Removes up until the first occurrence of a particular string for the
* remaining command, and returns the removed string.
- *
+ *
* By default, both the substring and the remaining text are trimmed
* (leading/trailing spaces removed).
- *
+ *
* @param delm
- * The delimiter to stop substringing at.
- *
- * @return The substring, or null if there is no occurrence of the
- * delimiter.
+ * The delimiter to stop substringing at.
+ *
+ * @return The substring, or null if there is no occurrence of the delimiter.
*/
public String trimTo(String delm) {
return trimTo(delm, true);
@@ -103,19 +103,19 @@ public class Command {
/**
* Removes up until the first occurrence of a particular string for the
* remaining command, and returns the removed string.
- *
+ *
* @param delm
- * The delimiter to stop substringing at.
+ * The delimiter to stop substringing at.
* @param doTrim
- * Whether or not to trim the substring and remaining
- * command (Remove leading/trailing spaces).
- *
- * @return The substring, or null if there is no occurrence of the
- * delimiter.
+ * Whether or not to trim the substring and remaining command
+ * (Remove leading/trailing spaces).
+ *
+ * @return The substring, or null if there is no occurrence of the delimiter.
*/
public String trimTo(String delm, boolean doTrim) {
int idx = remn.indexOf(delm);
- if (idx == -1) return null;
+ if (idx == -1)
+ return null;
String tmp = remn.substring(0, idx);
remn = remn.substring(idx);
@@ -129,15 +129,15 @@ public class Command {
}
/**
- * Removes up until the first occurrence of a particular regex for the
- * remaining command, and returns the removed string.
- *
+ * Removes up until the first occurrence of a particular regex for the remaining
+ * command, and returns the removed string.
+ *
* By default, both the substring and the remaining text are trimmed
* (leading/trailing spaces removed).
- *
+ *
* @param rDelm
- * The regex to stop substringing at.
- *
+ * The regex to stop substringing at.
+ *
* @return The string, up to the matched pattern.
*/
public String trimToRX(String rDelm) {
@@ -145,15 +145,15 @@ public class Command {
}
/**
- * Removes up until the first occurrence of a particular regex for the
- * remaining command, and returns the removed string.
- *
+ * Removes up until the first occurrence of a particular regex for the remaining
+ * command, and returns the removed string.
+ *
* By default, both the substring and the remaining text are trimmed
* (leading/trailing spaces removed).
- *
+ *
* @param delm
- * The regex to stop substringing at.
- *
+ * The regex to stop substringing at.
+ *
* @return The string, up to the matched pattern.
*/
public String trimToRX(Pattern delm) {
@@ -161,15 +161,15 @@ public class Command {
}
/**
- * Removes up until the first occurrence of a particular regex for the
- * remaining command, and returns the removed string.
- *
+ * Removes up until the first occurrence of a particular regex for the remaining
+ * command, and returns the removed string.
+ *
* @param rDelm
- * The regex to stop substringing at.
+ * The regex to stop substringing at.
* @param doTrim
- * Whether or not to trim the substring and remaining
- * command (Remove leading/trailing spaces).
- *
+ * Whether or not to trim the substring and remaining command
+ * (Remove leading/trailing spaces).
+ *
* @return The string, up to the matched pattern.
*/
public String trimToRX(String rDelm, boolean doTrim) {
@@ -177,20 +177,21 @@ public class Command {
}
/**
- * Removes up until the first occurrence of a particular regex for the
- * remaining command, and returns the removed string.
+ * Removes up until the first occurrence of a particular regex for the remaining
+ * command, and returns the removed string.
*
* @param delm
- * The regex to stop substringing at.
+ * The regex to stop substringing at.
* @param doTrim
- * Whether or not to trim the substring and remaining
- * command (Remove leading/trailing spaces).
- *
+ * Whether or not to trim the substring and remaining command
+ * (Remove leading/trailing spaces).
+ *
* @return The string, up to the matched pattern.
*/
public String trimToRX(Pattern delm, boolean doTrim) {
Matcher mat = delm.matcher(remn);
- if (!mat.find()) return null;
+ if (!mat.find())
+ return null;
String tmp = remn.substring(0, mat.start());
remn = remn.substring(mat.end());
@@ -206,15 +207,14 @@ public class Command {
/**
* Removes up until the first occurrence of a particular string for the
* remaining command, and returns the removed string.
- *
+ *
* By default, both the substring and the remaining text are trimmed
* (leading/trailing spaces removed).
- *
+ *
* @param delm
- * The delimiter to stop substringing at.
- *
- * @return The substring, or null if there is no occurrence of the
- * delimiter.
+ * The delimiter to stop substringing at.
+ *
+ * @return The substring, or null if there is no occurrence of the delimiter.
*/
public String trimTo(char delm) {
return trimTo(delm, true);
@@ -223,19 +223,19 @@ public class Command {
/**
* Removes up until the first occurrence of a particular string for the
* remaining command, and returns the removed string.
- *
+ *
* @param delm
- * The delimiter to stop substringing at.
+ * The delimiter to stop substringing at.
* @param doTrim
- * Whether or not to trim the substring and remaining
- * command (Remove leading/trailing spaces).
- *
- * @return The substring, or null if there is no occurrence of the
- * delimiter.
+ * Whether or not to trim the substring and remaining command
+ * (Remove leading/trailing spaces).
+ *
+ * @return The substring, or null if there is no occurrence of the delimiter.
*/
public String trimTo(char delm, boolean doTrim) {
int idx = remn.indexOf(delm);
- if (idx == -1) return null;
+ if (idx == -1)
+ return null;
String tmp = remn.substring(0, idx);
remn = remn.substring(idx);
@@ -250,7 +250,7 @@ public class Command {
/**
* Check if this command has text after its name.
- *
+ *
* @return Whether or not this command has text after its name.
*/
public boolean hasRemaining() {
@@ -260,9 +260,8 @@ public class Command {
/**
* Parse a command from a string.
*
- * The main thing this does is ignore blank lines, as well as comments
- * marked by #'s either at the start of the line or part of the way
- * through the line.
+ * The main thing this does is ignore blank lines, as well as comments marked by
+ * #'s either at the start of the line or part of the way through the line.
*
* @param ln
* The string to get the command from.
@@ -276,8 +275,10 @@ public class Command {
*/
public static Command fromString(String ln, int lno, String srcName) {
/* Ignore blank lines and comments. */
- if (ln.equals("")) return null;
- if (ln.startsWith("#")) return null;
+ if (ln.equals(""))
+ return null;
+ if (ln.startsWith("#"))
+ return null;
/* Trim off comments part-way through the line. */
int idxHash = ln.indexOf('#');
@@ -289,14 +290,13 @@ public class Command {
}
/**
- * Give an informational message about something in relation to this
- * command.
+ * Give an informational message about something in relation to this command.
*
* @param info
- * The informational message.
+ * The informational message.
*
* @param parms
- * The parameters for the informational message.
+ * The parameters for the informational message.
* @return The information message.
*/
public String info(String info, Object... parms) {
@@ -313,7 +313,7 @@ public class Command {
*
* @param parms
* The parameters for the warning message.
- *
+ *
* @return The formatted warning.
*/
public String warn(String warning, Object... parms) {
@@ -326,11 +326,11 @@ public class Command {
* Give an error about something in relation to this command.
*
* @param err
- * The error message.
+ * The error message.
*
* @param parms
- * The parameters for the error message.
- *
+ * The parameters for the error message.
+ *
* @return The formatted error
*/
public String error(String err, Object... parms) {
diff --git a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java
index fc6e04a..d2595d6 100644
--- a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java
+++ b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java
@@ -41,8 +41,9 @@ public class DefineCLI {
this(new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>());
}
- public DefineState(Map<String, UnaryOperator<String>> defines, Map<String, String> strings,
- Map<String, String> formats, Map<String, Pattern> patterns) {
+ public DefineState(Map<String, UnaryOperator<String>> defines,
+ Map<String, String> strings, Map<String, String> formats,
+ Map<String, Pattern> patterns) {
this.defines = defines;
this.strings = strings;
@@ -63,14 +64,14 @@ public class DefineCLI {
/**
* Main method
- *
+ *
* @param args
- * CLI args
+ * CLI args
*/
public static void main(String[] args) {
DefineCLI defin = new DefineCLI();
- try(Scanner scn = new Scanner(System.in)) {
+ try (Scanner scn = new Scanner(System.in)) {
defin.run(scn, "console", true);
}
}
@@ -79,23 +80,25 @@ public class DefineCLI {
* Run the CLI on an input source.
*
* @param input
- * The place to read input from.
+ * The place to read input from.
* @param ioSource
- * The name of the place to read input from.
+ * The name of the place to read input from.
* @param interactive
- * Whether or not the source is interactive
+ * Whether or not the source is interactive
*/
public void run(Scanner input, String ioSource, boolean interactive) {
int lno = 0;
- while(input.hasNextLine()) {
- if(interactive) System.out.printf("define-conf(%d)>", lno);
+ while (input.hasNextLine()) {
+ if (interactive)
+ System.out.printf("define-conf(%d)>", lno);
String ln = input.nextLine();
lno += 1;
Command com = Command.fromString(ln, lno, ioSource);
- if(com == null) continue;
+ if (com == null)
+ continue;
handleCommand(com, interactive);
}
@@ -105,15 +108,15 @@ public class DefineCLI {
/**
* Handle a command
- *
+ *
* @param com
- * The command to handle
+ * The command to handle
* @param interactive
- * Whether or not our I/O stream is interactive
+ * Whether or not our I/O stream is interactive
* @return The status of the executed command.
*/
public CommandStatus handleCommand(Command com, boolean interactive) {
- switch(com.name) {
+ switch (com.name) {
case "def-string":
return defString(com);
case "def-format":
@@ -129,7 +132,7 @@ public class DefineCLI {
private CommandStatus defString(Command com) {
List<String> arguments = StringUtils.processArguments(com.remn);
- if(arguments.size() < 1) {
+ if (arguments.size() < 1) {
LOGGER.severe(com.error(
"def-string expects at least one argument: the name of the string to bind"));
return FAIL;
@@ -138,14 +141,14 @@ public class DefineCLI {
String name = arguments.get(0);
String strang;
- if(arguments.size() < 2) {
+ if (arguments.size() < 2) {
LOGGER.warning(com.warn("Binding empty string to name '%s'\n", name));
strang = "";
} else {
strang = arguments.get(1);
}
- if(stat.strings.containsKey(name)) {
+ if (stat.strings.containsKey(name)) {
LOGGER.warning(com.warn("Shadowing string '%s'\n", name));
}
@@ -157,7 +160,7 @@ public class DefineCLI {
private CommandStatus defFormat(Command com) {
List<String> arguments = StringUtils.processArguments(com.remn);
- if(arguments.size() < 1) {
+ if (arguments.size() < 1) {
LOGGER.severe(com.error(
"def-format expects at least one argument: the name of the format to bind"));
return FAIL;
@@ -166,14 +169,14 @@ public class DefineCLI {
String name = arguments.get(0);
String fmt;
- if(arguments.size() < 2) {
+ if (arguments.size() < 2) {
LOGGER.warning(com.warn("Binding empty format to name '%s'\n", name));
fmt = "";
} else {
fmt = arguments.get(1);
}
- if(stat.formats.containsKey(name)) {
+ if (stat.formats.containsKey(name)) {
LOGGER.warning(com.warn("Shadowing format '%s'\n", name));
}
@@ -185,20 +188,20 @@ public class DefineCLI {
private CommandStatus bindFormat(Command com) {
List<String> strings = StringUtils.processArguments(com.remn);
- if(strings.size() < 2) {
+ if (strings.size() < 2) {
LOGGER.severe(com.error(
"Binding a format requires at least two arguments: the format to bind, and the name to bind it to."));
return FAIL;
}
String formatName = strings.get(0);
- if(!stat.formats.containsKey(formatName)) {
+ if (!stat.formats.containsKey(formatName)) {
LOGGER.severe(com.error("Unknown format %s", formatName));
return FAIL;
}
String bindName = strings.get(1);
- if(stat.strings.containsKey(bindName)) {
+ if (stat.strings.containsKey(bindName)) {
LOGGER.warning(com.warn("Shadowing string '%s'", bindName));
}
@@ -209,13 +212,13 @@ public class DefineCLI {
itr.next();
itr.next();
- while(itr.hasNext()) {
+ while (itr.hasNext()) {
String name = itr.next();
- if(name.startsWith("$")) {
+ if (name.startsWith("$")) {
String varName = name.substring(1);
- if(stat.strings.containsKey(varName)) {
+ if (stat.strings.containsKey(varName)) {
fillIns.add(stat.strings.get(varName));
} else {
LOGGER.severe(com.error("Unknown string '%s'", varName));
@@ -226,15 +229,16 @@ public class DefineCLI {
}
}
- // CLFormatter fmt = new CLFormatter();
+ // CLFormatter fmt = new CLFormatter();
String formatted = "";
- // try {
- // formatted = fmt.formatString(stat.formats.get(formatName), fillIns);
- // } catch (IOException ioex) {
- // LOGGER.severe(com.error("IOException formatting string: %s", ioex.getMessage()));
- // return FAIL;
- // }
+ // try {
+ // formatted = fmt.formatString(stat.formats.get(formatName), fillIns);
+ // } catch (IOException ioex) {
+ // LOGGER.severe(com.error("IOException formatting string: %s",
+ // ioex.getMessage()));
+ // return FAIL;
+ // }
stat.strings.put(bindName, formatted);
diff --git a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java
index 27d74c8..59822e4 100644
--- a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java
+++ b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java
@@ -83,8 +83,10 @@ public class DelimSplitterCLI {
/*
* Handle a input command.
*/
- private void handleCommand(final String inp, final Scanner scn, final boolean isInteractive) {
- if (inp.equals("")) return;
+ private void handleCommand(final String inp, final Scanner scn,
+ final boolean isInteractive) {
+ if (inp.equals(""))
+ return;
int idx = inp.indexOf(' ');
@@ -116,14 +118,15 @@ public class DelimSplitterCLI {
case "splitter-add":
split.addSimpleDelimiters(argArray);
if (verbose) {
- System.out.println("Added delimiters " + StringUtils.toEnglishList(argArray, true));
+ System.out.println(
+ "Added delimiters " + StringUtils.toEnglishList(argArray, true));
}
break;
case "splitter-addmulti":
split.addMultiDelimiters(argArray);
if (verbose) {
- System.out.println(
- "Added multi-delimiters " + StringUtils.toEnglishList(argArray, true));
+ System.out.println("Added multi-delimiters "
+ + StringUtils.toEnglishList(argArray, true));
}
break;
case "splitter-addmatch":
@@ -150,7 +153,8 @@ public class DelimSplitterCLI {
dlm.addGroup(groups.get(arg));
}
if (verbose) {
- System.out.println("Added groups " + StringUtils.toEnglishList(argArray, true));
+ System.out.println(
+ "Added groups " + StringUtils.toEnglishList(argArray, true));
}
break;
case "delims-setinitial":
@@ -176,7 +180,8 @@ public class DelimSplitterCLI {
groups.put(arg, new DelimiterGroup<>(arg));
}
if (verbose) {
- System.out.println("Created groups " + StringUtils.toEnglishList(argArray, true));
+ System.out.println(
+ "Created groups " + StringUtils.toEnglishList(argArray, true));
}
break;
case "delimgroups-edit":
@@ -238,14 +243,16 @@ public class DelimSplitterCLI {
} catch (final FileNotFoundException fnfex) {
System.out.println("Couldn't find file '" + args + "'");
} catch (final IOException ioex) {
- System.out.println("I/O error with file '" + args + "'\nCause: " + ioex.getMessage());
+ System.out.println(
+ "I/O error with file '" + args + "'\nCause: " + ioex.getMessage());
}
}
/*
* Handle editing a group.
*/
- private void handleEditGroup(final String arg, final Scanner scn, final boolean isInteractive) {
+ private void handleEditGroup(final String arg, final Scanner scn,
+ final boolean isInteractive) {
if (!groups.containsKey(arg)) {
System.out.println("No group named '" + arg + "'");
return;
@@ -306,8 +313,8 @@ public class DelimSplitterCLI {
case "add-implied-subgroup":
group.implySubgroup(argArray[0], argArray[1]);
if (verbose) {
- System.out.printf("Made closer '%s' imply a '%s' subgroup\n", argArray[0],
- argArray[1]);
+ System.out.printf("Made closer '%s' imply a '%s' subgroup\n",
+ argArray[0], argArray[1]);
}
break;
case "add-opener":
@@ -320,14 +327,15 @@ public class DelimSplitterCLI {
case "add-reopener":
group.addPredOpener(new RegexOpener(argArray[0], argArray[1]));
if (verbose) {
- System.out.printf("Added regex '%s' as opener for '%s'\n", argArray[1],
- argArray[0]);
+ System.out.printf("Added regex '%s' as opener for '%s'\n",
+ argArray[1], argArray[0]);
}
break;
case "add-recloser":
group.addPredCloser(new RegexCloser(argArray[0]));
if (verbose) {
- System.out.printf("Added parameterized string '%s' as closer\n", argArray[0]);
+ System.out.printf("Added parameterized string '%s' as closer\n",
+ argArray[0]);
}
break;
case "debug":
@@ -355,8 +363,8 @@ public class DelimSplitterCLI {
printDelimSeq(res);
} catch (final DelimiterException dex) {
- System.out.println("Expression '" + args + "' isn't properly delimited.\n\tCause: "
- + dex.getMessage());
+ System.out.println("Expression '" + args
+ + "' isn't properly delimited.\n\tCause: " + dex.getMessage());
}
}
@@ -392,7 +400,8 @@ public class DelimSplitterCLI {
strings = new FunctionalList<>(tks);
}
try {
- final ITree<String> delim = dlm.delimitSequence(strings.toArray(new String[0]));
+ final ITree<String> delim
+ = dlm.delimitSequence(strings.toArray(new String[0]));
printDelimSeq(delim);
} catch (final DelimiterException dex) {
@@ -420,7 +429,7 @@ public class DelimSplitterCLI {
}
private void intPrintDelimTree(final ITree<String> tree, final StringBuilder sb) {
- tree.doForChildren((child) -> {
+ tree.doForChildren(child -> {
intPrintDelimNode(child, sb);
});
}
@@ -462,7 +471,7 @@ public class DelimSplitterCLI {
* Main method
*
* @param args
- * Unused CLI args.
+ * Unused CLI args.
*/
public static void main(final String[] args) {
final DelimSplitterCLI tst = new DelimSplitterCLI();
diff --git a/base/src/main/java/bjc/utils/components/ComponentDescription.java b/base/src/main/java/bjc/utils/components/ComponentDescription.java
index 57005e2..189ef90 100644
--- a/base/src/main/java/bjc/utils/components/ComponentDescription.java
+++ b/base/src/main/java/bjc/utils/components/ComponentDescription.java
@@ -8,12 +8,13 @@ package bjc.utils.components;
public class ComponentDescription implements IDescribedComponent {
/* Check arguments are good. */
@SuppressWarnings("unused")
- private static void sanityCheckArgs(final String name, final String author, final String description,
- final int version) {
- if(name == null) {
+ private static void sanityCheckArgs(final String name, final String author,
+ final String description, final int version) {
+ if (name == null) {
throw new NullPointerException("Component name can't be null");
- } else if(version <= 0) {
- throw new IllegalArgumentException("Component version must be greater than 0");
+ } else if (version <= 0) {
+ throw new IllegalArgumentException(
+ "Component version must be greater than 0");
}
}
@@ -30,22 +31,22 @@ public class ComponentDescription implements IDescribedComponent {
* Create a new component description.
*
* @param name
- * The name of the component.
+ * The name of the component.
*
* @param author
- * The author of the component.
+ * The author of the component.
*
* @param description
- * The description of the component.
+ * The description of the component.
*
* @param version
- * The version of the component.
+ * The version of the component.
*
* @throws IllegalArgumentException
- * Thrown if version is less than 1.
+ * Thrown if version is less than 1.
*/
- public ComponentDescription(final String name, final String author, final String description,
- final int version) {
+ public ComponentDescription(final String name, final String author,
+ final String description, final int version) {
sanityCheckArgs(name, author, description, version);
this.name = name;
@@ -56,7 +57,7 @@ public class ComponentDescription implements IDescribedComponent {
@Override
public String getAuthor() {
- if(author == null) {
+ if (author == null) {
return IDescribedComponent.super.getAuthor();
}
@@ -65,7 +66,7 @@ public class ComponentDescription implements IDescribedComponent {
@Override
public String getDescription() {
- if(description == null) {
+ if (description == null) {
return IDescribedComponent.super.getDescription();
}
@@ -112,25 +113,35 @@ public class ComponentDescription implements IDescribedComponent {
*/
@Override
public boolean equals(final Object obj) {
- if(this == obj) return true;
- if(obj == null) return false;
- if(getClass() != obj.getClass()) return false;
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
final ComponentDescription other = (ComponentDescription) obj;
- if(author == null) {
- if(other.author != null) return false;
- } else if(!author.equals(other.author)) return false;
-
- if(description == null) {
- if(other.description != null) return false;
- } else if(!description.equals(other.description)) return false;
-
- if(name == null) {
- if(other.name != null) return false;
- } else if(!name.equals(other.name)) return false;
-
- if(version != other.version) return false;
+ if (author == null) {
+ if (other.author != null)
+ return false;
+ } else if (!author.equals(other.author))
+ return false;
+
+ if (description == null) {
+ if (other.description != null)
+ return false;
+ } else if (!description.equals(other.description))
+ return false;
+
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+
+ if (version != other.version)
+ return false;
return true;
}
diff --git a/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
index ee6e913..87a749e 100644
--- a/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
+++ b/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
@@ -13,11 +13,12 @@ import bjc.utils.ioutils.RuleBasedConfigReader;
* The file format is based entirely off of pragma statements, and should have
* at least one of each of the following statements
* <ul>
- * <li>pragma name &lt;component-name&rt; </li>
- * <li>pragma author &lt;component-version&rt; </li>
- * <li>pragma description &lt;component-description&rt;</li>
- * <li>pragma version &lt;component-version&rt; </li>
+ * <li>pragma name &lt;component-name&rt;</li>
+ * <li>pragma author &lt;component-version&rt;</li>
+ * <li>pragma description &lt;component-description&rt;</li>
+ * <li>pragma version &lt;component-version&rt;</li>
* </ul>
+ *
* @author ben
*/
public class ComponentDescriptionFileParser {
@@ -27,14 +28,13 @@ public class ComponentDescriptionFileParser {
/* Initialize the reader and its pragmas. */
static {
/*
- * This reader works entirely off of pragmas, so no need to
- * handle rules.
+ * This reader works entirely off of pragmas, so no need to handle rules.
*/
reader = new RuleBasedConfigReader<>((tokenizer, statePair) -> {
/* Don't need to do anything on rule start. */
}, (tokenizer, state) -> {
/* Don't need to do anything on rule continuation. */
- }, (state) -> {
+ }, state -> {
/* Don't need to do anything on rule end. */
});
@@ -46,19 +46,19 @@ public class ComponentDescriptionFileParser {
* Parse a component description from a stream.
*
* @param inputSource
- * The stream to parse from.
+ * The stream to parse from.
*
* @return The description parsed from the stream.
*/
public static ComponentDescription fromStream(final InputStream inputSource) {
- if(inputSource == null) {
+ if (inputSource == null) {
throw new NullPointerException("Input source must not be null");
}
ComponentDescriptionState state = new ComponentDescriptionState();
/*
- * This is valid, because the thing that is returned is the same
- * reference we passed in.
+ * This is valid, because the thing that is returned is the same reference we
+ * passed in.
*/
reader.fromStream(inputSource, state);
@@ -67,14 +67,17 @@ public class ComponentDescriptionFileParser {
/* Create all the pragmas the reader needs to function. */
private static void setupReaderPragmas() {
- reader.addPragma("name", buildStringCollapser("name", (name, state) -> state.setName(name)));
+ reader.addPragma("name",
+ buildStringCollapser("name", (name, state) -> state.setName(name)));
- reader.addPragma("author", buildStringCollapser("author", (author, state) -> state.setAuthor(author)));
+ reader.addPragma("author", buildStringCollapser("author",
+ (author, state) -> state.setAuthor(author)));
reader.addPragma("description", buildStringCollapser("description",
(description, state) -> state.setDescription(description)));
- reader.addPragma("version", buildInteger("version", (version, state) -> state.setVersion(version)));
+ reader.addPragma("version",
+ buildInteger("version", (version, state) -> state.setVersion(version)));
}
private static final class ComponentDescriptionState {
@@ -94,7 +97,7 @@ public class ComponentDescriptionFileParser {
* Set the author of this component.
*
* @param author
- * The author of this component.
+ * The author of this component.
*/
public void setAuthor(final String author) {
this.author = author;
@@ -104,7 +107,7 @@ public class ComponentDescriptionFileParser {
* Set the description of this component.
*
* @param description
- * The description of this component.
+ * The description of this component.
*/
public void setDescription(final String description) {
this.description = description;
@@ -114,7 +117,7 @@ public class ComponentDescriptionFileParser {
* Set the name of this component.
*
* @param name
- * The name of this component.
+ * The name of this component.
*/
public void setName(final String name) {
this.name = name;
@@ -124,7 +127,7 @@ public class ComponentDescriptionFileParser {
* Set the version of this component.
*
* @param version
- * The version of this component.
+ * The version of this component.
*/
public void setVersion(final int version) {
this.version = version;
@@ -154,25 +157,35 @@ public class ComponentDescriptionFileParser {
@Override
public boolean equals(final Object obj) {
- if(this == obj) return true;
- if(obj == null) return false;
- if(getClass() != obj.getClass()) return false;
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
final ComponentDescriptionState other = (ComponentDescriptionState) obj;
- if(author == null) {
- if(other.author != null) return false;
- } else if(!author.equals(other.author)) return false;
+ if (author == null) {
+ if (other.author != null)
+ return false;
+ } else if (!author.equals(other.author))
+ return false;
- if(description == null) {
- if(other.description != null) return false;
- } else if(!description.equals(other.description)) return false;
+ if (description == null) {
+ if (other.description != null)
+ return false;
+ } else if (!description.equals(other.description))
+ return false;
- if(name == null) {
- if(other.name != null) return false;
- } else if(!name.equals(other.name)) return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
- if(version != other.version) return false;
+ if (version != other.version)
+ return false;
return true;
}
@@ -187,19 +200,19 @@ public class ComponentDescriptionFileParser {
final StringBuilder builder = new StringBuilder();
builder.append("ComponentDescriptionState [");
- if(name != null) {
+ if (name != null) {
builder.append("name=");
builder.append(name);
builder.append(", ");
}
- if(description != null) {
+ if (description != null) {
builder.append("description=");
builder.append(description);
builder.append(", ");
}
- if(author != null) {
+ if (author != null) {
builder.append("author=");
builder.append(author);
builder.append(", ");
diff --git a/base/src/main/java/bjc/utils/components/FileComponentRepository.java b/base/src/main/java/bjc/utils/components/FileComponentRepository.java
index 113c6dc..82d2770 100644
--- a/base/src/main/java/bjc/utils/components/FileComponentRepository.java
+++ b/base/src/main/java/bjc/utils/components/FileComponentRepository.java
@@ -22,12 +22,13 @@ import bjc.utils.funcutils.FileUtils;
* @author ben
*
* @param <ComponentType>
- * The type of component being read in.
+ * The type of component being read in.
*/
public class FileComponentRepository<ComponentType extends IDescribedComponent>
implements IComponentRepository<ComponentType> {
/* The logger to use for storing data about this class. */
- private static final Logger CLASS_LOGGER = Logger.getLogger("FileComponentRepository");
+ private static final Logger CLASS_LOGGER
+ = Logger.getLogger("FileComponentRepository");
/* The internal storage of components. */
private IMap<String, ComponentType> components;
@@ -39,27 +40,27 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent>
* 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.
+ * 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.
+ * The directory to read component files from.
*
* @param componentReader
- * The function to use to convert files to components.
+ * The function to use to convert files to components.
*/
public FileComponentRepository(final File directory,
final Function<File, ? extends ComponentType> componentReader) {
/* Make sure we have valid arguments. */
- if(directory == null) {
+ if (directory == null) {
throw new NullPointerException("Directory must not be null");
- } else if(!directory.isDirectory()) {
+ } else if (!directory.isDirectory()) {
String msg = String.format(
"File %s is not a directory. Components can only be read from a directory.",
directory);
throw new IllegalArgumentException(msg);
- } else if(componentReader == null) {
+ } else if (componentReader == null) {
throw new NullPointerException("Component reader must not be null");
}
@@ -71,40 +72,40 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent>
final IHolder<Boolean> isFirstDir = new Identity<>(true);
/*
- * Predicate to use to traverse all the files in a directory,
- * but not recurse into sub-directories.
+ * Predicate to use to traverse all the files in a directory, but not recurse
+ * into sub-directories.
*/
- final BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, attr) -> {
- 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
- * directory.
- */
- isFirstDir.replace(false);
-
- return true;
- };
+ final BiPredicate<Path, BasicFileAttributes> firstLevelTraverser
+ = (pth, attr) -> {
+ 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 directory.
+ */
+ isFirstDir.replace(false);
+
+ return true;
+ };
/* Try reading components. */
try {
- FileUtils.traverseDirectory(sourceDirectory, firstLevelTraverser, (pth, attr) -> {
- loadComponent(componentReader, pth);
-
- /*
- * Keep loading components, even if this one
- * failed.
- */
- return true;
- });
- } catch(final IOException ioex) {
- CLASS_LOGGER.log(Level.WARNING, ioex, () -> "Error found reading component from file.");
+ FileUtils.traverseDirectory(sourceDirectory, firstLevelTraverser,
+ (pth, attr) -> {
+ loadComponent(componentReader, pth);
+
+ /*
+ * Keep loading components, even if this one failed.
+ */
+ return true;
+ });
+ } catch (final IOException ioex) {
+ CLASS_LOGGER.log(Level.WARNING, ioex,
+ () -> "Error found reading component from file.");
}
}
@@ -129,35 +130,39 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent>
}
/* Load a component from a file */
- private void loadComponent(final Function<File, ? extends ComponentType> componentReader, final Path pth) {
+ private void loadComponent(
+ final Function<File, ? extends ComponentType> componentReader,
+ final Path pth) {
try {
/* Try to load the component. */
final ComponentType component = componentReader.apply(pth.toFile());
- if(component == null) {
+ if (component == null) {
throw new NullPointerException("Component reader read null component");
- } else if(!components.containsKey(component.getName())) {
+ } else if (!components.containsKey(component.getName())) {
/*
- * We only care about the latest version of a
- * component.
+ * We only care about the latest version of a component.
*/
- final ComponentType oldComponent = components.put(component.getName(), component);
+ final ComponentType oldComponent
+ = components.put(component.getName(), component);
- if(oldComponent.getVersion() > component.getVersion()) {
+ if (oldComponent.getVersion() > component.getVersion()) {
components.put(oldComponent.getName(), oldComponent);
}
} else {
StringBuilder sb = new StringBuilder();
sb.append("Found a duplicate component.\n");
- sb.append("Multiple versions of the same component are not currently supported.\n");
+ sb.append(
+ "Multiple versions of the same component are not currently supported.\n");
sb.append("Only the latest version of the component ");
sb.append(component);
sb.append(" will be registered.");
CLASS_LOGGER.warning(sb.toString());
}
- } catch(final Exception ex) {
- String msg = String.format("Error found reading component from file %s. It will not be loaded.",
+ } catch (final Exception ex) {
+ String msg = String.format(
+ "Error found reading component from file %s. It will not be loaded.",
pth.toString());
CLASS_LOGGER.log(Level.WARNING, ex, () -> msg);
@@ -176,13 +181,13 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent>
final StringBuilder builder = new StringBuilder();
builder.append("FileComponentRepository [");
- if(components != null) {
+ if (components != null) {
builder.append("components=");
builder.append(components);
builder.append(", ");
}
- if(sourceDirectory != null) {
+ if (sourceDirectory != null) {
builder.append("sourceDirectory=");
builder.append(sourceDirectory);
}
diff --git a/base/src/main/java/bjc/utils/components/IComponentRepository.java b/base/src/main/java/bjc/utils/components/IComponentRepository.java
index 9339a19..5ebb1de 100644
--- a/base/src/main/java/bjc/utils/components/IComponentRepository.java
+++ b/base/src/main/java/bjc/utils/components/IComponentRepository.java
@@ -10,7 +10,7 @@ import bjc.funcdata.IMap;
* @author ben
*
* @param <ComponentType>
- * The type of components contained in this repository.
+ * The type of components contained in this repository.
*/
public interface IComponentRepository<ComponentType extends IDescribedComponent> {
/**
@@ -25,10 +25,9 @@ public interface IComponentRepository<ComponentType extends IDescribedComponent>
* Get a component with a specific name.
*
* @param name
- * The name of the component to retrieve.
+ * The name of the component to retrieve.
*
- * @return The named component, or null if no component with that name
- * exists.
+ * @return The named component, or null if no component with that name exists.
*/
public ComponentType getByName(String name);
diff --git a/base/src/main/java/bjc/utils/components/IDescribedComponent.java b/base/src/main/java/bjc/utils/components/IDescribedComponent.java
index 6921849..ae3e06c 100644
--- a/base/src/main/java/bjc/utils/components/IDescribedComponent.java
+++ b/base/src/main/java/bjc/utils/components/IDescribedComponent.java
@@ -22,8 +22,8 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> {
/**
* Get the description of this component.
*
- * Providing this is optional, with the default being a note that no
- * description was provided.
+ * Providing this is optional, with the default being a note that no description
+ * was provided.
*
* @return The description of the component
*/
@@ -55,7 +55,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> {
default int compareTo(final IDescribedComponent o) {
int res = getName().compareTo(o.getName());
- if(res == 0) {
+ if (res == 0) {
res = getVersion() - o.getVersion();
}
diff --git a/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java b/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java
index 22bc55d..ec3911e 100644
--- a/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java
+++ b/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java
@@ -4,10 +4,11 @@ import bjc.funcdata.IMap;
/**
* A repository of components stored in memory.
- *
+ *
* @author bjculkin
*
- * @param <ComponentType> The type of component stored in the repository.
+ * @param <ComponentType>
+ * The type of component stored in the repository.
*/
public class MemoryComponentRepository<ComponentType extends IDescribedComponent>
implements IComponentRepository<ComponentType> {
@@ -17,9 +18,9 @@ public class MemoryComponentRepository<ComponentType extends IDescribedComponent
/**
* Create a new memory component repository.
- *
+ *
* @param repo
- * The set of components to use.
+ * The set of components to use.
*/
public MemoryComponentRepository(IMap<String, ComponentType> repo) {
this(repo, "memory");
@@ -27,11 +28,11 @@ public class MemoryComponentRepository<ComponentType extends IDescribedComponent
/**
* Create a new memory component repository.
- *
+ *
* @param repo
- * The set of components to use.
+ * The set of components to use.
* @param source
- * Where the components came from.
+ * Where the components came from.
*/
public MemoryComponentRepository(IMap<String, ComponentType> repo, String source) {
this.repo = repo;
@@ -44,10 +45,12 @@ public class MemoryComponentRepository<ComponentType extends IDescribedComponent
return repo;
}
+ @Override
public ComponentType getByName(String name) {
return repo.get(name);
}
+ @Override
public String getSource() {
return source;
}
diff --git a/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java b/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java
index 44bef61..dcd47de 100644
--- a/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java
+++ b/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java
@@ -20,7 +20,7 @@ public class FileNotChosenException extends IOException {
* Create a new exception with the given cause.
*
* @param cause
- * The cause of why the exception was thrown.
+ * The cause of why the exception was thrown.
*/
public FileNotChosenException(final String cause) {
super(cause);
diff --git a/base/src/main/java/bjc/utils/exceptions/InvalidDirectionException.java b/base/src/main/java/bjc/utils/exceptions/InvalidDirectionException.java
index 216953c..d20b2d1 100644
--- a/base/src/main/java/bjc/utils/exceptions/InvalidDirectionException.java
+++ b/base/src/main/java/bjc/utils/exceptions/InvalidDirectionException.java
@@ -1,9 +1,8 @@
package bjc.utils.exceptions;
/**
- * Represents the condition where a direction has been used in a improper
- * manner
- *
+ * Represents the condition where a direction has been used in a improper manner
+ *
* @author ben
*
*/
@@ -16,9 +15,9 @@ public class InvalidDirectionException extends IllegalArgumentException {
/**
* Create a new {@link InvalidDirectionException} with the given cause
- *
+ *
* @param cause
- * The situation that resulting in this exit being thrown
+ * The situation that resulting in this exit being thrown
*/
public InvalidDirectionException(String cause) {
super(cause);
diff --git a/base/src/main/java/bjc/utils/exceptions/InvalidToken.java b/base/src/main/java/bjc/utils/exceptions/InvalidToken.java
index be8fcd9..c203f91 100644
--- a/base/src/main/java/bjc/utils/exceptions/InvalidToken.java
+++ b/base/src/main/java/bjc/utils/exceptions/InvalidToken.java
@@ -2,6 +2,7 @@ package bjc.utils.exceptions;
/**
* Exception thrown when an invalid token is found.
+ *
* @author Ben Culkin
*
*/
@@ -10,7 +11,9 @@ public class InvalidToken extends RuntimeException {
/**
* Create an invalid token exception.
- * @param tok The token that was invalid.
+ *
+ * @param tok
+ * The token that was invalid.
*/
public InvalidToken(String tok) {
super(String.format("Did not recognize token '%s' as a valid token", tok));
diff --git a/base/src/main/java/bjc/utils/exceptions/OperandsRemaining.java b/base/src/main/java/bjc/utils/exceptions/OperandsRemaining.java
index ca83b30..b305542 100644
--- a/base/src/main/java/bjc/utils/exceptions/OperandsRemaining.java
+++ b/base/src/main/java/bjc/utils/exceptions/OperandsRemaining.java
@@ -3,7 +3,7 @@ package bjc.utils.exceptions;
/**
* Exception thrown when an operation has finished, but still has more input
* that has not been processed.
- *
+ *
* @author Ben Culkin
*
*/
@@ -16,11 +16,12 @@ public class OperandsRemaining extends RuntimeException {
public OperandsRemaining() {
super("Operation had input left-over");
}
-
+
/**
* Create a new OperandsRemaining exception with a specific message.
- *
- * @param msg The message of the exception.
+ *
+ * @param msg
+ * The message of the exception.
*/
public OperandsRemaining(String msg) {
super(msg);
diff --git a/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
index 12bc6e4..684c63d 100644
--- a/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
+++ b/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
@@ -20,7 +20,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.
+ * The message to explain why the exception was thrown.
*/
public PragmaFormatException(final String message) {
super(message);
diff --git a/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java b/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java
index cbb2822..dec89a3 100644
--- a/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java
+++ b/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java
@@ -15,7 +15,7 @@ public class UnknownPragmaException extends InputMismatchException {
* Create a new exception with the given cause.
*
* @param cause
- * The cause for throwing this exception.
+ * The cause for throwing this exception.
*/
public UnknownPragmaException(final String cause) {
super(cause);
diff --git a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java
index fab2ba2..81313c8 100644
--- a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java
@@ -15,31 +15,33 @@ public class CollectorUtils {
* Create a collector that applies two collectors at once.
*
* @param <InitialType>
- * The type of the collection to collect from.
+ * The type of the collection to collect from.
*
* @param <AuxType1>
- * The intermediate type of the first collector.
+ * The intermediate type of the first collector.
*
* @param <AuxType2>
- * The intermediate type of the second collector.
+ * The intermediate type of the second collector.
*
* @param <FinalType1>
- * The final type of the first collector.
+ * The final type of the first collector.
*
* @param <FinalType2>
- * The final type of the second collector.
+ * The final type of the second collector.
*
* @param first
- * The first collector to use.
+ * The first collector to use.
*
* @param second
- * The second collector to use.
+ * The second collector to use.
*
* @return A collector that functions as mentioned above.
*/
- public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> compoundCollect(
- final Collector<InitialType, AuxType1, FinalType1> first,
- final Collector<InitialType, AuxType2, FinalType2> second) {
+ public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2>
+ Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>,
+ IPair<FinalType1, FinalType2>>
+ compoundCollect(final Collector<InitialType, AuxType1, FinalType1> first,
+ final Collector<InitialType, AuxType2, FinalType2> second) {
return new CompoundCollector<>(first, second);
}
}
diff --git a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java
index 555d3d1..5e51c20 100644
--- a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java
+++ b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java
@@ -18,7 +18,8 @@ import bjc.data.Pair;
* @author Ben Culkin
*/
final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2>
- implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> {
+ implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>,
+ IPair<FinalType1, FinalType2>> {
/* Our characteristics. */
private final Set<java.util.stream.Collector.Characteristics> characteristicSet;
@@ -31,10 +32,10 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final
* Create a collector that uses two collectors.
*
* @param first
- * The first collector.
+ * The first collector.
*
* @param second
- * The second collector.
+ * The second collector.
*/
public CompoundCollector(final Collector<InitialType, AuxType1, FinalType1> first,
final Collector<InitialType, AuxType2, FinalType2> second) {
@@ -71,27 +72,24 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final
final BinaryOperator<AuxType1> firstCombiner = first.combiner();
final BinaryOperator<AuxType2> secondCombiner = second.combiner();
- return (leftState, rightState) -> {
- return leftState.unwrap(leftPair -> {
- return rightState.transform(rightPair -> {
- return leftPair.combine(rightPair, firstCombiner, secondCombiner);
- });
+ return (leftState, rightState) -> leftState.unwrap(leftPair -> {
+ return rightState.transform(rightPair -> {
+ return leftPair.combine(rightPair, firstCombiner, secondCombiner);
});
- };
+ });
}
@Override
- public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> finisher() {
- return state -> {
- return state.unwrap(pair -> {
- return pair.bind((left, right) -> {
- final FinalType1 finalLeft = first.finisher().apply(left);
- final FinalType2 finalRight = second.finisher().apply(right);
+ public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>>
+ finisher() {
+ return state -> state.unwrap(pair -> {
+ return pair.bind((left, right) -> {
+ final FinalType1 finalLeft = first.finisher().apply(left);
+ final FinalType2 finalRight = second.finisher().apply(right);
- return new Pair<>(finalLeft, finalRight);
- });
+ return new Pair<>(finalLeft, finalRight);
});
- };
+ });
}
@Override
diff --git a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java
index 37ebd50..e8898ca 100644
--- a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java
@@ -16,29 +16,29 @@ public class EnumUtils {
* Do an action for a random number of enum values.
*
* @param <E>
- * The type of the enum.
+ * The type of the enum.
*
* @param clasz
- * The enum class.
+ * The enum class.
*
* @param nValues
- * The number of values to execute the action on.
+ * The number of values to execute the action on.
*
* @param action
- * The action to perform on random values.
+ * The action to perform on random values.
*
* @param rnd
- * The source of randomness to use.
+ * The source of randomness to use.
*/
- public static <E extends Enum<E>> void doForValues(final Class<E> clasz, final int nValues,
- final Consumer<E> action, final Random rnd) {
+ public static <E extends Enum<E>> void doForValues(final Class<E> clasz,
+ final int nValues, final Consumer<E> action, final Random rnd) {
final E[] enumValues = clasz.getEnumConstants();
final IList<E> valueList = new FunctionalList<>(enumValues);
final int randomValueCount = enumValues.length - nValues;
- for(int i = 0; i <= randomValueCount; i++) {
+ for (int i = 0; i <= randomValueCount; i++) {
final E rDir = valueList.randItem(rnd::nextInt);
valueList.removeMatching(rDir);
@@ -51,17 +51,18 @@ public class EnumUtils {
* Get a random value from an enum.
*
* @param <E>
- * The type of the enum.
+ * The type of the enum.
*
* @param clasz
- * The class of the enum.
+ * The class of the enum.
*
* @param rnd
- * The random source to use.
+ * The random source to use.
*
* @return A random value from the specified enum.
*/
- public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz, final Random rnd) {
+ public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz,
+ final Random rnd) {
final E[] enumValues = clasz.getEnumConstants();
return new FunctionalList<>(enumValues).randItem(rnd::nextInt);
diff --git a/base/src/main/java/bjc/utils/funcutils/FileUtils.java b/base/src/main/java/bjc/utils/funcutils/FileUtils.java
index 04ac6b0..477e395 100644
--- a/base/src/main/java/bjc/utils/funcutils/FileUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/FileUtils.java
@@ -14,30 +14,31 @@ import java.util.function.BiPredicate;
public class FileUtils {
/*
* @NOTE
- *
- * If it becomes necessary, write another overload for this with all the
- * buttons and knobs from walkFileTree.
+ *
+ * If it becomes necessary, write another overload for this with all the buttons
+ * and knobs from walkFileTree.
*/
/**
* Traverse a directory recursively. This is a depth-first traversal.
*
* @param root
- * The directory to start the traversal at.
+ * The directory to start the traversal at.
*
* @param predicate
- * The predicate to determine whether or not to traverse
- * a directory.
+ * The predicate to determine whether or not to traverse a
+ * directory.
*
* @param action
- * The action to invoke upon each file in the directory.
- * Returning true means to continue the traversal,
- * returning false stops it.
+ * The action to invoke upon each file in the directory.
+ * Returning true means to continue the traversal, returning
+ * false stops it.
*
* @throws IOException
- * If the walk throws an exception.
+ * If the walk throws an exception.
*
*/
- public static void traverseDirectory(final Path root, final BiPredicate<Path, BasicFileAttributes> predicate,
+ public static void traverseDirectory(final Path root,
+ final BiPredicate<Path, BasicFileAttributes> predicate,
final BiPredicate<Path, BasicFileAttributes> action) throws IOException {
Files.walkFileTree(root, new FunctionalFileVisitor(predicate, action));
}
diff --git a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java
index ff9fefb..70e521a 100644
--- a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java
@@ -13,38 +13,35 @@ import java.util.function.UnaryOperator;
*/
public class FuncUtils {
/**
- * Convert a binary function into a unary function that returns a
- * function.
+ * Convert a binary function into a unary function that returns a function.
*
* @param <A>
- * The initial type of the function.
+ * The initial type of the function.
*
* @param <B>
- * The intermediate type of the function.
+ * The intermediate type of the function.
*
* @param <C>
- * The terminal type of the function.
+ * The terminal type of the function.
*
* @param func
- * The function to transform.
+ * The function to transform.
*
- * @return The function transformed into a unary function returning a
- * function.
+ * @return The function transformed into a unary function returning a function.
*/
- public static <A, B, C> Function<A, Function<B, C>> curry2(final BiFunction<A, B, C> func) {
- return arg1 -> arg2 -> {
- return func.apply(arg1, arg2);
- };
+ public static <A, B, C> Function<A, Function<B, C>>
+ curry2(final BiFunction<A, B, C> func) {
+ return arg1 -> arg2 -> func.apply(arg1, arg2);
}
/**
* Do the specified action the specified number of times.
*
* @param nTimes
- * The number of times to do the action.
+ * The number of times to do the action.
*
* @param cons
- * The action to perform.
+ * The action to perform.
*/
public static void doTimes(final int nTimes, final Consumer<Integer> cons) {
for (int i = 0; i < nTimes; i++) {
@@ -56,36 +53,37 @@ public class FuncUtils {
* Return an operator that executes until it converges.
*
* @param op
- * The operator to execute.
+ * The operator to execute.
*
* @param maxTries
- * The maximum amount of times to apply the function in
- * an attempt to cause it to converge.
- *
+ * The maximum amount of times to apply the function in an
+ * attempt to cause it to converge.
+ *
* @return The requested operator.
*/
- public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, final int maxTries) {
- return converge(op, (nw, old) -> nw.equals(old), maxTries);
+ public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op,
+ final int maxTries) {
+ return converge(op, Object::equals, maxTries);
}
/**
* Return an operator that executes until it converges.
*
* @param op
- * The operator to execute.
+ * The operator to execute.
* @param converged
- * The predicate to execute to check if the function has
- * converged.
+ * The predicate to execute to check if the function has
+ * converged.
*
* @param maxTries
- * The maximum amount of times to apply the function in
- * an attempt to cause it to converge.
- *
+ * The maximum amount of times to apply the function in an
+ * attempt to cause it to converge.
+ *
* @return The requested operator.
*/
- public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, final BiPredicate<T, T> converged,
- final int maxTries) {
- return (val) -> {
+ public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op,
+ final BiPredicate<T, T> converged, final int maxTries) {
+ return val -> {
T newVal = op.apply(val);
T oldVal;
diff --git a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java
index fb2a697..c297465 100644
--- a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java
+++ b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java
@@ -22,10 +22,10 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> {
* Create a new file visitor, powered by functions.
*
* @param predicate
- * The predicate to use to pick which files to traverse.
+ * The predicate to use to pick which files to traverse.
*
* @param action
- * The function to execute on every file.
+ * The function to execute on every file.
*/
public FunctionalFileVisitor(final BiPredicate<Path, BasicFileAttributes> predicate,
final BiPredicate<Path, BasicFileAttributes> action) {
@@ -34,15 +34,19 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> {
}
@Override
- public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
- if(predicate.test(dir, attrs)) return FileVisitResult.CONTINUE;
+ public FileVisitResult preVisitDirectory(final Path dir,
+ final BasicFileAttributes attrs) throws IOException {
+ if (predicate.test(dir, attrs))
+ return FileVisitResult.CONTINUE;
return FileVisitResult.SKIP_SUBTREE;
}
@Override
- public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
- if(action.test(file, attrs)) return FileVisitResult.CONTINUE;
+ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
+ throws IOException {
+ if (action.test(file, attrs))
+ return FileVisitResult.CONTINUE;
return FileVisitResult.TERMINATE;
}
diff --git a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
index 455fbf8..681d707 100644
--- a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
+++ b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
@@ -12,7 +12,7 @@ import bjc.funcdata.IList;
* @author ben
*
* @param <E>
- * The type of element in the list being partitioned
+ * The type of element in the list being partitioned
*/
final class GroupPartIteration<E> implements Consumer<E> {
/* The list we're returning. */
@@ -35,21 +35,21 @@ final class GroupPartIteration<E> implements Consumer<E> {
* Create a new group partitioning iteration.
*
* @param returned
- * The list containing all of the existing partitions.
+ * The list containing all of the existing partitions.
*
* @param rejects
- * The items that have been rejected from a partition for being
- * too large.
+ * The items that have been rejected from a partition for being
+ * too large.
*
* @param nPerPart
- * The combined value of items that should go into each
- * partition.
+ * The combined value of items that should go into each
+ * partition.
*
* @param eleCount
- * The function to use to determine the value of an item.
+ * The function to use to determine the value of an item.
*/
- public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, final int nPerPart,
- final Function<E, Integer> eleCount) {
+ public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects,
+ final int nPerPart, final Function<E, Integer> eleCount) {
this.returnedList = returned;
this.rejectedItems = rejects;
this.numberPerPartition = nPerPart;
@@ -61,9 +61,10 @@ final class GroupPartIteration<E> implements Consumer<E> {
@Override
public void accept(final E value) {
- final boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition;
+ final boolean shouldStartPartition
+ = numberInCurrentPartition >= numberPerPartition;
- if(shouldStartPartition) {
+ if (shouldStartPartition) {
returnedList.add(currentPartition);
currentPartition = new FunctionalList<>();
@@ -71,10 +72,10 @@ final class GroupPartIteration<E> implements Consumer<E> {
} else {
final int currentElementCount = elementCounter.apply(value);
- final boolean shouldReject = (numberInCurrentPartition
- + currentElementCount) >= numberPerPartition;
+ final boolean shouldReject = (numberInCurrentPartition + currentElementCount)
+ >= numberPerPartition;
- if(shouldReject) {
+ if (shouldReject) {
rejectedItems.add(value);
} else {
currentPartition.add(value);
diff --git a/base/src/main/java/bjc/utils/funcutils/IBuilder.java b/base/src/main/java/bjc/utils/funcutils/IBuilder.java
index f8dd2fc..b1a2020 100644
--- a/base/src/main/java/bjc/utils/funcutils/IBuilder.java
+++ b/base/src/main/java/bjc/utils/funcutils/IBuilder.java
@@ -6,7 +6,7 @@ package bjc.utils.funcutils;
* @author ben
*
* @param <E>
- * The type of object being built.
+ * The type of object being built.
*/
public interface IBuilder<E> {
/**
@@ -15,8 +15,8 @@ public interface IBuilder<E> {
* @return The built object.
*
* @throws IllegalStateException
- * If the data in the builder cannot be built into its
- * corresponding object at this point in time.
+ * If the data in the builder cannot be built into
+ * its corresponding object at this point in time.
*/
public E build();
@@ -24,9 +24,11 @@ public interface IBuilder<E> {
* Reset the state of this builder to its initial state.
*
* @throws UnsupportedOperationException
- * If the builder doesn't support resetting its state.
+ * If the builder doesn't support
+ * resetting its state.
*/
public default void reset() {
- throw new UnsupportedOperationException("Builder doesn't support state resetting");
+ throw new UnsupportedOperationException(
+ "Builder doesn't support state resetting");
}
}
diff --git a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java
index 9559540..c219d7f 100644
--- a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java
+++ b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java
@@ -4,14 +4,14 @@ import java.util.function.Function;
/**
* A pair of functions to transform between a pair of types.
- *
+ *
* @author bjculkin
- *
+ *
* @param <S>
- * The source type of the isomorphism.
- *
+ * The source type of the isomorphism.
+ *
* @param <D>
- * The destination type of isomorphism.
+ * The destination type of isomorphism.
*/
public class Isomorphism<S, D> {
/* The function to the destination type. */
@@ -21,12 +21,12 @@ public class Isomorphism<S, D> {
/**
* Create a new isomorphism.
- *
+ *
* @param to
- * The 'forward' function, from the source to the definition.
- *
+ * The 'forward' function, from the source to the definition.
+ *
* @param from
- * The 'backward' function, from the definition to the source.
+ * The 'backward' function, from the definition to the source.
*/
public Isomorphism(Function<S, D> to, Function<D, S> from) {
toFunc = to;
@@ -35,10 +35,10 @@ public class Isomorphism<S, D> {
/**
* Apply the isomorphism forward.
- *
+ *
* @param val
- * The source value.
- *
+ * The source value.
+ *
* @return The destination value.
*/
public D to(S val) {
@@ -47,10 +47,10 @@ public class Isomorphism<S, D> {
/**
* Apply the isomorphism backward.
- *
+ *
* @param val
- * The destination value.
- *
+ * The destination value.
+ *
* @return The source value.
*/
public S from(D val) {
diff --git a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java
index 2b5fc57..a97e876 100644
--- a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java
@@ -7,20 +7,21 @@ import bjc.data.ArrayIterator;
/**
* Utility methods for dealing with iterators.
- *
+ *
* @author bjculkin
*
*/
public class IteratorUtils {
/**
* A chain iterator. This is essentially flatMap in iterator form.
+ *
* @author bjculkin
*
- * @param <T1>
- * The type of the input values.
- *
- * @param <T2>
- * The type of the output values.
+ * @param <T1>
+ * The type of the input values.
+ *
+ * @param <T2>
+ * The type of the output values.
*/
public static class ChainIterator<T1, T2> implements Iterator<T2> {
private Iterator<T1> mainItr;
@@ -30,23 +31,25 @@ public class IteratorUtils {
/**
* Create a new chain iterator.
- *
+ *
* @param mainItr
- * The main iterator for input.
- *
+ * The main iterator for input.
+ *
* @param trans
- * The transformation to use to produce the outputs.
+ * The transformation to use to produce the outputs.
*/
public ChainIterator(Iterator<T1> mainItr, Function<T1, Iterator<T2>> trans) {
this.mainItr = mainItr;
- this.trans = trans;
+ this.trans = trans;
}
@Override
public boolean hasNext() {
if (curItr != null) {
- if (curItr.hasNext()) return true;
- else return mainItr.hasNext();
+ if (curItr.hasNext())
+ return true;
+ else
+ return mainItr.hasNext();
}
return mainItr.hasNext();
@@ -64,9 +67,9 @@ public class IteratorUtils {
/**
* Convert an iterator to an iterable.
- *
+ *
* @param itr
- * The iterator to convert.
+ * The iterator to convert.
*
* @return An iterable that gives back that iterator.
*/
@@ -76,9 +79,9 @@ public class IteratorUtils {
/**
* Convert an iterable to an iterator.
- *
+ *
* @param itr
- * The iterable to convert.
+ * The iterable to convert.
*
* @return The iterator from that iterable
*/
@@ -90,7 +93,7 @@ public class IteratorUtils {
* Convert an array to an iterator.
*
* @param parms
- * The array to iterate over.
+ * The array to iterate over.
*
* @return An iterator over the provided array.
*/
@@ -101,16 +104,17 @@ public class IteratorUtils {
/**
* Create a chain iterator.
- *
+ *
* @param itrA
- * The iterator for input values.
- *
+ * The iterator for input values.
+ *
* @param itrB
- * The transformation for output values.
- *
+ * The transformation for output values.
+ *
* @return A chain iterator from the provided values.
*/
- public static <A, B> Iterator<B> chain(Iterator<A> itrA, Function<A, Iterator<B>> itrB) {
+ public static <A, B> Iterator<B> chain(Iterator<A> itrA,
+ Function<A, Iterator<B>> itrB) {
return new ChainIterator<>(itrA, itrB);
}
}
diff --git a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java
index 0130a77..f3637f9 100644
--- a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java
+++ b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java
@@ -26,7 +26,7 @@ public class LambdaLock {
* Create a new lambda-enabled lock.
*
* @param lck
- * The lock to wrap.
+ * The lock to wrap.
*/
public LambdaLock(final ReadWriteLock lck) {
readLock = lck.readLock();
@@ -37,7 +37,7 @@ public class LambdaLock {
* Execute an action with the read lock taken.
*
* @param supp
- * The action to call.
+ * The action to call.
*
* @return The result of the action.
*/
@@ -55,7 +55,7 @@ public class LambdaLock {
* Execute an action with the write lock taken.
*
* @param supp
- * The action to call.
+ * The action to call.
*
* @return The result of the action.
*/
@@ -73,7 +73,7 @@ public class LambdaLock {
* Execute an action with the read lock taken.
*
* @param action
- * The action to call.
+ * The action to call.
*/
public void read(final Runnable action) {
readLock.lock();
@@ -89,7 +89,7 @@ public class LambdaLock {
* Execute an action with the write lock taken.
*
* @param action
- * The action to call.
+ * The action to call.
*/
public void write(final Runnable action) {
writeLock.lock();
diff --git a/base/src/main/java/bjc/utils/funcutils/ListUtils.java b/base/src/main/java/bjc/utils/funcutils/ListUtils.java
index 0be42ed..f689d6c 100644
--- a/base/src/main/java/bjc/utils/funcutils/ListUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/ListUtils.java
@@ -21,16 +21,16 @@ public class ListUtils {
private static final int MAX_NTRIESPART = 50;
/**
- * Collapse a string of tokens into a single string without adding any
- * spaces.
+ * Collapse a string of tokens into a single string without adding any spaces.
*
* @param input
- * The list of tokens to collapse.
+ * The list of tokens to collapse.
*
* @return The collapsed string of tokens.
*/
public static String collapseTokens(final IList<String> 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, "");
}
@@ -40,14 +40,15 @@ public class ListUtils {
* separator after each token.
*
* @param input
- * The list of tokens to collapse.
+ * The list of tokens to collapse.
*
* @param seperator
- * The separator to use for separating tokens.
+ * The separator to use for separating tokens.
*
* @return The collapsed string of tokens.
*/
- public static String collapseTokens(final IList<String> input, final String seperator) {
+ public static String collapseTokens(final IList<String> input,
+ final String seperator) {
if (input == null) {
throw new NullPointerException("Input must not be null");
} else if (seperator == null) {
@@ -80,23 +81,23 @@ public class ListUtils {
* Select a number of random items from the list without replacement.
*
* @param <E>
- * The type of items to select.
+ * The type of items to select.
*
* @param list
- * The list to select from.
+ * The list to select from.
*
* @param number
- * The number of items to selet.
+ * The number of items to selet.
*
* @param rng
- * A function that creates a random number from 0 to the
- * desired number.
+ * A function that creates a random number from 0 to the desired
+ * number.
*
- * @return A new list containing the desired number of items randomly
- * selected from the specified list without replacement.
+ * @return A new list containing the desired number of items randomly selected
+ * from the specified list without replacement.
*/
- public static <E> IList<E> drawWithoutReplacement(final IList<E> list, final int number,
- final Function<Integer, Integer> rng) {
+ public static <E> IList<E> drawWithoutReplacement(final IList<E> list,
+ final int number, final Function<Integer, Integer> rng) {
final IList<E> selected = new FunctionalList<>(new ArrayList<>(number));
final int total = list.getSize();
@@ -124,20 +125,20 @@ public class ListUtils {
* Select a number of random items from the list, with replacement.
*
* @param <E>
- * The type of items to select.
+ * The type of items to select.
*
* @param list
- * The list to select from.
+ * The list to select from.
*
* @param number
- * The number of items to select.
+ * The number of items to select.
*
* @param rng
- * A function that creates a random number from 0 to the
- * desired number.
+ * A function that creates a random number from 0 to the desired
+ * number.
*
- * @return A new list containing the desired number of items randomly
- * selected from the specified list.
+ * @return A new list containing the desired number of items randomly selected
+ * from the specified list.
*/
public static <E> IList<E> drawWithReplacement(final IList<E> list, final int number,
final Function<Integer, Integer> rng) {
@@ -151,32 +152,33 @@ public class ListUtils {
}
/**
- * Partition a list into a list of lists, where each element can count
- * for more than one element in a partition.
+ * Partition a list into a list of lists, where each element can count for more
+ * than one element in a partition.
*
* @param <E>
- * The type of elements in the list to partition.
+ * The type of elements in the list to partition.
*
* @param input
- * The list to partition.
+ * The list to partition.
*
* @param counter
- * The function to determine the count for each element
- * for.
+ * The function to determine the count for each element
+ * for.
*
* @param partitionSize
- * The number of elements to put in each partition.
+ * The number of elements to put in each partition.
*
* @return A list partitioned according to the above rules.
*/
- public static <E> IList<IList<E>> groupPartition(final IList<E> input, final Function<E, Integer> counter,
- final int partitionSize) {
+ public static <E> IList<IList<E>> groupPartition(final IList<E> input,
+ final Function<E, Integer> counter, final int partitionSize) {
if (input == null) {
throw new NullPointerException("Input list must not be null");
} else if (counter == null) {
throw new NullPointerException("Counter must not be null");
} else if (partitionSize < 1 || partitionSize > input.getSize()) {
- final String fmt = "%d is not a valid partition size. Must be between 1 and %d";
+ final String fmt
+ = "%d is not a valid partition size. Must be between 1 and %d";
final String msg = String.format(fmt, partitionSize, input.getSize());
throw new IllegalArgumentException(msg);
@@ -188,11 +190,13 @@ public class ListUtils {
/* List that holds elements rejected during current pass. */
final IList<E> rejected = new FunctionalList<>();
- final GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter);
+ final GroupPartIteration<E> it
+ = new GroupPartIteration<>(returned, rejected, partitionSize, counter);
/* Run up to a certain number of passes. */
- for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART
- && !rejected.isEmpty(); numberOfIterations++) {
+ for (int numberOfIterations = 0;
+ numberOfIterations < MAX_NTRIESPART && !rejected.isEmpty();
+ numberOfIterations++) {
input.forEach(it);
if (rejected.isEmpty()) {
@@ -201,10 +205,11 @@ public class ListUtils {
}
}
- final String fmt = "Heuristic (more than %d iterations of partitioning) detected an unpartitionable list. (%s)\nThe following elements were not partitioned: %s\nCurrent group in formation: %s\nPreviously formed groups: %s\n";
+ final String fmt
+ = "Heuristic (more than %d iterations of partitioning) detected an unpartitionable list. (%s)\nThe following elements were not partitioned: %s\nCurrent group in formation: %s\nPreviously formed groups: %s\n";
- final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(), rejected.toString(),
- it.currentPartition.toString(), returned.toString());
+ final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(),
+ rejected.toString(), it.currentPartition.toString(), returned.toString());
throw new IllegalArgumentException(msg);
}
@@ -213,10 +218,10 @@ public class ListUtils {
* Merge the contents of a bunch of lists together into a single list.
*
* @param <E>
- * The type of value in this lists.
+ * The type of value in this lists.
*
* @param lists
- * The values in the lists to merge.
+ * The values in the lists to merge.
*
* @return A list containing all the elements of the lists.
*/
@@ -254,9 +259,11 @@ public class ListUtils {
* @return The list, padded to the desired size.
*
* @throws IllegalArgumentException
- * If the list couldn't be padded to the desired size.
+ * If the list couldn't be padded to the
+ * desired size.
*/
- public static <E> IList<E> padList(final IList<E> list, final Function<E, Integer> counter, final int size,
+ public static <E> IList<E> padList(final IList<E> list,
+ final Function<E, Integer> counter, final int size,
final Supplier<E> padder) {
int count = 0;
@@ -289,7 +296,8 @@ public class ListUtils {
}
if (threshold > MAX_NTRIESPART) {
- final String fmt = "Heuristic (more than %d iterations of attempting to pad) detected an unpaddable list. (%s)\nPartially padded list: %S";
+ final String fmt
+ = "Heuristic (more than %d iterations of attempting to pad) detected an unpaddable list. (%s)\nPartially padded list: %S";
final String msg = String.format(fmt, MAX_NTRIESPART, list.toString(),
returned.toString());
@@ -303,9 +311,9 @@ public class ListUtils {
/**
* Convert a list of longs into an array of longs.
- *
+ *
* @param list
- * The list to convert.
+ * The list to convert.
* @return The list as an array.
*/
public static long[] toPrimitive(List<Long> list) {
@@ -324,11 +332,10 @@ public class ListUtils {
/**
* Generate all of the permuations of a list.
*
- * This is a version of Algorith P (Plain Changes) from Knuth (vol 4A,
- * pg 322)
+ * This is a version of Algorith P (Plain Changes) from Knuth (vol 4A, pg 322)
*
* @param list
- * The list to generate permutations from.
+ * The list to generate permutations from.
* @return The list of permutations of the list.
*/
public static <T> List<List<T>> permuteList(List<T> list) {
@@ -396,7 +403,8 @@ public class ListUtils {
}
if (q == j) {
- if (j == 0) break;
+ if (j == 0)
+ break;
s += 1;
diff --git a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java
index c29fafe..a5a046a 100644
--- a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java
@@ -12,22 +12,22 @@ public class NumberUtils {
* Compute the falling factorial of a number.
*
* @param value
- * The number to compute.
+ * The number to compute.
*
* @param power
- * The power to do the falling factorial for.
+ * The power to do the falling factorial for.
*
* @return The falling factorial of the number to the power.
*/
public static int fallingFactorial(final int value, final int power) {
- if(power == 0) {
+ if (power == 0) {
return 1;
- } else if(power == 1) {
+ } else if (power == 1) {
return value;
} else {
int result = 1;
- for(int currentSub = 0; currentSub < power + 1; currentSub++) {
+ for (int currentSub = 0; currentSub < power + 1; currentSub++) {
result *= value - currentSub;
}
@@ -39,17 +39,18 @@ public class NumberUtils {
* Evaluates a linear probability distribution.
*
* @param winning
- * The number of winning possibilities.
+ * The number of winning possibilities.
*
* @param total
- * The number of total possibilities.
+ * The number of total possibilities.
*
* @param rng
- * The function to use to generate a random possibility.
+ * The function to use to generate a random possibility.
*
* @return Whether or not a random possibility was a winning one.
*/
- public static boolean isProbable(final int winning, final int total, final Function<Integer, Integer> rng) {
+ public static boolean isProbable(final int winning, final int total,
+ final Function<Integer, Integer> rng) {
return rng.apply(total) < winning;
}
@@ -57,13 +58,13 @@ public class NumberUtils {
* Check if a number is in an inclusive range.
*
* @param min
- * The minimum value of the range.
+ * The minimum value of the range.
*
* @param max
- * The maximum value of the range.
+ * The maximum value of the range.
*
* @param i
- * The number to check.
+ * The number to check.
*
* @return Whether the number is in the range.
*/
diff --git a/base/src/main/java/bjc/utils/funcutils/SetUtils.java b/base/src/main/java/bjc/utils/funcutils/SetUtils.java
index d57ac00..83c191b 100644
--- a/base/src/main/java/bjc/utils/funcutils/SetUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/SetUtils.java
@@ -7,17 +7,20 @@ import java.util.Set;
/**
* Various utility functions dealing with sets.
+ *
* @author bjculkin
*
*/
public class SetUtils {
/**
* Create a power-set (set of all subsets) of a given set.
- * @param originalSet The set to create a power-set of.
+ *
+ * @param originalSet
+ * The set to create a power-set of.
* @return The power-set of the set.
*/
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
- Set<Set<T>> sets = new HashSet<Set<T>>();
+ Set<Set<T>> sets = new HashSet<>();
// Special-case empty input
if (originalSet.isEmpty()) {
@@ -25,18 +28,18 @@ public class SetUtils {
return sets;
}
- List<T> list = new ArrayList<T>(originalSet);
+ List<T> list = new ArrayList<>(originalSet);
// Add original set to list.
T head = list.get(0);
// Trim leading element from set.
- Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
+ Set<T> rest = new HashSet<>(list.subList(1, list.size()));
Set<Set<T>> remSets = powerSet(rest);
-
+
for (Set<T> set : remSets) {
- Set<T> newSet = new HashSet<T>();
+ Set<T> newSet = new HashSet<>();
// Create a new set with the removed element.
newSet.add(head);
@@ -51,14 +54,16 @@ public class SetUtils {
/**
* Utility method for set construction.
- * @param elms The elements to stick in the set.
+ *
+ * @param elms
+ * The elements to stick in the set.
* @return A set containing the specified elements.
*/
@SafeVarargs
public static <T> Set<T> toSet(T... elms) {
Set<T> set = new HashSet<>();
- for(T elm : elms) {
+ for (T elm : elms) {
set.add(elm);
}
diff --git a/base/src/main/java/bjc/utils/funcutils/StringUtils.java b/base/src/main/java/bjc/utils/funcutils/StringUtils.java
index 88c418f..b7a6835 100644
--- a/base/src/main/java/bjc/utils/funcutils/StringUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/StringUtils.java
@@ -26,27 +26,26 @@ public class StringUtils {
* expression.
*
* @param input
- * The string to check.
+ * The string to check.
*
* @param rRegex
- * The regex to see if the string only contains matches
- * of.
+ * The regex to see if the string only contains matches of.
*
- * @return Whether or not the string consists only of multiple matches
- * of the provided regex.
+ * @return Whether or not the string consists only of multiple matches of the
+ * provided regex.
*/
public static boolean containsOnly(final String input, final String rRegex) {
if (input == null)
throw new NullPointerException("Input must not be null");
- else if (rRegex == null) throw new NullPointerException("Regex must not be null");
+ else if (rRegex == null)
+ throw new NullPointerException("Regex must not be null");
/*
* This regular expression is fairly simple.
*
- * First, we match the beginning of the string. Then, we start a
- * non-capturing group whose contents are the passed in regex.
- * That group is then matched one or more times and the pattern
- * matches to the end of the string.
+ * First, we match the beginning of the string. Then, we start a non-capturing
+ * group whose contents are the passed in regex. That group is then matched one
+ * or more times and the pattern matches to the end of the string.
*/
return input.matches("\\A(?:" + rRegex + ")+\\Z");
}
@@ -67,17 +66,15 @@ public class StringUtils {
}
/**
- * Print out a deque with a special case for easily showing a deque is
- * empty.
+ * Print out a deque with a special case for easily showing a deque is empty.
*
* @param <ContainedType>
- * The type in the deque.
+ * The type in the deque.
*
* @param queue
- * The deque to print.
+ * The deque to print.
*
- * @return A string version of the deque, with allowance for an empty
- * deque.
+ * @return A string version of the deque, with allowance for an empty deque.
*/
public static <ContainedType> String printDeque(final Deque<ContainedType> queue) {
return queue.isEmpty() ? "(none)" : queue.toString();
@@ -90,16 +87,18 @@ public class StringUtils {
* The sequence to convert to an English list.
*
* @param join
- * The string to use for separating the last element from
- * the rest.
+ * The string to use for separating the last element from the
+ * rest.
*
* @param comma
* The string to use as a comma
*
* @return The sequence as an English list.
*/
- public static String toEnglishList(final Object[] objects, final String join, final String comma) {
- if (objects == null) throw new NullPointerException("Sequence must not be null");
+ public static String toEnglishList(final Object[] objects, final String join,
+ final String comma) {
+ if (objects == null)
+ throw new NullPointerException("Sequence must not be null");
final StringBuilder sb = new StringBuilder();
@@ -107,35 +106,35 @@ public class StringUtils {
final String coma = comma;
switch (objects.length) {
- case 0:
- /* Empty list. */
- break;
- case 1:
- /* One item. */
- sb.append(objects[0].toString());
- break;
- case 2:
- /* Two items. */
- sb.append(objects[0].toString());
- sb.append(" " + joiner + " ");
- sb.append(objects[1].toString());
- break;
- default:
- /* Three or more items. */
- for (int i = 0; i < objects.length - 1; i++) {
- sb.append(objects[i].toString());
- sb.append(coma + " ");
- }
+ case 0:
+ /* Empty list. */
+ break;
+ case 1:
+ /* One item. */
+ sb.append(objects[0].toString());
+ break;
+ case 2:
+ /* Two items. */
+ sb.append(objects[0].toString());
+ sb.append(" " + joiner + " ");
+ sb.append(objects[1].toString());
+ break;
+ default:
+ /* Three or more items. */
+ for (int i = 0; i < objects.length - 1; i++) {
+ sb.append(objects[i].toString());
+ sb.append(coma + " ");
+ }
- /*
- * Uncomment this to remove serial commas.
- *
- * int lc = sb.length() - 1;
- *
- * sb.delete(lc - coma.length(), lc);
- */
- sb.append(joiner + " ");
- sb.append(objects[objects.length - 1].toString());
+ /*
+ * Uncomment this to remove serial commas.
+ *
+ * int lc = sb.length() - 1;
+ *
+ * sb.delete(lc - coma.length(), lc);
+ */
+ sb.append(joiner + " ");
+ sb.append(objects[objects.length - 1].toString());
}
return sb.toString();
@@ -148,8 +147,8 @@ public class StringUtils {
* The sequence to convert to an English list.
*
* @param join
- * The string to use for separating the last element from
- * the rest.
+ * The string to use for separating the last element from the
+ * rest.
*
* @return The sequence as an English list.
*/
@@ -169,7 +168,9 @@ public class StringUtils {
* @return The sequence as an English list.
*/
public static String toEnglishList(final Object[] objects, final boolean and) {
- if (and) { return toEnglishList(objects, "and"); }
+ if (and) {
+ return toEnglishList(objects, "and");
+ }
return toEnglishList(objects, "or");
}
@@ -178,7 +179,7 @@ public class StringUtils {
* Count the number of graphemes in a string.
*
* @param value
- * The string to check.
+ * The string to check.
*
* @return The number of graphemes in the string.
*/
@@ -216,12 +217,12 @@ public class StringUtils {
/**
* Get a substring until a specified string.
- *
+ *
* @param strang
- * The string to substring.
+ * The string to substring.
* @param vx
- * The place to substring until.
- *
+ * The place to substring until.
+ *
* @return The specified substring.
*/
public static String substringTo(String strang, String vx) {
@@ -230,22 +231,23 @@ public class StringUtils {
/**
* Get a substring until a specified string.
- *
+ *
* @param strang
- * The string to substring.
+ * The string to substring.
* @param vx
- * The place to substring until.
+ * The place to substring until.
* @param allowFail
- * Whether or not to allow failure.
- *
- * @return The specified substring, or null if the specified place to
- * substring to was not found, and we were not allowed to fail.
+ * Whether or not to allow failure.
+ *
+ * @return The specified substring, or null if the specified place to substring
+ * to was not found, and we were not allowed to fail.
*/
public static String substringTo(String strang, String vx, boolean allowFail) {
int idx = strang.indexOf(vx);
if (idx == -1) {
- if (allowFail) return strang;
+ if (allowFail)
+ return strang;
return null;
}
@@ -254,11 +256,11 @@ public class StringUtils {
}
/**
- * Split a line into a series of space-separated arguments, including
- * string literals.
- *
+ * Split a line into a series of space-separated arguments, including string
+ * literals.
+ *
* @param com
- * The command to split from
+ * The command to split from
* @return The split arguments.
*/
public static List<String> processArguments(String com) {
@@ -283,7 +285,7 @@ public class StringUtils {
private Scanner scn;
public boolean processComments;
- public String commentInd;
+ public String commentInd;
public boolean skipBlanks;
@@ -304,13 +306,16 @@ public class StringUtils {
boolean doLoop = true;
do {
- if (!scn.hasNextLine()) break;
+ if (!scn.hasNextLine())
+ break;
tmp = scn.nextLine().trim();
// Skip blank lines
- if (skipBlanks && tmp.equals("")) continue;
- if (processComments && tmp.startsWith(commentInd)) continue;
+ if (skipBlanks && tmp.equals(""))
+ continue;
+ if (processComments && tmp.startsWith(commentInd))
+ continue;
doLoop = tmp.endsWith("\\") && !tmp.endsWith("\\\\");
@@ -329,7 +334,7 @@ public class StringUtils {
* Read a series of lines from an input source.
*
* @param scn
- * The source to read the lines from.
+ * The source to read the lines from.
*
* @return An iterator over the lines from the input source.
*/
@@ -341,24 +346,25 @@ public class StringUtils {
* Read a series of lines from an input source.
*
* @param scn
- * The source to read the lines from.
+ * The source to read the lines from.
*
* @param processComments
- * Whether or not to skip comment lines.
+ * Whether or not to skip comment lines.
*
* @param commentInd
- * Indicator for starting comment lines.
+ * Indicator for starting comment lines.
*
* @param skipBlanks
- * Whether or not to skip blank lines.
+ * Whether or not to skip blank lines.
*
* @return An iterator over the lines from the input source.
*/
- public static Iterator<String> readLines(Scanner scn, boolean processComments, String commentInd, boolean skipBlanks) {
+ public static Iterator<String> readLines(Scanner scn, boolean processComments,
+ String commentInd, boolean skipBlanks) {
LineIterator itr = new LineIterator(scn);
itr.processComments = processComments;
- itr.commentInd = commentInd;
+ itr.commentInd = commentInd;
itr.skipBlanks = skipBlanks;
@@ -368,13 +374,12 @@ public class StringUtils {
/**
* Check if a string contains any one of a specified number of things,
* respecting groups.
- *
+ *
* @param haystack
- * The string to look in.
+ * The string to look in.
* @param needles
- * The strings to look for.
- * @return Whether or not any of the strings were contained outside of
- * groups.
+ * The strings to look for.
+ * @return Whether or not any of the strings were contained outside of groups.
*/
public static boolean levelContains(String haystack, String... needles) {
return LevelSplitter.def.levelContains(haystack, needles);
@@ -382,13 +387,13 @@ public class StringUtils {
/**
* Split a string, respecting groups.
- *
+ *
* @param phrase
- * The string to split.
+ * The string to split.
* @param splits
- * The strings to split on.
- * @return A list of split strings. If keepDelims is true, it also
- * includes the delimiters in between the split strings.
+ * The strings to split on.
+ * @return A list of split strings. If keepDelims is true, it also includes the
+ * delimiters in between the split strings.
*/
public static List<String> levelSplit(String phrase, String... splits) {
return LevelSplitter.def.levelSplit(phrase, false, splits);
@@ -396,18 +401,18 @@ public class StringUtils {
/**
* Split a string, respecting groups.
- *
+ *
* @param phrase
- * The string to split.
+ * The string to split.
* @param keepDelims
- * Whether or not to include the delimiters in the
- * results.
+ * Whether or not to include the delimiters in the results.
* @param splits
- * The strings to split on.
- * @return A list of split strings. If keepDelims is true, it also
- * includes the delimiters in between the split strings.
+ * The strings to split on.
+ * @return A list of split strings. If keepDelims is true, it also includes the
+ * delimiters in between the split strings.
*/
- public static List<String> levelSplit(String phrase, boolean keepDelims, String... splits) {
+ public static List<String> levelSplit(String phrase, boolean keepDelims,
+ String... splits) {
return LevelSplitter.def.levelSplit(phrase, keepDelims, splits);
}
}
diff --git a/base/src/main/java/bjc/utils/funcutils/TestUtils.java b/base/src/main/java/bjc/utils/funcutils/TestUtils.java
index c037ec4..3aa20a2 100644
--- a/base/src/main/java/bjc/utils/funcutils/TestUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/TestUtils.java
@@ -7,18 +7,18 @@ import java.util.List;
/**
* Utilities for testing.
- *
+ *
* @author bjculkin
*
*/
public class TestUtils {
/**
* Assert an iterator provides a particular sequence of values.
- *
+ *
* @param src
- * The iterator to pull values from.
+ * The iterator to pull values from.
* @param vals
- * The values to expect from the iterator.
+ * The values to expect from the iterator.
*/
@SafeVarargs
public static <T> void assertIteratorEquals(Iterator<T> src, T... vals) {
@@ -29,7 +29,7 @@ public class TestUtils {
/**
* Assert an iterator provides a particular sequence of values.
- *
+ *
* @param src
* The iterator to pull values from.
* @param hasMore
@@ -38,14 +38,14 @@ public class TestUtils {
* The values to expect from the iterator.
*/
@SafeVarargs
- public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, T... vals) {
+ public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src,
+ T... vals) {
/*
* @NOTE
- *
- * Even though it's awkward, the boolean has to come first.
- * Otherwise, there are cases where the compiler will get
- * confused as to what the right value for T is, and be unable
- * to pick an overload.
+ *
+ * Even though it's awkward, the boolean has to come first. Otherwise, there are
+ * cases where the compiler will get confused as to what the right value for T
+ * is, and be unable to pick an overload.
*/
assertIteratorEquals(src, vals);
@@ -54,12 +54,12 @@ public class TestUtils {
/**
* Assert that a list has a given set of contents.
- *
- * @param src
- * The list of actual elements.
- *
+ *
+ * @param src
+ * The list of actual elements.
+ *
* @param exps
- * The list of expected elements.
+ * The list of expected elements.
*/
@SafeVarargs
public static <T> void assertListEquals(List<T> src, T... exps) {
diff --git a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java
index bbb9153..d525773 100644
--- a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java
+++ b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java
@@ -14,13 +14,12 @@ import bjc.funcdata.IList;
*/
public class TreeUtils {
/**
- * Convert a tree into a list of outline nodes that match a certain
- * path.
- *
+ * Convert a tree into a list of outline nodes that match a certain path.
+ *
* @param tre
- * The tree to outline.
+ * The tree to outline.
* @param leafMarker
- * The path to mark nodes with.
+ * The path to mark nodes with.
* @return The list of marked paths.
*/
public static <T> IList<IList<T>> outlineTree(ITree<T> tre, Predicate<T> leafMarker) {
@@ -29,19 +28,19 @@ public class TreeUtils {
LinkedList<T> path = new LinkedList<>();
path.add(tre.getHead());
- tre.doForChildren((child) -> findPath(child, path, leafMarker, paths));
+ tre.doForChildren(child -> findPath(child, path, leafMarker, paths));
return paths;
}
/* Find a path in a tree. */
- private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, Predicate<T> leafMarker,
- IList<IList<T>> paths) {
- if(subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) {
+ private static <T> void findPath(ITree<T> subtree, LinkedList<T> path,
+ Predicate<T> leafMarker, IList<IList<T>> paths) {
+ if (subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) {
/* We're at a matching leaf node. Add it. */
IList<T> finalPath = new FunctionalList<>();
- for(T ePath : path) {
+ for (T ePath : path) {
finalPath.add(ePath);
}
@@ -52,7 +51,7 @@ public class TreeUtils {
/* Check the children of this node. */
path.add(subtree.getHead());
- subtree.doForChildren((child) -> findPath(child, path, leafMarker, paths));
+ subtree.doForChildren(child -> findPath(child, path, leafMarker, paths));
path.removeLast();
}
diff --git a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java
index 7b15097..8a0832c 100644
--- a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java
+++ b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java
@@ -6,13 +6,13 @@ package bjc.utils.funcutils;
* @author EVE
*
* @param <A>
- * Type of the first argument.
+ * Type of the first argument.
*
* @param <B>
- * Type of the second argument.
+ * Type of the second argument.
*
* @param <C>
- * Type of the third argument.
+ * Type of the third argument.
*/
@FunctionalInterface
public interface TriConsumer<A, B, C> {
@@ -20,13 +20,13 @@ public interface TriConsumer<A, B, C> {
* Perform the action.
*
* @param a
- * The first parameter.
+ * The first parameter.
*
* @param b
- * The second parameter.
+ * The second parameter.
*
* @param c
- * The third parameter.
+ * The third parameter.
*/
public void accept(A a, B b, C c);
}
diff --git a/base/src/main/java/bjc/utils/gen/RandomGrammar.java b/base/src/main/java/bjc/utils/gen/RandomGrammar.java
index d0a71c5..050165b 100644
--- a/base/src/main/java/bjc/utils/gen/RandomGrammar.java
+++ b/base/src/main/java/bjc/utils/gen/RandomGrammar.java
@@ -9,7 +9,7 @@ import bjc.funcdata.IList;
* @author ben
*
* @param <E>
- * The type of grammar elements to use.
+ * The type of grammar elements to use.
*/
public class RandomGrammar<E> extends WeightedGrammar<E> {
/** Create a new random grammar. */
@@ -21,14 +21,14 @@ public class RandomGrammar<E> extends WeightedGrammar<E> {
* Add cases to a specified rule.
*
* @param rule
- * The name of the rule to add cases to.
+ * The name of the rule to add cases to.
*
* @param cases
- * The cases to add for this rule.
+ * The cases to add for this rule.
*/
@SafeVarargs
public final void addCases(final E rule, final IList<E>... cases) {
- for(final IList<E> currentCase : cases) {
+ for (final IList<E> currentCase : cases) {
super.addCase(rule, 1, currentCase);
}
}
@@ -37,16 +37,16 @@ public class RandomGrammar<E> extends WeightedGrammar<E> {
* Create a rule with the specified name and cases.
*
* @param rule
- * The name of the rule to add.
+ * The name of the rule to add.
*
* @param cases
- * The cases to add for this rule.
+ * The cases to add for this rule.
*/
@SafeVarargs
public final void makeRule(final E rule, final IList<E>... cases) {
super.addRule(rule);
- for(final IList<E> currentCase : cases) {
+ for (final IList<E> currentCase : cases) {
super.addCase(rule, 1, currentCase);
}
}
@@ -55,13 +55,14 @@ public class RandomGrammar<E> extends WeightedGrammar<E> {
* Create a rule with the specified name and cases.
*
* @param rule
- * The name of the rule to add.
+ * The name of the rule to add.
*
* @param cases
- * The cases to add for this rule.
+ * The cases to add for this rule.
*/
public void makeRule(final E rule, final IList<IList<E>> 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/base/src/main/java/bjc/utils/gen/WeightedGrammar.java b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java
index 774d694..324a80c 100644
--- a/base/src/main/java/bjc/utils/gen/WeightedGrammar.java
+++ b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java
@@ -19,7 +19,7 @@ import bjc.funcdata.IMap;
* @author ben
*
* @param <E>
- * The values that make up sentences of this grammar.
+ * The values that make up sentences of this grammar.
*/
public class WeightedGrammar<E> {
/** The initial rule of the grammar */
@@ -51,16 +51,16 @@ public class WeightedGrammar<E> {
}
/**
- * Create a new weighted grammar that uses the specified source of
- * randomness.
+ * Create a new weighted grammar that uses the specified source of randomness.
*
* @param source
- * The source of randomness to use
+ * The source of randomness to use
*/
public WeightedGrammar(final 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;
}
@@ -69,10 +69,10 @@ public class WeightedGrammar<E> {
* Configure the action to perform on special tokens.
*
* @param marker
- * The marker to find special tokens.
+ * The marker to find special tokens.
*
* @param action
- * The action to take on those tokens.
+ * The action to take on those tokens.
*/
public void configureSpecial(final Predicate<E> marker,
final BiFunction<E, WeightedGrammar<E>, IList<E>> action) {
@@ -84,15 +84,15 @@ public class WeightedGrammar<E> {
* Adds a special rule to the grammar.
*
* @param ruleName
- * The name of the special rule.
+ * The name of the special rule.
*
* @param cse
- * The case for the rule.
+ * The case for the rule.
*/
public void addSpecialRule(final E ruleName, final Supplier<IList<E>> cse) {
- if(ruleName == null) {
+ if (ruleName == null) {
throw new NullPointerException("Rule name must not be null");
- } else if(cse == null) {
+ } else if (cse == null) {
throw new NullPointerException("Case must not be null");
}
@@ -103,18 +103,18 @@ public class WeightedGrammar<E> {
* Add a case to an already existing rule.
*
* @param ruleName
- * The rule to add a case to.
+ * The rule to add a case to.
*
* @param probability
- * The probability for this rule to be chosen.
+ * The probability for this rule to be chosen.
*
* @param cse
- * The case being added.
+ * The case being added.
*/
public void addCase(final E ruleName, final int probability, final IList<E> cse) {
- if(ruleName == null) {
+ if (ruleName == null) {
throw new NullPointerException("Rule name must be not null");
- } else if(cse == null) {
+ } else if (cse == null) {
throw new NullPointerException("Case body must not be null");
}
@@ -125,23 +125,24 @@ public class WeightedGrammar<E> {
* Add a alias for an existing subgrammar.
*
* @param name
- * The name of the subgrammar to alias.
+ * The name of the subgrammar to alias.
*
* @param alias
- * The alias of the subgrammar.
+ * The alias of the subgrammar.
*
* @return Whether the alias was succesfully created.
*/
public boolean addGrammarAlias(final E name, final E alias) {
- if(name == null) {
+ if (name == null) {
throw new NullPointerException("Subgrammar name must not be null");
- } else if(alias == 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;
}
@@ -153,16 +154,17 @@ public class WeightedGrammar<E> {
* Add a new rule with no cases.
*
* @param name
- * The name of the rule to add.
+ * The name of the rule to add.
*
* @return Whether or not the rule was successfully added.
*/
public boolean addRule(final 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));
}
@@ -171,21 +173,22 @@ public class WeightedGrammar<E> {
* Add a new rule with a set of cases.
*
* @param name
- * The name of the rule to add.
+ * The name of the rule to add.
*
* @param cases
- * The set of cases for the rule.
+ * The set of cases for the rule.
*
* @return Whether or not the rule was succesfully added.
*/
public boolean addRule(final E name, final WeightedRandom<IList<E>> cases) {
- if(name == null) {
+ if (name == null) {
throw new NullPointerException("Name must not be null");
- } else if(cases == 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;
@@ -195,21 +198,22 @@ public class WeightedGrammar<E> {
* Add a subgrammar.
*
* @param name
- * The name of the subgrammar.
+ * The name of the subgrammar.
*
* @param subgrammar
- * The subgrammar to add.
+ * The subgrammar to add.
*
* @return Whether or not the subgrammar was succesfully added.
*/
public boolean addSubgrammar(final E name, final WeightedGrammar<E> subgrammar) {
- if(name == null) {
+ if (name == null) {
throw new NullPointerException("Subgrammar name must not be null");
- } else if(subgrammar == 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;
@@ -219,10 +223,11 @@ public class WeightedGrammar<E> {
* Remove a rule with the specified name.
*
* @param name
- * The name of the rule to remove.
+ * The name of the rule to remove.
*/
public void deleteRule(final 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);
}
@@ -231,10 +236,11 @@ public class WeightedGrammar<E> {
* Remove a subgrammar with the specified name.
*
* @param name
- * The name of the subgrammar to remove.
+ * The name of the subgrammar to remove.
*/
public void deleteSubgrammar(final 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);
}
@@ -245,18 +251,19 @@ public class WeightedGrammar<E> {
* Only generates sentences one layer deep.
*
* @param ruleName
- * The rule to test.
+ * The rule to test.
*
* @return A set of sentences generated by the specified rule.
*/
public IList<IList<E>> generateDebugValues(final 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");
final IList<IList<E>> returnedList = new FunctionalList<>();
final WeightedRandom<IList<E>> ruleGenerator = rules.get(ruleName);
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
returnedList.add(ruleGenerator.generateValue());
}
@@ -267,27 +274,27 @@ public class WeightedGrammar<E> {
* Generate a generic sentence from a initial rule.
*
* @param <T>
- * The type of the transformed output
+ * The type of the transformed output
*
* @param initRules
- * The initial rule to start with.
+ * The initial rule to start with.
*
* @param tokenTransformer
- * The function to transform grammar output into something.
+ * The function to transform grammar output into
+ * something.
*
* @param spacer
- * The spacer element to add in between output tokens.
+ * The spacer element to add in between output tokens.
*
- * @return A randomly generated sentence from the specified initial
- * rule.
+ * @return A randomly generated sentence from the specified initial rule.
*/
- public <T> IList<T> generateGenericValues(final E initRules, final Function<E, T> tokenTransformer,
- final T spacer) {
- if(initRules == null) {
+ public <T> IList<T> generateGenericValues(final E initRules,
+ final Function<E, T> tokenTransformer, final T spacer) {
+ if (initRules == null) {
throw new NullPointerException("Initial rule must not be null");
- } else if(tokenTransformer == null) {
+ } else if (tokenTransformer == null) {
throw new NullPointerException("Transformer must not be null");
- } else if(spacer == null) {
+ } else if (spacer == null) {
throw new NullPointerException("Spacer must not be null");
}
@@ -295,8 +302,8 @@ public class WeightedGrammar<E> {
IList<E> genRules = new FunctionalList<>(initRules);
- if(specialMarker != null) {
- if(specialMarker.test(initRules)) {
+ if (specialMarker != null) {
+ if (specialMarker.test(initRules)) {
genRules = specialAction.apply(initRules, this);
}
}
@@ -304,33 +311,37 @@ public class WeightedGrammar<E> {
/*
* @NOTE Can this loop be simplified in some way?
*/
- for(final E initRule : genRules.toIterable()) {
- if(specialRules.containsKey(initRule)) {
- for(final E rulePart : specialRules.get(initRule).get().toIterable()) {
- final Iterable<T> generatedRuleParts = generateGenericValues(rulePart,
- tokenTransformer, spacer).toIterable();
-
- for(final T generatedRulePart : generatedRuleParts) {
+ for (final E initRule : genRules.toIterable()) {
+ if (specialRules.containsKey(initRule)) {
+ for (final E rulePart : specialRules.get(initRule).get().toIterable()) {
+ final Iterable<T> generatedRuleParts
+ = generateGenericValues(rulePart, tokenTransformer, spacer)
+ .toIterable();
+
+ for (final T generatedRulePart : generatedRuleParts) {
returnedList.add(generatedRulePart);
returnedList.add(spacer);
}
}
- } else if(subgrammars.containsKey(initRule)) {
+ } else if (subgrammars.containsKey(initRule)) {
final Iterable<T> ruleParts = subgrammars.get(initRule)
- .generateGenericValues(initRule, tokenTransformer, spacer).toIterable();
+ .generateGenericValues(initRule, tokenTransformer, spacer)
+ .toIterable();
- for(final T rulePart : ruleParts) {
+ for (final T rulePart : ruleParts) {
returnedList.add(rulePart);
returnedList.add(spacer);
}
- } else if(rules.containsKey(initRule)) {
- final Iterable<E> ruleParts = rules.get(initRule).generateValue().toIterable();
+ } else if (rules.containsKey(initRule)) {
+ final Iterable<E> ruleParts
+ = rules.get(initRule).generateValue().toIterable();
- for(final E rulePart : ruleParts) {
- final Iterable<T> generatedRuleParts = generateGenericValues(rulePart,
- tokenTransformer, spacer).toIterable();
+ for (final E rulePart : ruleParts) {
+ final Iterable<T> generatedRuleParts
+ = generateGenericValues(rulePart, tokenTransformer, spacer)
+ .toIterable();
- for(final T generatedRulePart : generatedRuleParts) {
+ for (final T generatedRulePart : generatedRuleParts) {
returnedList.add(generatedRulePart);
returnedList.add(spacer);
}
@@ -338,7 +349,7 @@ public class WeightedGrammar<E> {
} else {
final T transformedToken = tokenTransformer.apply(initRule);
- if(transformedToken == null)
+ if (transformedToken == null)
throw new NullPointerException("Transformer created null token");
returnedList.add(transformedToken);
@@ -353,16 +364,16 @@ public class WeightedGrammar<E> {
* Generate a random list of grammar elements from a given initial rule.
*
* @param initRule
- * The initial rule to start with.
+ * The initial rule to start with.
*
* @param spacer
- * The item to use to space the list.
+ * The item to use to space the list.
*
- * @return A list of random grammar elements generated by the specified
- * rule.
+ * @return A list of random grammar elements generated by the specified rule.
*/
public IList<E> generateListValues(final E initRule, final E spacer) {
- final IList<E> retList = generateGenericValues(initRule, strang -> strang, spacer);
+ final IList<E> retList
+ = generateGenericValues(initRule, strang -> strang, spacer);
return retList;
}
@@ -403,12 +414,13 @@ public class WeightedGrammar<E> {
* Get the subgrammar with the specified name.
*
* @param name
- * The name of the subgrammar to get.
+ * The name of the subgrammar to get.
*
* @return The subgrammar with the specified name.
*/
public WeightedGrammar<E> getSubgrammar(final 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);
}
@@ -426,7 +438,7 @@ public class WeightedGrammar<E> {
* Check if this grammar has a given rule.
*
* @param ruleName
- * The rule to check for.
+ * The rule to check for.
*
* @return Whether or not the grammar has a rule by that name.
*/
@@ -438,25 +450,26 @@ public class WeightedGrammar<E> {
* Prefix a given rule with a token multiple times.
*
* @param ruleName
- * The name of the rule to prefix.
+ * The name of the rule to prefix.
*
* @param prefixToken
- * The token to prefix to the rules.
+ * The token to prefix to the rules.
*
* @param additionalProbability
- * The additional probability of the tokens.
+ * The additional probability of the tokens.
*
* @param numberOfTimes
- * The number of times to prefix the token.
+ * The number of times to prefix the token.
*/
- public void multiPrefixRule(final E ruleName, final E prefixToken, final int additionalProbability,
- final int numberOfTimes) {
- if(ruleName == null)
+ public void multiPrefixRule(final E ruleName, final E prefixToken,
+ final int additionalProbability, final int numberOfTimes) {
+ if (ruleName == null)
throw new NullPointerException("Rule name must not be null");
- else if(prefixToken == null)
+ else if (prefixToken == null)
throw new NullPointerException("Prefix token must not be null");
- else if(numberOfTimes < 1)
- throw new IllegalArgumentException("Number of times to prefix must be positive.");
+ else if (numberOfTimes < 1)
+ throw new IllegalArgumentException(
+ "Number of times to prefix must be positive.");
final WeightedRandom<IList<E>> rule = rules.get(ruleName);
@@ -465,21 +478,21 @@ public class WeightedGrammar<E> {
/*
* @NOTE Can this be simplified?
*/
- rule.getValues().forEach((pair) -> {
+ rule.getValues().forEach(pair -> {
final IList<IList<E>> newRule = new FunctionalList<>();
- for(int i = 1; i <= numberOfTimes; i++) {
+ for (int i = 1; i <= numberOfTimes; i++) {
final IList<E> newCase = pair.merge((left, right) -> {
final IList<E> returnVal = new FunctionalList<>();
- for(final E val : right.toIterable()) {
+ for (final 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);
}
@@ -493,7 +506,7 @@ public class WeightedGrammar<E> {
});
});
- newResults.forEach((pair) -> {
+ newResults.forEach(pair -> {
pair.doWith((left, right) -> {
addCase(ruleName, left, right);
});
@@ -501,22 +514,23 @@ public class WeightedGrammar<E> {
}
/**
- * Create a series of alternatives for a rule by prefixing them with a
- * given token.
+ * Create a series of alternatives for a rule by prefixing them with a given
+ * token.
*
* @param additionalProbability
- * The amount to adjust the probability by.
+ * The amount to adjust the probability by.
*
* @param ruleName
- * The name of the rule to prefix.
+ * The name of the rule to prefix.
*
* @param prefixToken
- * The token to prefix to the rule.
+ * The token to prefix to the rule.
*/
- public void prefixRule(final E ruleName, final E prefixToken, final int additionalProbability) {
- if(ruleName == null) {
+ public void prefixRule(final E ruleName, final E prefixToken,
+ final int additionalProbability) {
+ if (ruleName == null) {
throw new NullPointerException("Rule name must not be null");
- } else if(prefixToken == null) {
+ } else if (prefixToken == null) {
throw new NullPointerException("Prefix token must not be null");
}
@@ -524,11 +538,11 @@ public class WeightedGrammar<E> {
final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>();
- rule.getValues().forEach((pair) -> {
+ rule.getValues().forEach(pair -> {
final IList<E> newCase = pair.merge((left, right) -> {
final IList<E> returnVal = new FunctionalList<>();
- for(final E val : right.toIterable()) {
+ for (final E val : right.toIterable()) {
returnVal.add(val);
}
@@ -537,17 +551,19 @@ public class WeightedGrammar<E> {
newCase.prepend(prefixToken);
- newResults.add(new Pair<>(pair.merge((left, right) -> left) + additionalProbability, newCase));
+ newResults.add(new Pair<>(
+ pair.merge((left, right) -> left) + additionalProbability, newCase));
});
- newResults.forEach((pair) -> pair.doWith((left, right) -> addCase(ruleName, left, right)));
+ newResults.forEach(
+ pair -> pair.doWith((left, right) -> addCase(ruleName, left, right)));
}
/**
* Set the initial rule of the grammar.
*
* @param initRule
- * The initial rule of this grammar.
+ * The initial rule of this grammar.
*/
public void setInitialRule(final String initRule) {
this.initialRule = initRule;
@@ -557,18 +573,19 @@ public class WeightedGrammar<E> {
* Suffix a token to a rule.
*
* @param ruleName
- * The rule to suffix.
+ * The rule to suffix.
*
* @param suffixToken
- * The token to prefix to the rule.
+ * The token to prefix to the rule.
*
* @param additionalProbability
- * Additional probability of the prefixed rule.
+ * Additional probability of the prefixed rule.
*/
- public void suffixRule(final E ruleName, final E suffixToken, final int additionalProbability) {
- if(ruleName == null) {
+ public void suffixRule(final E ruleName, final E suffixToken,
+ final int additionalProbability) {
+ if (ruleName == null) {
throw new NullPointerException("Rule name must not be null");
- } else if(suffixToken == null) {
+ } else if (suffixToken == null) {
throw new NullPointerException("Prefix token must not be null");
}
@@ -576,11 +593,11 @@ public class WeightedGrammar<E> {
final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>();
- rule.getValues().forEach((par) -> {
+ rule.getValues().forEach(par -> {
final IList<E> newCase = par.merge((left, right) -> {
final IList<E> returnVal = new FunctionalList<>();
- for(final E val : right.toIterable()) {
+ for (final E val : right.toIterable()) {
returnVal.add(val);
}
@@ -589,9 +606,11 @@ public class WeightedGrammar<E> {
newCase.add(suffixToken);
- newResults.add(new Pair<>(par.merge((left, right) -> left) + additionalProbability, newCase));
+ newResults.add(new Pair<>(
+ par.merge((left, right) -> left) + additionalProbability, newCase));
});
- newResults.forEach((pair) -> pair.doWith((left, right) -> addCase(ruleName, left, right)));
+ newResults.forEach(
+ pair -> pair.doWith((left, right) -> addCase(ruleName, left, right)));
}
}
diff --git a/base/src/main/java/bjc/utils/gen/WeightedRandom.java b/base/src/main/java/bjc/utils/gen/WeightedRandom.java
index 15f5821..b17017b 100644
--- a/base/src/main/java/bjc/utils/gen/WeightedRandom.java
+++ b/base/src/main/java/bjc/utils/gen/WeightedRandom.java
@@ -14,7 +14,7 @@ import bjc.funcdata.IList;
* @author ben
*
* @param <E>
- * The type of values that are randomly selected.
+ * The type of values that are randomly selected.
*/
public class WeightedRandom<E> {
private final IList<IPair<Integer, E>> values;
@@ -33,12 +33,13 @@ public class WeightedRandom<E> {
* randomness.
*
* @param src
- * The source of randomness to use.
+ * The source of randomness to use.
*/
public WeightedRandom(Random src) {
values = 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;
}
@@ -62,10 +63,10 @@ public class WeightedRandom<E> {
* Add a probability for a specific result to be given.
*
* @param chance
- * The chance to get this result.
+ * The chance to get this result.
*
* @param result
- * The result to get when the chance comes up.
+ * The result to get when the chance comes up.
*/
public void addProbability(final int chance, final E result) {
values.add(new Pair<>(chance, result));
@@ -84,9 +85,9 @@ public class WeightedRandom<E> {
/**
* Generate a random value, using the specified Random.
- *
+ *
* @param rn
- * The Random instance to use.
+ * The Random instance to use.
* @return A random value.
*/
public E generateValue(Random rn) {
@@ -130,13 +131,12 @@ public class WeightedRandom<E> {
/**
* Get a descending value.
- *
- * Descending values are quite simple. You have a 1 in factor chance to
- * advance to the next value, otherwise, the current value is the one
- * returned.
- *
+ *
+ * Descending values are quite simple. You have a 1 in factor chance to advance
+ * to the next value, otherwise, the current value is the one returned.
+ *
* @param factor
- * The descent factor to use.
+ * The descent factor to use.
* @return A random value.
*/
public E getDescent(int factor) {
@@ -145,22 +145,23 @@ public class WeightedRandom<E> {
/**
* Get a descending value.
- *
- * Descending values are quite simple. You have a 1 in factor chance to
- * advance to the next value, otherwise, the current value is the one
- * returned.
- *
+ *
+ * Descending values are quite simple. You have a 1 in factor chance to advance
+ * to the next value, otherwise, the current value is the one returned.
+ *
* @param factor
- * The descent factor to use.
+ * The descent factor to use.
* @param rn
- * The Random instance to use.
+ * The Random instance to use.
* @return A random value.
*/
public E getDescent(int factor, Random rn) {
- if (values.getSize() == 0) return null;
+ if (values.getSize() == 0)
+ return null;
for (IPair<Integer, E> val : values) {
- if (rn.nextInt(factor) == 0) continue;
+ if (rn.nextInt(factor) == 0)
+ continue;
if (exhaust) {
totalChance -= val.getLeft();
@@ -172,25 +173,25 @@ public class WeightedRandom<E> {
}
IPair<Integer, E> val = values.getByIndex(values.getSize() - 1);
- if (exhaust) values.removeMatching(val);
+ if (exhaust)
+ values.removeMatching(val);
return val.getRight();
}
/**
* Get a value, treating this as a set of binomial trials.
- *
- * Essentially, the system rolls a bound-sided dice trials times, and
- * marks a success for every roll less than or equal to target.
- *
+ *
+ * Essentially, the system rolls a bound-sided dice trials times, and marks a
+ * success for every roll less than or equal to target.
+ *
* @param target
- * The number to roll at or under.
+ * The number to roll at or under.
* @param bound
- * The maximum roll value.
+ * The maximum roll value.
* @param trials
- * The number of times to roll.
- * @return The value at the index corresponding to the number of
- * successes.
+ * The number of times to roll.
+ * @return The value at the index corresponding to the number of successes.
*/
public E getBinomial(int target, int bound, int trials) {
return getBinomial(target, bound, trials, source);
@@ -198,41 +199,43 @@ public class WeightedRandom<E> {
/**
* Get a value, treating this as a set of binomial trials.
- *
- * Essentially, the system rolls a bound-sided dice trials times, and
- * marks a success for every roll less than or equal to target.
- *
+ *
+ * Essentially, the system rolls a bound-sided dice trials times, and marks a
+ * success for every roll less than or equal to target.
+ *
* @param target
- * The number to roll at or under.
+ * The number to roll at or under.
* @param bound
- * The maximum roll value.
+ * The maximum roll value.
* @param trials
- * The number of times to roll.
+ * The number of times to roll.
* @param rn
- * The Random instance to use.
- * @return The value at the index corresponding to the number of
- * successes.
+ * The Random instance to use.
+ * @return The value at the index corresponding to the number of successes.
*/
public E getBinomial(int target, int bound, int trials, Random rn) {
- if (values.getSize() == 0) return null;
+ if (values.getSize() == 0)
+ return null;
int numSuc = 0;
for (int i = 0; i < trials; i++) {
/*
- * Adjust for zero, because it's easy to think of this
- * as rolling a bound-sided dice and marking a success
- * for every roll less than or equal to target.
+ * Adjust for zero, because it's easy to think of this as rolling a
+ * bound-sided dice and marking a success for every roll less than or equal to
+ * target.
*/
int num = rn.nextInt(bound) + 1;
if (num <= target) {
- //System.err.printf("\t\tTRACE: mark binomial success (%d <= 1d%d, %d)\n", target, bound, num);
+ // System.err.printf("\t\tTRACE: mark binomial success (%d <= 1d%d,
+ // %d)\n", target, bound, num);
numSuc += 1;
}
}
- //System.err.printf("\tTRACE: got %d success for binomial trials (%d <= 1d%d, %d times)\n", numSuc, target, bound, trials);
+ // System.err.printf("\tTRACE: got %d success for binomial trials (%d <= 1d%d,
+ // %d times)\n", numSuc, target, bound, trials);
IPair<Integer, E> val = values.getByIndex(Math.min(numSuc, values.getSize() - 1));
if (exhaust) {
totalChance -= val.getLeft();
@@ -244,8 +247,9 @@ public class WeightedRandom<E> {
}
/**
- * Return a new WeightedRandom that is exhaustible (only returns one value once).
- *
+ * Return a new WeightedRandom that is exhaustible (only returns one value
+ * once).
+ *
* @return A new WeightedRandom that is exhaustible.
*/
public WeightedRandom<E> exhaustible() {
diff --git a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java
index ee360bd..d818ca1 100644
--- a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java
+++ b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java
@@ -20,24 +20,25 @@ import bjc.utils.funcutils.FuncUtils;
* @author ben
*
* @param <T>
- * The type of the nodes in the graph
+ * The type of the nodes in the graph
*/
public class AdjacencyMap<T> {
/**
* Create an adjacency map from a stream of text
*
* @param stream
- * The stream of text to read in
+ * The stream of text to read in
*
* @return An adjacency map defined by the text
*/
public static AdjacencyMap<Integer> fromStream(final 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<Integer> adjacency;
- try(Scanner input = new Scanner(stream)) {
+ try (Scanner input = new Scanner(stream)) {
input.useDelimiter("\n");
int vertexCount;
@@ -47,7 +48,7 @@ public class AdjacencyMap<T> {
try {
/* First, read in number of vertices. */
vertexCount = Integer.parseInt(possible);
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
String msg = String.format(
"The first line must contain the number of vertices. %s is not a valid number",
possible);
@@ -59,18 +60,19 @@ public class AdjacencyMap<T> {
throw imex;
}
- if(vertexCount <= 0)
- throw new InputMismatchException("The number of vertices must be greater than 0");
+ if (vertexCount <= 0)
+ throw new InputMismatchException(
+ "The number of vertices must be greater than 0");
final IList<Integer> vertices = new FunctionalList<>();
- FuncUtils.doTimes(vertexCount, (vertexNo) -> vertices.add(vertexNo));
+ FuncUtils.doTimes(vertexCount, vertexNo -> vertices.add(vertexNo));
adjacency = new AdjacencyMap<>(vertices);
final IHolder<Integer> row = new Identity<>(0);
- input.forEachRemaining((strang) -> {
+ input.forEachRemaining(strang -> {
readRow(adjacency, vertexCount, row, strang);
});
}
@@ -79,24 +81,25 @@ public class AdjacencyMap<T> {
}
/* Read a row of edges. */
- private static void readRow(final AdjacencyMap<Integer> adjacency, final int vertexCount,
- final IHolder<Integer> row, final String strang) {
+ private static void readRow(final AdjacencyMap<Integer> adjacency,
+ final int vertexCount, final IHolder<Integer> row, final String strang) {
final String[] parts = strang.split(" ");
- if(parts.length != vertexCount) {
- String msg = String.format("Must specify a weight for all %d vertices", vertexCount);
+ if (parts.length != vertexCount) {
+ String msg = String.format("Must specify a weight for all %d vertices",
+ vertexCount);
throw new InputMismatchException(msg);
}
int column = 0;
- for(final String part : parts) {
+ for (final String part : parts) {
int weight;
try {
weight = Integer.parseInt(part);
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
String msg = String.format("%d is not a valid weight.", part);
final InputMismatchException imex = new InputMismatchException(msg);
@@ -110,7 +113,7 @@ public class AdjacencyMap<T> {
column++;
}
- row.transform((rowNumber) -> rowNumber + 1);
+ row.transform(rowNumber -> rowNumber + 1);
}
/** The backing storage of the map */
@@ -120,10 +123,11 @@ public class AdjacencyMap<T> {
* Create a new map from a set of vertices
*
* @param vertices
- * The set of vertices to create a map from
+ * The set of vertices to create a map from
*/
public AdjacencyMap(final IList<T> 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 -> {
final IMap<T, Integer> row = new FunctionalMap<>();
@@ -148,7 +152,7 @@ public class AdjacencyMap<T> {
sourceValue.forEach((targetKey, targetValue) -> {
final int inverseValue = adjacency.get(targetKey).get(sourceKey);
- if(targetValue != inverseValue) {
+ if (targetValue != inverseValue) {
result.replace(false);
}
});
@@ -161,24 +165,24 @@ public class AdjacencyMap<T> {
* Set the weight of an edge.
*
* @param source
- * The source node of the edge.
+ * The source node of the edge.
* @param target
- * The target node of the edge.
+ * The target node of the edge.
* @param weight
- * The weight of the edge.
+ * The weight of the edge.
*/
public void setWeight(final T source, final T target, final int weight) {
- if(source == null) {
+ if (source == null) {
throw new NullPointerException("Source vertex must not be null");
- } else if(target == null) {
+ } else if (target == null) {
throw new NullPointerException("Target vertex must not be null");
}
- if(!adjacency.containsKey(source)) {
+ if (!adjacency.containsKey(source)) {
String msg = String.format("Source vertex %s isn't present in map", source);
throw new IllegalArgumentException(msg);
- } else if(!adjacency.containsKey(target)) {
+ } else if (!adjacency.containsKey(target)) {
String msg = String.format("Target vertex %s isn't present in map", target);
throw new IllegalArgumentException(msg);
@@ -208,10 +212,11 @@ public class AdjacencyMap<T> {
* Convert an adjacency map back into a stream.
*
* @param sink
- * The stream to convert to.
+ * The stream to convert to.
*/
public void toStream(final 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");
final PrintStream outputPrinter = new PrintStream(sink);
diff --git a/base/src/main/java/bjc/utils/graph/Edge.java b/base/src/main/java/bjc/utils/graph/Edge.java
index e7e7b36..fe3d891 100644
--- a/base/src/main/java/bjc/utils/graph/Edge.java
+++ b/base/src/main/java/bjc/utils/graph/Edge.java
@@ -6,7 +6,7 @@ package bjc.utils.graph;
* @author ben
*
* @param <T>
- * The type of the nodes in the graph.
+ * The type of the nodes in the graph.
*/
public class Edge<T> {
/* The distance from initial to terminal node. */
@@ -19,18 +19,18 @@ public class Edge<T> {
* Create a new edge with set parameters.
*
* @param initial
- * The initial node of the edge.
+ * The initial node of the edge.
*
* @param terminal
- * The terminal node of the edge.
+ * The terminal node of the edge.
*
* @param distance
- * The distance between initial and terminal edge.
+ * The distance between initial and terminal edge.
*/
public Edge(final T initial, final T terminal, final int distance) {
- if(initial == null) {
+ if (initial == null) {
throw new NullPointerException("Initial node must not be null");
- } else if(terminal == null) {
+ } else if (terminal == null) {
throw new NullPointerException("Terminal node must not be null");
}
@@ -41,24 +41,27 @@ public class Edge<T> {
@Override
public boolean equals(final 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 {
final Edge<?> other = (Edge<?>) obj;
- if(distance != other.distance)
+ if (distance != other.distance)
return false;
- else if(source == null) {
- if(other.source != null) return false;
- } else if(!source.equals(other.source))
+ else if (source == null) {
+ if (other.source != null)
+ return false;
+ } else if (!source.equals(other.source))
+ return false;
+ else if (target == null) {
+ if (other.target != null)
+ return false;
+ } else if (!target.equals(other.target))
return false;
- else if(target == null) {
- if(other.target != null) return false;
- } else if(!target.equals(other.target)) return false;
return true;
}
@@ -67,8 +70,7 @@ public class Edge<T> {
/**
* Get the distance in this edge.
*
- * @return The distance between the initial and terminal nodes of this
- * edge.
+ * @return The distance between the initial and terminal nodes of this edge.
*/
public int getDistance() {
return distance;
@@ -107,8 +109,9 @@ public class Edge<T> {
@Override
public String toString() {
- String msg = String.format("source vertex %s to target vertex %s with distance: %s", source, target,
- distance);
+ String msg
+ = String.format("source vertex %s to target vertex %s with distance: %s",
+ source, target, distance);
return msg;
}
diff --git a/base/src/main/java/bjc/utils/graph/Graph.java b/base/src/main/java/bjc/utils/graph/Graph.java
index e092623..8ff5647 100644
--- a/base/src/main/java/bjc/utils/graph/Graph.java
+++ b/base/src/main/java/bjc/utils/graph/Graph.java
@@ -22,17 +22,17 @@ import bjc.funcdata.IMap;
* @author ben
*
* @param <T>
- * The label for vertices.
+ * The label for vertices.
*/
public class Graph<T> {
/**
* Create a graph from a list of edges.
*
* @param <E>
- * The type of data stored in the edges.
+ * The type of data stored in the edges.
*
* @param edges
- * The list of edges to build from.
+ * The list of edges to build from.
*
* @return A graph built from the provided edge-list.
*/
@@ -58,27 +58,28 @@ public class Graph<T> {
* Add a edge to the graph.
*
* @param source
- * The source vertex for this edge.
+ * The source vertex for this edge.
*
* @param target
- * The target vertex for this edge.
+ * The target vertex for this edge.
*
* @param distance
- * The distance from the source vertex to the target vertex.
+ * The distance from the source vertex to the target vertex.
*
* @param directed
- * Whether or not the edge is directed or not.
+ * Whether or not the edge is directed or not.
*/
- public void addEdge(final T source, final T target, final int distance, final boolean directed) {
+ public void addEdge(final T source, final T target, final int distance,
+ final boolean directed) {
/* Can't add edges with a null source or target. */
- if(source == null) {
+ if (source == null) {
throw new NullPointerException("The source vertex cannot be null");
- } else if(target == 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<T, Integer>());
}
@@ -86,8 +87,8 @@ public class Graph<T> {
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<T, Integer>());
}
@@ -96,28 +97,27 @@ public class Graph<T> {
}
/**
- * Execute an action for all edges of a specific vertex matching
- * conditions.
+ * Execute an action for all edges of a specific vertex matching conditions.
*
* @param source
- * The vertex to test edges for.
+ * The vertex to test edges for.
*
* @param matcher
- * The conditions an edge must match.
+ * The conditions an edge must match.
*
* @param action
- * The action to execute for matching edges.
+ * The action to execute for matching edges.
*/
- public void forAllEdgesMatchingAt(final T source, final BiPredicate<T, Integer> matcher,
- final BiConsumer<T, Integer> action) {
- if(matcher == null) {
+ public void forAllEdgesMatchingAt(final T source,
+ final BiPredicate<T, Integer> matcher, final BiConsumer<T, Integer> action) {
+ if (matcher == null) {
throw new NullPointerException("Matcher must not be null");
- } else if(action == null) {
+ } 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);
}
});
@@ -127,14 +127,14 @@ public class Graph<T> {
* Get all the edges that begin at a particular source vertex.
*
* @param source
- * The vertex to use as a source.
+ * The vertex to use as a source.
* @return All of the edges with the specified vertex as a source.
*/
public IMap<T, Integer> getEdges(final 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);
@@ -152,8 +152,7 @@ public class Graph<T> {
/**
* Uses Prim's algorothm to calculate a MST for the graph.
*
- * If the graph is non-connected, this will lead to unpredictable
- * results.
+ * If the graph is non-connected, this will lead to unpredictable results.
*
* @return A list of edges that constitute the MST.
*/
@@ -174,12 +173,10 @@ public class Graph<T> {
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) -> {
- return !visited.contains(target);
- }, (target, weight) -> {
+ forAllEdgesMatchingAt(source.getValue(), (target, weight) -> !visited.contains(target), (target, weight) -> {
final T vert = source.unwrap(vertex -> vertex);
available.add(new Edge<>(vert, target, weight));
@@ -189,18 +186,17 @@ public class Graph<T> {
final IHolder<Edge<T>> minimum = new Identity<>(available.poll());
/*
- * Only consider edges where we haven't visited the
- * target of the edge.
+ * Only consider edges where we haven't visited the target of the edge.
*/
- while(visited.contains(minimum.getValue().getTarget())) {
- minimum.transform((edge) -> available.poll());
+ while (visited.contains(minimum.getValue().getTarget())) {
+ minimum.transform(edge -> available.poll());
}
/* Add it to our MST. */
minimums.add(minimum.getValue());
/* Advance to the next node. */
- source.transform((vertex) -> minimum.unwrap(edge -> edge.getTarget()));
+ source.transform(vertex -> minimum.unwrap(edge -> edge.getTarget()));
/* Visit this node. */
visited.add(source.getValue());
@@ -231,27 +227,27 @@ public class Graph<T> {
* Remove the edge starting at the source and ending at the target.
*
* @param source
- * The source vertex for the edge.
+ * The source vertex for the edge.
*
* @param target
- * The target vertex for the edge.
+ * The target vertex for the edge.
*/
public void removeEdge(final T source, final 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) {
+ } 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)) {
String msg = String.format("vertex %s does not exist", source);
throw new NoSuchElementException(msg);
}
- if(!backing.containsKey(target)) {
+ if (!backing.containsKey(target)) {
String msg = String.format("vertex %s does not exist", target);
throw new NoSuchElementException(msg);
diff --git a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java
index d2129b0..d9ebda5 100644
--- a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java
+++ b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java
@@ -26,7 +26,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.
+ * The extensions to show in this filter.
*/
public ExtensionFileFilter(final List<String> exts) {
extensions = new FunctionalList<>(exts);
@@ -36,7 +36,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.
+ * The extensions to show in this filter.
*/
public ExtensionFileFilter(final String... exts) {
extensions = new FunctionalList<>(exts);
@@ -44,7 +44,8 @@ public class ExtensionFileFilter extends FileFilter {
@Override
public boolean accept(final 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/base/src/main/java/bjc/utils/gui/SimpleDialogs.java b/base/src/main/java/bjc/utils/gui/SimpleDialogs.java
index b7763a2..a0df64d 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleDialogs.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleDialogs.java
@@ -25,25 +25,25 @@ public class SimpleDialogs {
* Get a bounded integer from the user.
*
* @param parent
- * The parent component for the dialogs.
+ * The parent component for the dialogs.
* @param title
- * The title for the dialogs.
+ * The title for the dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @param lowerBound
- * The lower integer bound to accept.
+ * The lower integer bound to accept.
* @param upperBound
- * The upper integer bound to accept.
+ * The upper integer bound to accept.
* @return A int within the specified bounds.
*/
- public static int getBoundedInt(final Component parent, final String title, final String prompt,
- final int lowerBound, final int upperBound) {
- return getValue(parent, title, prompt, (strang) -> {
+ public static int getBoundedInt(final Component parent, final String title,
+ final String prompt, final int lowerBound, final int upperBound) {
+ return getValue(parent, title, prompt, strang -> {
try {
final int value = Integer.parseInt(strang);
return value < upperBound && value > lowerBound;
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
// We don't care about the specifics of the
// exception, just
// that this value isn't good
@@ -56,26 +56,27 @@ public class SimpleDialogs {
* Asks the user to pick an option from a series of choices.
*
* @param <E>
- * The type of choices for the user to pick
+ * The type of choices for the user to pick
*
* @param parent
- * The parent frame for this dialog
+ * The parent frame for this dialog
* @param title
- * The title of this dialog
+ * The title of this dialog
* @param question
- * The question being asked
+ * The question being asked
* @param choices
- * The available choices for the question
+ * The available choices for the question
* @return The choice the user picked, or null if they didn't pick one
*/
@SuppressWarnings("unchecked")
- public static <E> E getChoice(final Frame parent, final String title, final String question,
- final E... choices) {
- if(parent == null)
+ public static <E> E getChoice(final Frame parent, final String title,
+ final String question, final E... choices) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(question == null) throw new NullPointerException("Question must not be null");
+ else if (question == null)
+ throw new NullPointerException("Question must not be null");
final JDialog chooser = new JDialog(parent, title, true);
chooser.setLayout(new VLayout(2));
@@ -93,8 +94,8 @@ public class SimpleDialogs {
final JButton okButton = new JButton("Ok");
final JButton cancelButton = new JButton("Cancel");
- okButton.addActionListener((event) -> chooser.dispose());
- cancelButton.addActionListener((event) -> chooser.dispose());
+ okButton.addActionListener(event -> chooser.dispose());
+ cancelButton.addActionListener(event -> chooser.dispose());
buttonPane.add(cancelButton);
buttonPane.add(okButton);
@@ -112,19 +113,20 @@ public class SimpleDialogs {
* Get a integer from the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A int.
*/
- public static int getInt(final Component parent, final String title, final String prompt) {
+ public static int getInt(final Component parent, final String title,
+ final String prompt) {
return getValue(parent, title, prompt, strang -> {
try {
Integer.parseInt(strang);
return true;
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
// We don't care about this exception, just mark
// the value
// as not good
@@ -137,50 +139,55 @@ public class SimpleDialogs {
* Get a string from the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for the dialogs.
+ * The title for the dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A string.
*/
- public static String getString(final Component parent, final String title, final String prompt) {
- if(parent == null)
+ public static String getString(final Component parent, final String title,
+ final String prompt) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(prompt == null) throw new NullPointerException("Prompt must not be null");
+ else if (prompt == null)
+ throw new NullPointerException("Prompt must not be null");
- return JOptionPane.showInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE);
+ return JOptionPane.showInputDialog(parent, prompt, title,
+ JOptionPane.QUESTION_MESSAGE);
}
/**
* Get a value parsable from a string from the user.
*
* @param <E>
- * The type of the value parsed from the string
+ * The type of the value parsed from the string
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @param validator
- * A predicate to determine if a input is valid.
+ * A predicate to determine if a input is valid.
* @param transformer
- * The function to transform the string into a value.
+ * The function to transform the string into a value.
* @return The value parsed from a string.
*/
- public static <E> E getValue(final Component parent, final String title, final String prompt,
- final Predicate<String> validator, final Function<String, E> transformer) {
- if(validator == null)
+ public static <E> E getValue(final Component parent, final String title,
+ final String prompt, final Predicate<String> validator,
+ final Function<String, E> transformer) {
+ if (validator == null)
throw new NullPointerException("Validator must not be null");
- else if(transformer == null) throw new NullPointerException("Transformer must not be null");
+ else if (transformer == null)
+ throw new NullPointerException("Transformer must not be null");
String input = getString(parent, title, prompt);
- while(!validator.test(input)) {
+ while (!validator.test(input)) {
showError(parent, "I/O Error", "Please enter a valid value");
input = getString(parent, title, prompt);
@@ -193,14 +200,15 @@ public class SimpleDialogs {
* Get a whole number from the user.
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A whole number.
*/
- public static int getWhole(final Component parent, final String title, final String prompt) {
+ public static int getWhole(final Component parent, final String title,
+ final String prompt) {
return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE);
}
@@ -208,21 +216,24 @@ public class SimpleDialogs {
* Ask the user a Yes/No question.
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param question
- * The question to ask the user.
+ * The question to ask the user.
* @return True if the user said yes, false otherwise.
*/
- public static boolean getYesNo(final Component parent, final String title, final String question) {
- if(parent == null)
+ public static boolean getYesNo(final Component parent, final String title,
+ final String question) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(question == null) throw new NullPointerException("Question must not be null");
+ else if (question == null)
+ throw new NullPointerException("Question must not be null");
- final int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION);
+ final int result = JOptionPane.showConfirmDialog(parent, question, title,
+ JOptionPane.YES_NO_OPTION);
return result == JOptionPane.YES_OPTION ? true : false;
}
@@ -231,18 +242,20 @@ public class SimpleDialogs {
* Show a error message to the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param message
- * The error to show the user.
+ * The error to show the user.
*/
- public static void showError(final Component parent, final String title, final String message) {
- if(parent == null)
+ public static void showError(final Component parent, final String title,
+ final String message) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(message == null) throw new NullPointerException("Error message must not be null");
+ else if (message == null)
+ throw new NullPointerException("Error message must not be null");
JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE);
}
@@ -251,19 +264,22 @@ public class SimpleDialogs {
* Show an informative message to the user
*
* @param parent
- * The parent for this dialog
+ * The parent for this dialog
* @param title
- * Show the title for this dialog
+ * Show the title for this dialog
* @param message
- * Show the message for this dialog
+ * Show the message for this dialog
*/
- public static void showMessage(final Component parent, final String title, final String message) {
- if(parent == null)
+ public static void showMessage(final Component parent, final String title,
+ final String message) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(message == null) throw new NullPointerException("Message must not be null");
+ else if (message == null)
+ throw new NullPointerException("Message must not be null");
- JOptionPane.showMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE);
+ JOptionPane.showMessageDialog(parent, title, message,
+ JOptionPane.INFORMATION_MESSAGE);
}
}
diff --git a/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java
index 01cd37f..7be9f84 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java
@@ -16,54 +16,60 @@ import bjc.utils.exceptions.FileNotChosenException;
*
*/
public class SimpleFileChooser {
- private static File doOpenFile(final Component parent, final String title, final JFileChooser files) {
- if(title == null) throw new NullPointerException("Title must not be null");
+ private static File doOpenFile(final Component parent, final String title,
+ final JFileChooser files) {
+ if (title == null)
+ throw new NullPointerException("Title must not be null");
files.setDialogTitle(title);
boolean success = false;
- while(!success) {
+ while (!success) {
try {
maybeDoOpenFile(parent, files);
success = true;
- } catch(final FileNotChosenException fncx) {
+ } catch (final FileNotChosenException fncx) {
// We don't care about specifics
- SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open");
+ SimpleDialogs.showError(parent, "I/O Error",
+ "Please pick a file to open");
}
}
return files.getSelectedFile();
}
- private static File doSaveFile(final Component parent, final String title, final JFileChooser files) {
- if(title == null) throw new NullPointerException("Title must not be null");
+ private static File doSaveFile(final Component parent, final String title,
+ final JFileChooser files) {
+ if (title == null)
+ throw new NullPointerException("Title must not be null");
files.setDialogTitle(title);
final boolean success = false;
- while(!success) {
+ while (!success) {
try {
maybeDoSaveFile(parent, files);
return files.getSelectedFile();
- } catch(final FileNotChosenException fncex) {
+ } catch (final FileNotChosenException fncex) {
// We don't care about specifics
- SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to");
+ SimpleDialogs.showError(parent, "I/O Error",
+ "Please pick a file to save to");
}
}
}
/**
- * Prompt the user with a "Open File..." dialog. Keeps prompting them
- * until they pick a file.
+ * 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.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @return The file the user has chosen.
*/
public static File getOpenFile(final Component parent, final String title) {
@@ -73,18 +79,19 @@ public class SimpleFileChooser {
}
/**
- * Prompt the user with a "Open File..." dialog. Keeps prompting them
- * until they pick a file.
+ * 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.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @param extensions
- * The list of file extensions the file should have.
+ * The list of file extensions the file should have.
* @return The file the user has chosen.
*/
- public static File getOpenFile(final Component parent, final String title, final String... extensions) {
+ public static File getOpenFile(final Component parent, final String title,
+ final String... extensions) {
final JFileChooser files = new JFileChooser();
files.addChoosableFileFilter(new ExtensionFileFilter(extensions));
@@ -96,9 +103,9 @@ public class SimpleFileChooser {
* Prompt the user with a "Save File..." dialog.
*
* @param parent
- * The component to use as the parent for the dialog.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @return The file the user chose.
*/
public static File getSaveFile(final Component parent, final String title) {
@@ -111,14 +118,15 @@ public class SimpleFileChooser {
* Prompt the user with a "Save File..." dialog.
*
* @param parent
- * The component to use as the parent for the dialog.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @param extensions
- * The extensions of the files the user can choose.
+ * The extensions of the files the user can choose.
* @return The file the user chose.
*/
- public static File getSaveFile(final Component parent, final String title, final String... extensions) {
+ public static File getSaveFile(final Component parent, final String title,
+ final String... extensions) {
final JFileChooser files = new JFileChooser();
files.addChoosableFileFilter(new ExtensionFileFilter(extensions));
@@ -128,44 +136,49 @@ public class SimpleFileChooser {
private static void maybeDoOpenFile(final Component parent, final 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");
final int result = files.showSaveDialog(parent);
- if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException();
+ if (result != JFileChooser.APPROVE_OPTION)
+ throw new FileNotChosenException();
}
private static void maybeDoSaveFile(final Component parent, final 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");
final 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.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @return The file if the user chose one or null if they didn't.
*/
public static File maybeOpenFile(final Component parent, final String title) {
- if(title == null) throw new NullPointerException("Title must not be null");
+ if (title == null)
+ throw new NullPointerException("Title must not be null");
final JFileChooser files = new JFileChooser();
files.setDialogTitle(title);
try {
maybeDoOpenFile(parent, files);
- } catch(final FileNotChosenException fncex) {
+ } catch (final FileNotChosenException fncex) {
// We don't care about specifics
}
@@ -176,45 +189,47 @@ public class SimpleFileChooser {
* Prompt the user with a "Save File..." dialog.
*
* @param parent
- * The component to use as the parent for the dialog.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog to prompt with.
+ * The title of the dialog to prompt with.
* @return The file if the user chose one or null if they didn't.
*/
public static File maybeSaveFile(final Component parent, final String title) {
- if(title == null) throw new NullPointerException("Title must not be null");
+ if (title == null)
+ throw new NullPointerException("Title must not be null");
final JFileChooser files = new JFileChooser();
files.setDialogTitle(title);
try {
maybeDoSaveFile(parent, files);
- } catch(final FileNotChosenException fncex) {
+ } catch (final FileNotChosenException fncex) {
// We don't care about specifics
}
return files.getSelectedFile();
}
-
+
/**
* Show a dialog box to pick a directory.
- *
+ *
* @param parent
- * The component to use as the parent for the dialog.
+ * The component to use as the parent for the dialog.
* @param title
- * The title of the dialog for prompting.
+ * The title of the dialog for prompting.
* @return The directory picked, if the user picked one; null if they didn't.
*/
public static File pickDirectory(final Component parent, final String title) {
- if (title == null) throw new NullPointerException("Title must not be null");
-
+ if (title == null)
+ throw new NullPointerException("Title must not be null");
+
final JFileChooser files = new JFileChooser();
files.setDialogType(JFileChooser.OPEN_DIALOG);
files.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
files.setDialogTitle(title);
-
+
files.showOpenDialog(parent);
-
+
return files.getSelectedFile();
}
}
diff --git a/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java b/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java
index ef56011..5e16c84 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java
@@ -19,25 +19,25 @@ public class SimpleInternalDialogs {
* Get a bounded integer from the user.
*
* @param parent
- * The parent component for the dialogs.
+ * The parent component for the dialogs.
* @param title
- * The title for the dialogs.
+ * The title for the dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @param lowerBound
- * The lower integer bound to accept.
+ * The lower integer bound to accept.
* @param upperBound
- * The upper integer bound to accept.
+ * The upper integer bound to accept.
* @return A int within the specified bounds.
*/
- public static int getBoundedInt(final Component parent, final String title, final String prompt,
- final int lowerBound, final int upperBound) {
- return getValue(parent, title, prompt, (strang) -> {
+ public static int getBoundedInt(final Component parent, final String title,
+ final String prompt, final int lowerBound, final int upperBound) {
+ return getValue(parent, title, prompt, strang -> {
try {
final int value = Integer.parseInt(strang);
return value < upperBound && value > lowerBound;
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
// We don't care about the specifics of the
// exception, just
// that this value isn't good
@@ -50,19 +50,20 @@ public class SimpleInternalDialogs {
* Get a integer from the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A int.
*/
- public static int getInt(final Component parent, final String title, final String prompt) {
+ public static int getInt(final Component parent, final String title,
+ final String prompt) {
return getValue(parent, title, prompt, strang -> {
try {
Integer.parseInt(strang);
return true;
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
// We don't care about this exception, just mark
// the value
// as not good
@@ -75,50 +76,55 @@ public class SimpleInternalDialogs {
* Get a string from the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for the dialogs.
+ * The title for the dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A string.
*/
- public static String getString(final Component parent, final String title, final String prompt) {
- if(parent == null)
+ public static String getString(final Component parent, final String title,
+ final String prompt) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(prompt == null) throw new NullPointerException("Prompt must not be null");
+ else if (prompt == null)
+ throw new NullPointerException("Prompt must not be null");
- return JOptionPane.showInternalInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE);
+ return JOptionPane.showInternalInputDialog(parent, prompt, title,
+ JOptionPane.QUESTION_MESSAGE);
}
/**
* Get a value parsable from a string from the user.
*
* @param <E>
- * The type of the value parsed from the string
+ * The type of the value parsed from the string
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @param validator
- * A predicate to determine if a input is valid.
+ * A predicate to determine if a input is valid.
* @param transformer
- * The function to transform the string into a value.
+ * The function to transform the string into a value.
* @return The value parsed from a string.
*/
- public static <E> E getValue(final Component parent, final String title, final String prompt,
- final Predicate<String> validator, final Function<String, E> transformer) {
- if(validator == null)
+ public static <E> E getValue(final Component parent, final String title,
+ final String prompt, final Predicate<String> validator,
+ final Function<String, E> transformer) {
+ if (validator == null)
throw new NullPointerException("Validator must not be null");
- else if(transformer == null) throw new NullPointerException("Transformer must not be null");
+ else if (transformer == null)
+ throw new NullPointerException("Transformer must not be null");
String strang = getString(parent, title, prompt);
- while(!validator.test(strang)) {
+ while (!validator.test(strang)) {
showError(parent, "I/O Error", "Please enter a valid value");
strang = getString(parent, title, prompt);
@@ -131,14 +137,15 @@ public class SimpleInternalDialogs {
* Get a whole number from the user.
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param prompt
- * The prompt to tell the user what to enter.
+ * The prompt to tell the user what to enter.
* @return A whole number.
*/
- public static int getWhole(final Component parent, final String title, final String prompt) {
+ public static int getWhole(final Component parent, final String title,
+ final String prompt) {
return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE);
}
@@ -146,19 +153,21 @@ public class SimpleInternalDialogs {
* Ask the user a Yes/No question.
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param question
- * The question to ask the user.
+ * The question to ask the user.
* @return True if the user said yes, false otherwise.
*/
- public static boolean getYesNo(final Component parent, final String title, final String question) {
- if(parent == null)
+ public static boolean getYesNo(final Component parent, final String title,
+ final String question) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(question == null) throw new NullPointerException("Question must not be null");
+ else if (question == null)
+ throw new NullPointerException("Question must not be null");
final int result = JOptionPane.showInternalConfirmDialog(parent, question, title,
JOptionPane.YES_NO_OPTION);
@@ -170,39 +179,45 @@ public class SimpleInternalDialogs {
* Show a error message to the user
*
* @param parent
- * The parent component for dialogs.
+ * The parent component for dialogs.
* @param title
- * The title for dialogs.
+ * The title for dialogs.
* @param message
- * The error to show the user.
+ * The error to show the user.
*/
- public static void showError(final Component parent, final String title, final String message) {
- if(parent == null)
+ public static void showError(final Component parent, final String title,
+ final String message) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(message == null) throw new NullPointerException("Error message must not be null");
+ else if (message == null)
+ throw new NullPointerException("Error message must not be null");
- JOptionPane.showInternalMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showInternalMessageDialog(parent, message, title,
+ JOptionPane.ERROR_MESSAGE);
}
/**
* Show an informative message to the user
*
* @param parent
- * The parent for this dialog
+ * The parent for this dialog
* @param title
- * Show the title for this dialog
+ * Show the title for this dialog
* @param message
- * Show the message for this dialog
+ * Show the message for this dialog
*/
- public static void showMessage(final Component parent, final String title, final String message) {
- if(parent == null)
+ public static void showMessage(final Component parent, final String title,
+ final String message) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null)
+ else if (title == null)
throw new NullPointerException("Title must not be null");
- else if(message == null) throw new NullPointerException("Message must not be null");
+ else if (message == null)
+ throw new NullPointerException("Message must not be null");
- JOptionPane.showInternalMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE);
+ JOptionPane.showInternalMessageDialog(parent, title, message,
+ JOptionPane.INFORMATION_MESSAGE);
}
}
diff --git a/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java b/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java
index 5c7983c..9cec9e1 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java
@@ -22,7 +22,7 @@ public class SimpleInternalFrame extends JInternalFrame {
* Create a new blank internal frame with a specific title
*
* @param title
- * The title of the internal frame
+ * The title of the internal frame
*/
public SimpleInternalFrame(final String title) {
super(title);
diff --git a/base/src/main/java/bjc/utils/gui/SimpleJList.java b/base/src/main/java/bjc/utils/gui/SimpleJList.java
index 31c995c..ca8eeb9 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleJList.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleJList.java
@@ -15,14 +15,15 @@ public class SimpleJList {
* Create a new JList from a given list.
*
* @param <E>
- * The type of data in the JList
+ * The type of data in the JList
*
* @param source
- * The list to populate the JList with.
+ * The list to populate the JList with.
* @return A JList populated with the elements from ls.
*/
public static <E> JList<E> buildFromList(final Iterable<E> 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));
}
@@ -31,14 +32,15 @@ public class SimpleJList {
* Create a new list model from a given list.
*
* @param <E>
- * The type of data in the list model
+ * The type of data in the list model
*
* @param source
- * The list to fill the list model from.
+ * The list to fill the list model from.
* @return A list model populated with the elements from ls.
*/
public static <E> ListModel<E> buildModel(final Iterable<E> source) {
- if(source == null) throw new NullPointerException("Source must not be null");
+ if (source == null)
+ throw new NullPointerException("Source must not be null");
final DefaultListModel<E> defaultModel = new DefaultListModel<>();
diff --git a/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java b/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java
index 031cee3..0c40fbe 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java
@@ -10,7 +10,7 @@ import javax.swing.KeyStroke;
/**
* Simple {@link JButton} that provides an easy way to add a key-map to it.
- *
+ *
* @author Ben Culkin
*
*/
@@ -32,48 +32,62 @@ public class SimpleKeyedButton extends JButton {
}
private static final long serialVersionUID = -8550504153221678178L;
-
+
private String label;
/**
* Create a new keyed button.
- *
- * @param label The label for the button.
+ *
+ * @param label
+ * The label for the button.
*/
public SimpleKeyedButton(String label) {
super(label);
-
+
this.label = label;
}
-
+
/**
- * Sets the default action for this button, and installs a global (WHEN_IN_FOCUSED_WINDOW) keystroke handler for it.
- *
- * @param eventName An unique internal name for the event.
- * @param keystroke The keystroke for this event, passed to {@link KeyStroke#getKeyStroke(String)}.
- * @param aevListener The listener that handles the implementation of the action.
+ * Sets the default action for this button, and installs a global
+ * (WHEN_IN_FOCUSED_WINDOW) keystroke handler for it.
+ *
+ * @param eventName
+ * An unique internal name for the event.
+ * @param keystroke
+ * The keystroke for this event, passed to
+ * {@link KeyStroke#getKeyStroke(String)}.
+ * @param aevListener
+ * The listener that handles the implementation of the
+ * action.
*/
- public void setGlobalDefaultKeystroke(String eventName, String keystroke, Consumer<ActionEvent> aevListener) {
+ public void setGlobalDefaultKeystroke(String eventName, String keystroke,
+ Consumer<ActionEvent> aevListener) {
Action act = new KeyedButtonAction(eventName, aevListener);
KeyStroke stroke = KeyStroke.getKeyStroke(keystroke);
-
+
this.setAction(act);
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName);
this.getActionMap().put(eventName, act);
this.setText(label);
}
-
+
/**
* Installs a global (WHEN_IN_FOCUSED_WINDOW) keystroke handler for an action.
- *
- * @param eventName An unique internal name for the event.
- * @param keystroke The keystroke for this event, passed to {@link KeyStroke#getKeyStroke(String)}.
- * @param aevListener The listener that handles the implementation of the action.
+ *
+ * @param eventName
+ * An unique internal name for the event.
+ * @param keystroke
+ * The keystroke for this event, passed to
+ * {@link KeyStroke#getKeyStroke(String)}.
+ * @param aevListener
+ * The listener that handles the implementation of the
+ * action.
*/
- public void addGlobalKeystroke(String eventName, String keystroke, Consumer<ActionEvent> aevListener) {
+ public void addGlobalKeystroke(String eventName, String keystroke,
+ Consumer<ActionEvent> aevListener) {
Action act = new KeyedButtonAction(eventName, aevListener);
KeyStroke stroke = KeyStroke.getKeyStroke(keystroke);
-
+
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName);
this.getActionMap().put(eventName, act);
this.setText(label);
diff --git a/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java b/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java
index bddb564..81b0579 100644
--- a/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java
+++ b/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java
@@ -17,7 +17,7 @@ public class SimpleTitledBorder extends TitledBorder {
* Create a new border with the specified title.
*
* @param title
- * The title for the border.
+ * The title for the border.
*/
public SimpleTitledBorder(final String title) {
super(new EtchedBorder(), title);
diff --git a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java
index 0beb1e2..fbc58ed 100644
--- a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java
+++ b/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java
@@ -18,7 +18,7 @@ public class TextAreaOutputStream extends OutputStream {
* Create a new output stream attached to a textarea
*
* @param console
- * The textarea to write to
+ * The textarea to write to
*/
public TextAreaOutputStream(final JTextArea console) {
this.textArea = console;
@@ -28,7 +28,7 @@ public class TextAreaOutputStream extends OutputStream {
public void write(final int b) throws IOException {
textArea.append("" + (char) b);
- if(b == '\n') {
+ if (b == '\n') {
textArea.repaint();
}
}
diff --git a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java
index e207a35..04b0b68 100644
--- a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java
+++ b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java
@@ -22,10 +22,11 @@ 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.
+ * The extensions to show in this filter.
*/
public ExtensionFileFilter(final List<String> 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);
}
@@ -34,7 +35,7 @@ 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.
+ * The extensions to show in this filter.
*/
public ExtensionFileFilter(final String... exts) {
extensions = new FunctionalList<>(exts);
diff --git a/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java
index daea7cd..2cb3122 100644
--- a/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java
+++ b/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java
@@ -19,10 +19,10 @@ public class SimpleFileDialog {
* Prompt the user to pick a file to open.
*
* @param parent
- * The parent of the file picker.
+ * The parent of the file picker.
*
* @param title
- * The title of the file picker.
+ * The title of the file picker.
*
* @return The file the user picked.
*/
@@ -34,34 +34,36 @@ public class SimpleFileDialog {
* Prompt the user to pick a file to open.
*
* @param parent
- * The parent of the file picker.
+ * The parent of the file picker.
*
* @param title
- * The title of the file picker.
+ * The title of the file picker.
*
* @param extensions
- * The extensions to accept as valid.
+ * The extensions to accept as valid.
*
* @return The file the user picked.
*/
- public static File getOpenFile(final Frame parent, final String title, final String... extensions) {
- if(parent == null) {
+ public static File getOpenFile(final Frame parent, final String title,
+ final String... extensions) {
+ if (parent == null) {
throw new NullPointerException("Parent must not be null");
- } else if(title == null) {
+ } else if (title == null) {
throw new NullPointerException("Title must not be null");
}
final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD);
- if(extensions != null) {
+ if (extensions != null) {
final FilenameFilter filter = new ExtensionFileFilter(extensions);
chooser.setFilenameFilter(filter);
}
chooser.setVisible(true);
- while(chooser.getFile() == null) {
- SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open.");
+ while (chooser.getFile() == null) {
+ SimpleDialogs.showError(parent, "File I/O Error",
+ "Please choose a file to open.");
chooser.setVisible(true);
}
@@ -72,24 +74,26 @@ public class SimpleFileDialog {
* Prompt the user to pick a file to open.
*
* @param parent
- * The parent of the file picker.
+ * The parent of the file picker.
*
* @param title
- * The title of the file picker.
+ * The title of the file picker.
*
* @param extensions
- * The extensions to accept as valid.
+ * The extensions to accept as valid.
*
* @return The file the user picked.
*/
- public static File[] getOpenFiles(final Frame parent, final String title, final String... extensions) {
- if(parent == null)
+ public static File[] getOpenFiles(final Frame parent, final String title,
+ final String... extensions) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null) throw new NullPointerException("Title must not be null");
+ else if (title == null)
+ throw new NullPointerException("Title must not be null");
final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD);
- if(extensions != null) {
+ if (extensions != null) {
final FilenameFilter filter = new ExtensionFileFilter(extensions);
chooser.setFilenameFilter(filter);
}
@@ -97,8 +101,9 @@ public class SimpleFileDialog {
chooser.setMultipleMode(true);
chooser.setVisible(true);
- while(chooser.getFile() == null) {
- SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open.");
+ while (chooser.getFile() == null) {
+ SimpleDialogs.showError(parent, "File I/O Error",
+ "Please choose a file to open.");
chooser.setVisible(true);
}
@@ -109,10 +114,10 @@ public class SimpleFileDialog {
* Prompt the user to pick a file to save
*
* @param parent
- * The parent of the file picker
+ * The parent of the file picker
*
* @param title
- * The title of the file picker
+ * The title of the file picker
*
* @return The file the user picked
*/
@@ -124,32 +129,35 @@ public class SimpleFileDialog {
* Prompt the user to pick a file to save
*
* @param parent
- * The parent of the file picker
+ * The parent of the file picker
*
* @param title
- * The title of the file picker
+ * The title of the file picker
*
* @param extensions
- * The extensions to accept as valid
+ * The extensions to accept as valid
*
* @return The file the user picked
*/
- public static File getSaveFile(final Frame parent, final String title, final String... extensions) {
- if(parent == null)
+ public static File getSaveFile(final Frame parent, final String title,
+ final String... extensions) {
+ if (parent == null)
throw new NullPointerException("Parent must not be null");
- else if(title == null) throw new NullPointerException("Title must not be null");
+ else if (title == null)
+ throw new NullPointerException("Title must not be null");
final FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE);
- if(extensions != null) {
+ if (extensions != null) {
final FilenameFilter filter = new ExtensionFileFilter(extensions);
chooser.setFilenameFilter(filter);
}
chooser.setVisible(true);
- while(chooser.getFile() == null) {
- SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to.");
+ while (chooser.getFile() == null) {
+ SimpleDialogs.showError(parent, "File I/O Error",
+ "Please choose a file to save to.");
chooser.setVisible(true);
}
diff --git a/base/src/main/java/bjc/utils/gui/layout/HLayout.java b/base/src/main/java/bjc/utils/gui/layout/HLayout.java
index c2caa01..977cb15 100644
--- a/base/src/main/java/bjc/utils/gui/layout/HLayout.java
+++ b/base/src/main/java/bjc/utils/gui/layout/HLayout.java
@@ -16,7 +16,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.
+ * The number of columns in this layout.
*/
public HLayout(final int columns) {
super(1, columns);
diff --git a/base/src/main/java/bjc/utils/gui/layout/VLayout.java b/base/src/main/java/bjc/utils/gui/layout/VLayout.java
index d0f0503..3ee99e8 100644
--- a/base/src/main/java/bjc/utils/gui/layout/VLayout.java
+++ b/base/src/main/java/bjc/utils/gui/layout/VLayout.java
@@ -17,7 +17,7 @@ public class VLayout extends GridLayout {
* Create a new vertical layout with the specified number of rows.
*
* @param rows
- * The number of rows.
+ * The number of rows.
*/
public VLayout(final int rows) {
super(rows, 1);
diff --git a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java
index 642eee9..8f65577 100644
--- a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java
@@ -26,15 +26,16 @@ public class DropdownListPanel extends JPanel {
* Create a new dropdown list panel
*
* @param <T>
- * The type of items in the dropdown list
+ * The type of items in the dropdown list
* @param type
- * The label of the type of items in the list
+ * The label of the type of items in the list
* @param model
- * The model to put items into
+ * The model to put items into
* @param choices
- * The items to choose from
+ * The items to choose from
*/
- public <T> DropdownListPanel(final String type, final DefaultListModel<T> model, final IList<T> choices) {
+ public <T> DropdownListPanel(final String type, final DefaultListModel<T> model,
+ final IList<T> choices) {
setLayout(new AutosizeLayout());
final JPanel itemInputPanel = new JPanel();
@@ -56,11 +57,11 @@ public class DropdownListPanel extends JPanel {
final JButton removeItemButton = new JButton("Remove " + type);
- addItemButton.addActionListener((ev) -> {
+ addItemButton.addActionListener(ev -> {
model.addElement(addItemBox.getItemAt(addItemBox.getSelectedIndex()));
});
- removeItemButton.addActionListener((ev) -> {
+ removeItemButton.addActionListener(ev -> {
model.remove(itemList.getSelectedIndex());
});
diff --git a/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java
index 96f0487..3b66086 100644
--- a/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java
@@ -15,7 +15,7 @@ import bjc.utils.gui.layout.HLayout;
* @author ben
*
* @param <InputVal>
- * The type of value being formatted
+ * The type of value being formatted
*/
public class FormattedInputPanel<InputVal> extends JPanel {
private static final long serialVersionUID = 5232016563558588031L;
@@ -26,17 +26,17 @@ public class FormattedInputPanel<InputVal> extends JPanel {
* Create a new formatted input panel
*
* @param label
- * The label for this panel
+ * The label for this panel
* @param length
- * The length of this panel
+ * The length of this panel
* @param formatter
- * The formatter to use for input
+ * The formatter to use for input
* @param reciever
- * The action to call whenever the value changes
+ * The action to call whenever the value changes
*/
@SuppressWarnings("unchecked")
- public FormattedInputPanel(final String label, final int length, final AbstractFormatter formatter,
- final Consumer<InputVal> reciever) {
+ public FormattedInputPanel(final String label, final int length,
+ final AbstractFormatter formatter, final Consumer<InputVal> reciever) {
setLayout(new HLayout(2));
final JLabel lab = new JLabel(label);
@@ -44,7 +44,7 @@ public class FormattedInputPanel<InputVal> extends JPanel {
field.setColumns(length);
field.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
- field.addPropertyChangeListener("value", (event) -> {
+ field.addPropertyChangeListener("value", event -> {
// This is safe, because InputVal should be the type of
// whatever object the formatter is returning
reciever.accept((InputVal) field.getValue());
@@ -58,7 +58,7 @@ public class FormattedInputPanel<InputVal> extends JPanel {
* Reset the value in this panel to a specified value
*
* @param value
- * The value to set the panel to
+ * The value to set the panel to
*/
public void resetValues(final InputVal value) {
field.setValue(value);
diff --git a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java
index 9e1592e..d0b5383 100644
--- a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java
@@ -25,13 +25,14 @@ public class HolderOutputPanel extends JPanel {
* Create a new display panel, backed by a holder
*
* @param lab
- * The label to attach to this field
+ * The label to attach to this field
* @param valueHolder
- * The holder to get the value from
+ * The holder to get the value from
* @param nDelay
- * The delay in ms between value updates
+ * The delay in ms between value updates
*/
- public HolderOutputPanel(final String lab, final IHolder<String> valueHolder, final int nDelay) {
+ public HolderOutputPanel(final String lab, final IHolder<String> valueHolder,
+ final int nDelay) {
this.val = valueHolder;
this.nDelay = nDelay;
@@ -40,7 +41,7 @@ public class HolderOutputPanel extends JPanel {
final JLabel label = new JLabel(lab);
value = new JLabel("(stopped)");
- updater = new Timer(nDelay, (event) -> {
+ updater = new Timer(nDelay, event -> {
value.setText(valueHolder.getValue());
});
@@ -56,7 +57,7 @@ public class HolderOutputPanel extends JPanel {
value.setText("(stopped)");
- updater = new Timer(nDelay, (event) -> {
+ updater = new Timer(nDelay, event -> {
value.setText(val.getValue());
});
}
diff --git a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java
index d9c5966..3b48309 100644
--- a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java
@@ -20,7 +20,7 @@ import bjc.utils.gui.layout.VLayout;
* @author ben
*
* @param <E>
- * The type of data stored in the list
+ * The type of data stored in the list
*/
public class ListParameterPanel<E> extends JPanel {
// Version id for serialization
@@ -30,13 +30,14 @@ public class ListParameterPanel<E> extends JPanel {
* Create a new panel using the specified actions for doing things
*
* @param add
- * The action that provides items
+ * The action that provides items
* @param edit
- * The action that edits items
+ * The action that edits items
* @param remove
- * The action that removes items
+ * The action that removes items
*/
- public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove) {
+ public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit,
+ final Consumer<E> remove) {
this(add, edit, remove, null);
}
@@ -44,21 +45,21 @@ public class ListParameterPanel<E> extends JPanel {
* Create a new panel using the specified actions for doing things
*
* @param add
- * The action that provides items
+ * The action that provides items
* @param edit
- * The action that edits items
+ * The action that edits items
* @param remove
- * The action that removes items
+ * The action that removes items
* @param defaults
- * The default values to put in the list
+ * The default values to put in the list
*/
- public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove,
- final IList<E> defaults) {
+ public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit,
+ final Consumer<E> remove, final IList<E> defaults) {
setLayout(new VLayout(2));
JList<E> list;
- if(defaults != null) {
+ if (defaults != null) {
list = SimpleJList.buildFromList(defaults.toIterable());
} else {
list = new JList<>(new DefaultListModel<>());
@@ -70,15 +71,15 @@ public class ListParameterPanel<E> 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++;
}
@@ -86,9 +87,9 @@ public class ListParameterPanel<E> extends JPanel {
JButton addParam = null;
- if(add != null) {
+ if (add != null) {
addParam = new JButton("Add...");
- addParam.addActionListener((event) -> {
+ addParam.addActionListener(event -> {
final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel();
model.addElement(add.get());
@@ -97,33 +98,33 @@ public class ListParameterPanel<E> extends JPanel {
JButton editParam = null;
- if(edit != null) {
+ if (edit != null) {
editParam = new JButton("Edit...");
- editParam.addActionListener((event) -> {
+ editParam.addActionListener(event -> {
edit.accept(list.getSelectedValue());
});
}
JButton removeParam = null;
- if(remove != null) {
+ if (remove != null) {
removeParam = new JButton("Remove...");
- removeParam.addActionListener((event) -> {
+ removeParam.addActionListener(event -> {
final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel();
remove.accept(model.remove(list.getSelectedIndex()));
});
}
- if(add != null) {
+ if (add != null) {
buttonPanel.add(addParam);
}
- if(edit != null) {
+ if (edit != null) {
buttonPanel.add(editParam);
}
- if(remove != null) {
+ if (remove != null) {
buttonPanel.add(removeParam);
}
diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java
index 301a183..65c533d 100644
--- a/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java
@@ -24,16 +24,16 @@ public class SimpleInputPanel extends JPanel {
* Create a new input panel
*
* @param label
- * The label for the field
+ * The label for the field
* @param columns
- * The number of columns of text input to take
+ * The number of columns of text input to take
*/
public SimpleInputPanel(final String label, final int columns) {
setLayout(new BorderLayout());
final JLabel inputLabel = new JLabel(label);
- if(columns < 1) {
+ if (columns < 1) {
inputValue = new JTextField();
} else {
inputValue = new JTextField(columns);
diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java
index 628d146..d4dda55 100644
--- a/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java
@@ -24,11 +24,12 @@ import bjc.utils.gui.layout.HLayout;
public class SimpleListPanel extends JPanel {
private static final long serialVersionUID = 2719963952350133541L;
- private static void addItem(final DefaultListModel<String> model, final Predicate<String> verifier,
- final Consumer<String> onFailure, final JTextField addItemField) {
+ private static void addItem(final DefaultListModel<String> model,
+ final Predicate<String> verifier, final Consumer<String> onFailure,
+ final JTextField addItemField) {
final String potentialItem = addItemField.getText();
- if(verifier == null || verifier.test(potentialItem)) {
+ if (verifier == null || verifier.test(potentialItem)) {
model.addElement(potentialItem);
} else {
onFailure.accept(potentialItem);
@@ -41,13 +42,13 @@ public class SimpleListPanel extends JPanel {
* Create a new list panel
*
* @param type
- * The type of things in the list
+ * The type of things in the list
* @param model
- * The model to put items into
+ * The model to put items into
* @param verifier
- * The predicate to use to verify items
+ * The predicate to use to verify items
* @param onFailure
- * The function to call when an item doesn't verify
+ * The function to call when an item doesn't verify
*/
public SimpleListPanel(final String type, final DefaultListModel<String> model,
final Predicate<String> verifier, final Consumer<String> onFailure) {
@@ -72,15 +73,15 @@ public class SimpleListPanel extends JPanel {
final JButton removeItemButton = new JButton("Remove " + type);
- addItemButton.addActionListener((ev) -> {
+ addItemButton.addActionListener(ev -> {
addItem(model, verifier, onFailure, addItemField);
});
- addItemField.addActionListener((ev) -> {
+ addItemField.addActionListener(ev -> {
addItem(model, verifier, onFailure, addItemField);
});
- removeItemButton.addActionListener((ev) -> {
+ removeItemButton.addActionListener(ev -> {
model.remove(itemList.getSelectedIndex());
});
diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java
index 2628c39..8ca6f2b 100644
--- a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java
@@ -25,9 +25,9 @@ public class SimpleSpinnerPanel extends JPanel {
* Create a new spinner panel
*
* @param label
- * The label for the spinner
+ * The label for the spinner
* @param model
- * The model to attach to the spinner
+ * The model to attach to the spinner
*/
public SimpleSpinnerPanel(final String label, final SpinnerModel model) {
setLayout(new BorderLayout());
diff --git a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java
index da87357..835513a 100644
--- a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java
+++ b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java
@@ -38,14 +38,15 @@ public class SliderInputPanel extends JPanel {
try {
final int val = Integer.parseInt(text);
- if(val < minValue)
+ if (val < minValue)
throw new ParseException("Value must be greater than " + minValue, 0);
- else if(val > maxValue)
+ else if (val > maxValue)
throw new ParseException("Value must be smaller than " + maxValue, 0);
else
return val;
- } catch(final NumberFormatException nfex) {
- final ParseException pex = new ParseException("Value must be a valid integer", 0);
+ } catch (final NumberFormatException nfex) {
+ final ParseException pex
+ = new ParseException("Value must be a valid integer", 0);
pex.initCause(nfex);
@@ -55,7 +56,8 @@ public class SliderInputPanel extends JPanel {
@Override
public String valueToString(final Object value) throws ParseException {
- if(value == null) return Integer.toString(initValue);
+ if (value == null)
+ return Integer.toString(initValue);
return Integer.toString((Integer) value);
}
@@ -83,13 +85,12 @@ public class SliderInputPanel extends JPanel {
public final int initValue;
/**
- * Create a new slider settings, with the initial value in the
- * middle
+ * Create a new slider settings, with the initial value in the middle
*
* @param min
- * The minimum value of the slider
+ * The minimum value of the slider
* @param max
- * The maximum value of the slider
+ * The maximum value of the slider
*/
public SliderSettings(final int min, final int max) {
this(min, max, (min + max) / 2);
@@ -99,11 +100,11 @@ public class SliderInputPanel extends JPanel {
* Create a new set of slider sttings
*
* @param min
- * The minimum slider value
+ * The minimum slider value
* @param max
- * The maximum slider value
+ * The maximum slider value
* @param init
- * Th initial slider value
+ * Th initial slider value
*/
public SliderSettings(final int min, final int max, final int init) {
minValue = min;
@@ -121,18 +122,18 @@ public class SliderInputPanel extends JPanel {
* Create a new slider input panel
*
* @param lab
- * The label for the field
+ * The label for the field
* @param settings
- * The settings for slider values
+ * The settings for slider values
* @param majorTick
- * The setting for where to place big ticks
+ * The setting for where to place big ticks
* @param minorTick
- * The setting for where to place small ticks
+ * The setting for where to place small ticks
* @param action
- * The action to execute for a given value
+ * The action to execute for a given value
*/
- public SliderInputPanel(final String lab, final SliderSettings settings, final int majorTick,
- final int minorTick, final Consumer<Integer> action) {
+ public SliderInputPanel(final String lab, final SliderSettings settings,
+ final int majorTick, final int minorTick, final Consumer<Integer> action) {
setLayout(new HLayout(3));
final JLabel label = new JLabel(lab);
@@ -145,8 +146,8 @@ public class SliderInputPanel extends JPanel {
slider.setPaintTicks(true);
slider.setPaintLabels(true);
- slider.addChangeListener((event) -> {
- if(slider.getValueIsAdjusting()) {
+ slider.addChangeListener(event -> {
+ if (slider.getValueIsAdjusting()) {
// Do nothing
} else {
final int val = slider.getValue();
@@ -159,10 +160,10 @@ public class SliderInputPanel extends JPanel {
field.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
field.setColumns(15);
- field.addPropertyChangeListener("value", (event) -> {
+ field.addPropertyChangeListener("value", event -> {
final Object value = field.getValue();
- if(value == null) {
+ if (value == null) {
// Do nothing
} else {
slider.setValue((Integer) value);
@@ -178,7 +179,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
+ * The value to reset the fields to
*/
public void resetValues(final int value) {
slider.setValue(value);
diff --git a/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java b/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java
index e66ac75..735dd3a 100644
--- a/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java
+++ b/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java
@@ -7,10 +7,10 @@ import java.util.regex.Pattern;
/**
* Splits a string on a delimiter, respecting grouping delimiters.
- *
+ *
* By default, grouping delimiters are (), [], {}, and <>, as well as single and
* double quoted strings.
- *
+ *
* @author bjculkin
*
*/
@@ -23,13 +23,12 @@ public class LevelSplitter {
/**
* Check if a string contains any one of a specified number of things,
* respecting groups.
- *
+ *
* @param haystack
- * The string to look in.
+ * The string to look in.
* @param needles
- * The strings to look for.
- * @return Whether or not any of the strings were contained outside of
- * groups.
+ * The strings to look for.
+ * @return Whether or not any of the strings were contained outside of groups.
*/
public boolean levelContains(String haystack, String... needles) {
int nestLevel = 0;
@@ -43,7 +42,9 @@ public class LevelSplitter {
while (i < haystack.length()) {
if (inString == false && nestLevel == 0) {
for (String needle : needles) {
- if (haystack.regionMatches(i, needle, 0, needle.length())) { return true; }
+ if (haystack.regionMatches(i, needle, 0, needle.length())) {
+ return true;
+ }
}
}
@@ -86,13 +87,13 @@ public class LevelSplitter {
/**
* Split a string, respecting groups.
- *
+ *
* @param phrase
- * The string to split.
+ * The string to split.
* @param splits
- * The strings to split on.
- * @return A list of split strings. If keepDelims is true, it also
- * includes the delimiters in between the split strings.
+ * The strings to split on.
+ * @return A list of split strings. If keepDelims is true, it also includes the
+ * delimiters in between the split strings.
*/
public List<String> levelSplit(String phrase, String... splits) {
return levelSplit(phrase, false, splits);
@@ -100,16 +101,15 @@ public class LevelSplitter {
/**
* Split a string, respecting groups.
- *
+ *
* @param phrase
- * The string to split.
+ * The string to split.
* @param keepDelims
- * Whether or not to include the delimiters in the
- * results.
+ * Whether or not to include the delimiters in the results.
* @param splits
- * The strings to split on.
- * @return A list of split strings. If keepDelims is true, it also
- * includes the delimiters in between the split strings.
+ * The strings to split on.
+ * @return A list of split strings. If keepDelims is true, it also includes the
+ * delimiters in between the split strings.
*/
public List<String> levelSplit(String phrase, boolean keepDelims, String... splits) {
String work = phrase;
@@ -137,7 +137,8 @@ public class LevelSplitter {
if (work.regionMatches(i, split, 0, split.length())) {
strangs.add(work.substring(0, i));
- if (keepDelims) strangs.add(split);
+ if (keepDelims)
+ strangs.add(split);
work = work.substring(i + split.length());
i = 0;
@@ -157,8 +158,8 @@ public class LevelSplitter {
/*
* @TODO Ben Culkin 9/4/18
*
- * This currently crashes if the string ends
- * with one of the delimiters in question.
+ * This currently crashes if the string ends with one of the delimiters in
+ * question.
*/
switch (work.charAt(i)) {
case '\'':
@@ -226,9 +227,10 @@ public class LevelSplitter {
if (mat.lookingAt()) {
strangs.add(phrase.substring(lastMatch, mat.start()));
- if (keepDelims) strangs.add(mat.group());
+ if (keepDelims)
+ strangs.add(mat.group());
lastMatch = mat.end();
- //work = work.substring(mat.end());
+ // work = work.substring(mat.end());
// i = 0;
// mat = pat.matcher(work);
diff --git a/base/src/main/java/bjc/utils/ioutils/LineReader.java b/base/src/main/java/bjc/utils/ioutils/LineReader.java
index 7449670..9a5167d 100644
--- a/base/src/main/java/bjc/utils/ioutils/LineReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/LineReader.java
@@ -4,6 +4,7 @@ import java.util.Scanner;
/**
* A line reader
+ *
* @author bjculkin
*
*/
@@ -14,6 +15,6 @@ public class LineReader implements AutoCloseable {
public void close() {
scn.close();
}
-
+
// @TODO Implement me - ben, 1/6/20
}
diff --git a/base/src/main/java/bjc/utils/ioutils/MirrorDB.java b/base/src/main/java/bjc/utils/ioutils/MirrorDB.java
index 1010fd6..6518d56 100644
--- a/base/src/main/java/bjc/utils/ioutils/MirrorDB.java
+++ b/base/src/main/java/bjc/utils/ioutils/MirrorDB.java
@@ -13,7 +13,7 @@ import java.util.Scanner;
/**
* A database for describing mirrored characters.
- *
+ *
* @author bjculkin
*
*/
@@ -57,9 +57,9 @@ public class MirrorDB {
/**
* Check if a string can be mirrored.
- *
+ *
* @param mir
- * The string to check for mirroring.
+ * The string to check for mirroring.
* @return Whether or not the given string can be mirrored.
*/
public boolean canMirror(String mir) {
@@ -68,9 +68,9 @@ public class MirrorDB {
/**
* Mirror a string.
- *
+ *
* @param mir
- * The string to mirror.
+ * The string to mirror.
* @return The mirrored version of the string.
*/
public String mirror(String mir) {
diff --git a/base/src/main/java/bjc/utils/ioutils/Prompter.java b/base/src/main/java/bjc/utils/ioutils/Prompter.java
index f39020d..352e55b 100644
--- a/base/src/main/java/bjc/utils/ioutils/Prompter.java
+++ b/base/src/main/java/bjc/utils/ioutils/Prompter.java
@@ -19,10 +19,10 @@ public final class Prompter implements Runnable {
* Create a new prompter using the specified prompt.
*
* @param prompt
- * The prompt to present.
+ * The prompt to present.
*
* @param output
- * The stream to print the prompt on.
+ * The stream to print the prompt on.
*/
public Prompter(final String prompt, final PrintStream output) {
promt = prompt;
@@ -34,7 +34,7 @@ public final class Prompter implements Runnable {
* Set the prompt this prompter uses.
*
* @param prompt
- * The prompt this prompter uses.
+ * The prompt this prompter uses.
*/
public void setPrompt(final String prompt) {
promt = prompt;
diff --git a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java
index 83672e6..3dad724 100644
--- a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java
+++ b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java
@@ -21,39 +21,40 @@ public class RegexStringEditor {
private static final UnaryOperator<String> SID = ID.id();
/**
- * Replace every occurrence of the pattern with the result of applying
- * the action to the string matched by the pattern.
+ * Replace every occurrence of the pattern with the result of applying the
+ * action to the string matched by the pattern.
*
* @param input
- * The input string to process.
+ * The input string to process.
*
* @param patt
- * The pattern to match the string against.
+ * The pattern to match the string against.
*
* @param action
- * The action to transform matches with.
+ * The action to transform matches with.
*
* @return The string, with matches replaced with the action.
*/
- public static String onOccurances(final String input, final Pattern patt, final UnaryOperator<String> action) {
+ public static String onOccurances(final String input, final Pattern patt,
+ final UnaryOperator<String> action) {
return reduceOccurances(input, patt, SID, action);
}
/**
- * Replace every occurrence between the patterns with the result of
- * applying the action to the strings between the patterns.
+ * Replace every occurrence between the patterns with the result of applying the
+ * action to the strings between the patterns.
*
* @param input
- * The input string to process.
+ * The input string to process.
*
* @param patt
- * The pattern to match the string against.
+ * The pattern to match the string against.
*
* @param action
- * The action to transform matches with.
+ * The action to transform matches with.
*
- * @return The string, with strings between the matches replaced with
- * the action.
+ * @return The string, with strings between the matches replaced with the
+ * action.
*/
public static String betweenOccurances(final String input, final Pattern patt,
final UnaryOperator<String> action) {
@@ -64,21 +65,22 @@ public class RegexStringEditor {
* Execute actions between and on matches of a regular expression.
*
* @param input
- * The input string.
+ * The input string.
*
* @param rPatt
- * The pattern to match against the string.
+ * The pattern to match against the string.
*
* @param betweenAction
- * The function to execute between matches of the string.
+ * The function to execute between matches of the string.
*
* @param onAction
- * The function to execute on matches of the string.
+ * The function to execute on matches of the string.
*
* @return The string, with both actions applied.
*/
public static String reduceOccurances(final String input, final Pattern rPatt,
- final UnaryOperator<String> betweenAction, final UnaryOperator<String> onAction) {
+ final UnaryOperator<String> betweenAction,
+ final UnaryOperator<String> onAction) {
/*
* Get all of the occurances.
*/
@@ -87,36 +89,38 @@ public class RegexStringEditor {
/*
* Execute the correct action on every occurance.
*/
- final Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction);
- final BiFunction<String, StringBuilder, StringBuilder> reducer = (strang, state) -> {
- return state.append(actions.get().apply(strang));
- };
+ final Toggle<UnaryOperator<String>> actions
+ = new ValueToggle<>(onAction, betweenAction);
+ final BiFunction<String, StringBuilder, StringBuilder> reducer
+ = (strang, state) -> state.append(actions.get().apply(strang));
/*
* Convert the list back to a string.
*/
- return occurances.reduceAux(new StringBuilder(), reducer, StringBuilder::toString);
+ return occurances.reduceAux(new StringBuilder(), reducer,
+ StringBuilder::toString);
}
/**
* Execute actions between and on matches of a regular expression.
*
* @param input
- * The input string.
+ * The input string.
*
* @param rPatt
- * The pattern to match against the string.
+ * The pattern to match against the string.
*
* @param betweenAction
- * The function to execute between matches of the string.
+ * The function to execute between matches of the string.
*
* @param onAction
- * The function to execute on matches of the string.
+ * The function to execute on matches of the string.
*
* @return The string, with both actions applied.
*/
public static IList<String> mapOccurances(final String input, final Pattern rPatt,
- final UnaryOperator<String> betweenAction, final UnaryOperator<String> onAction) {
+ final UnaryOperator<String> betweenAction,
+ final UnaryOperator<String> onAction) {
/*
* Get all of the occurances.
*/
@@ -125,7 +129,8 @@ public class RegexStringEditor {
/*
* Execute the correct action on every occurance.
*/
- final Toggle<UnaryOperator<String>> actions = new ValueToggle<>(onAction, betweenAction);
+ final Toggle<UnaryOperator<String>> actions
+ = new ValueToggle<>(onAction, betweenAction);
return occurances.map(strang -> actions.get().apply(strang));
}
@@ -133,13 +138,13 @@ public class RegexStringEditor {
* Separate a string into match/non-match segments.
*
* @param input
- * The string to separate.
+ * The string to separate.
*
* @param rPatt
- * The pattern to use for separation.
+ * The pattern to use for separation.
*
- * @return The string, as a list of match/non-match segments,
- * starting/ending with a non-match segment.
+ * @return The string, as a list of match/non-match segments, starting/ending
+ * with a non-match segment.
*/
public static IList<String> listOccurances(final String input, final Pattern rPatt) {
final IList<String> res = new FunctionalList<>();
@@ -153,7 +158,7 @@ public class RegexStringEditor {
/*
* For every match.
*/
- while(matcher.find()) {
+ while (matcher.find()) {
final String match = matcher.group();
/*
@@ -183,20 +188,21 @@ public class RegexStringEditor {
* Apply an operation to a string if it matches a regular expression.
*
* @param input
- * The input string.
+ * The input string.
*
* @param patt
- * The pattern to match against it.
+ * The pattern to match against it.
*
* @param action
- * The action to execute if it matches.
+ * The action to execute if it matches.
*
* @return The string, modified by the action if the pattern matched.
*/
- public static String ifMatches(final String input, final Pattern patt, final UnaryOperator<String> action) {
+ public static String ifMatches(final String input, final Pattern patt,
+ final UnaryOperator<String> action) {
final Matcher matcher = patt.matcher(input);
- if(matcher.matches()) {
+ if (matcher.matches()) {
return action.apply(input);
}
@@ -207,21 +213,21 @@ public class RegexStringEditor {
* Apply an operation to a string if it doesn't match a regular expression.
*
* @param input
- * The input string.
+ * The input string.
*
* @param patt
- * The pattern to match against it.
+ * The pattern to match against it.
*
* @param action
- * The action to execute if it doesn't match.
+ * The action to execute if it doesn't match.
*
- * @return The string, modified by the action if the pattern didn't
- * match.
+ * @return The string, modified by the action if the pattern didn't match.
*/
- public static String ifNotMatches(final String input, final Pattern patt, final UnaryOperator<String> action) {
+ public static String ifNotMatches(final String input, final Pattern patt,
+ final UnaryOperator<String> action) {
final Matcher matcher = patt.matcher(input);
- if(matcher.matches()) {
+ if (matcher.matches()) {
return input;
}
diff --git a/base/src/main/java/bjc/utils/ioutils/ReportWriter.java b/base/src/main/java/bjc/utils/ioutils/ReportWriter.java
index d340ffb..95a7f6d 100644
--- a/base/src/main/java/bjc/utils/ioutils/ReportWriter.java
+++ b/base/src/main/java/bjc/utils/ioutils/ReportWriter.java
@@ -9,7 +9,7 @@ import bjc.esodata.DefaultList;
/**
* A writer with support for some formatting operations, such as autoindentation
* and pagination.
- *
+ *
* @author bjculkin
*
*/
@@ -82,7 +82,7 @@ public class ReportWriter extends Writer {
/**
* Get the current indent level.
- *
+ *
* @return The current indent level.
*/
public int getLevel() {
@@ -91,10 +91,10 @@ public class ReportWriter extends Writer {
/**
* Get the current line-spacing.
- *
- * This is the number of blank lines to print out every time a blank
- * line is encountered in the input, and is set to 1 by default.
- *
+ *
+ * This is the number of blank lines to print out every time a blank line is
+ * encountered in the input, and is set to 1 by default.
+ *
* @return The current line spacing.
*/
public int getLineSpacing() {
@@ -103,7 +103,7 @@ public class ReportWriter extends Writer {
/**
* Get the current line on the page.
- *
+ *
* @return The current line on the page.
*/
public int getPageLine() {
@@ -112,7 +112,7 @@ public class ReportWriter extends Writer {
/**
* Get the current page number.
- *
+ *
* @return The current page number.
*/
public int getPageNum() {
@@ -121,7 +121,7 @@ public class ReportWriter extends Writer {
/**
* Get the number of lines per page.
- *
+ *
* @return The number of lines per page.
*/
public int getLinesPerPage() {
@@ -130,9 +130,9 @@ public class ReportWriter extends Writer {
/**
* Get the current indent position.
- *
+ *
* This is the count of columns the indentation occupies.
- *
+ *
* @return The current indent position.
*/
public int getIndentPos() {
@@ -141,7 +141,7 @@ public class ReportWriter extends Writer {
/**
* Get the string of the default indentation value.
- *
+ *
* @return The string for the default indentation value.
*/
public String getString() {
@@ -150,9 +150,9 @@ public class ReportWriter extends Writer {
/**
* Get the string of a specific indentation value.
- *
+ *
* @param lvl
- * The level to get the value for.
+ * The level to get the value for.
* @return The string for the specified indentation value.
*/
public String getString(int lvl) {
@@ -161,7 +161,7 @@ public class ReportWriter extends Writer {
/**
* Get the number of spaces to a tab.
- *
+ *
* @return The number of spaces to a tab.
*/
public int getTabEqv() {
@@ -170,7 +170,7 @@ public class ReportWriter extends Writer {
/**
* Get the total number of lines written.
- *
+ *
* @return The total number of lines written.
*/
public int getLinesWritter() {
@@ -179,7 +179,7 @@ public class ReportWriter extends Writer {
/**
* Get the current position in the line.
- *
+ *
* @return The current position in the line.
*/
public int getLinePos() {
@@ -188,7 +188,7 @@ public class ReportWriter extends Writer {
/**
* Get the last character printed.
- *
+ *
* @return The last character printed.
*/
public char getLastChar() {
@@ -197,7 +197,7 @@ public class ReportWriter extends Writer {
/**
* Get the contained writer.
- *
+ *
* @return The contained writer.
*/
public Writer getWriter() {
@@ -206,7 +206,7 @@ public class ReportWriter extends Writer {
/**
* Check if the last character was a newline.
- *
+ *
* @return Was the last character a new line?
*/
public boolean isLastCharNL() {
@@ -215,7 +215,7 @@ public class ReportWriter extends Writer {
/**
* Check if tabs are being printed as spaces.
- *
+ *
* @return Are tabs being printed as spaces?
*/
public boolean isPrintingTabsAsSpaces() {
@@ -224,10 +224,9 @@ public class ReportWriter extends Writer {
/**
* Set the line spacing.
- *
+ *
* @param spacing
- * The number of lines to print for every blank line
- * encountered.
+ * The number of lines to print for every blank line encountered.
*/
public void setLineSpacing(int spacing) {
lineSpacing = spacing;
@@ -235,9 +234,9 @@ public class ReportWriter extends Writer {
/**
* Set whether tabs are being printed as spaces.
- *
+ *
* @param tabsAsSpaces
- * Whether to print tabs as spaces.
+ * Whether to print tabs as spaces.
*/
public void setPrintTabsAsSpaces(boolean tabsAsSpaces) {
printTabsAsSpaces = tabsAsSpaces;
@@ -248,9 +247,9 @@ public class ReportWriter extends Writer {
/**
* Set the number of lines per page.
- *
+ *
* @param lines
- * The number of lines per page.
+ * The number of lines per page.
*/
public void setLinesPerPage(int lines) {
linesPerPage = lines;
@@ -273,9 +272,9 @@ public class ReportWriter extends Writer {
/**
* Set the current indentation level.
- *
+ *
* @param level
- * The indentation level.
+ * The indentation level.
*/
public void setLevel(int level) {
indentLevel = level;
@@ -283,9 +282,9 @@ public class ReportWriter extends Writer {
/**
* Set the current amount of spaces per tab.
- *
+ *
* @param eqv
- * The amount of spaces per tab.
+ * The amount of spaces per tab.
*/
public void setTabEqv(int eqv) {
tabEqv = eqv;
@@ -302,12 +301,12 @@ public class ReportWriter extends Writer {
/**
* Set the default indentation string to use.
- *
- * NOTE: Using a string that contains a newline may cause weirdness of
- * various sorts to happen.
- *
+ *
+ * NOTE: Using a string that contains a newline may cause weirdness of various
+ * sorts to happen.
+ *
* @param str
- * The string to use for default indentation.
+ * The string to use for default indentation.
*/
public void setString(String str) {
defIVal.indentStr = str;
@@ -317,11 +316,11 @@ public class ReportWriter extends Writer {
/**
* Set the indentation string for a specific indentation level.
- *
+ *
* @param lvl
- * The level to set the indentation string for.
+ * The level to set the indentation string for.
* @param str
- * The indentation string to use.
+ * The indentation string to use.
*/
public void setString(int lvl, String str) {
iVals.get(lvl).indentStr = str;
@@ -336,11 +335,11 @@ public class ReportWriter extends Writer {
// Pass -2 to refresh the default index
/**
* Refresh the indentation settings.
- *
+ *
* @param lvl
- * The level of indents to refresh. Passing a number >= 0
- * refreshes that level, -1 refreshes every level, and -2
- * refreshes just the default indentation.
+ * The level of indents to refresh. Passing a number >= 0 refreshes
+ * that level, -1 refreshes every level, and -2 refreshes just the
+ * default indentation.
*/
private void refreshIndents(int lvl) {
if (lvl == -2) {
@@ -349,7 +348,7 @@ public class ReportWriter extends Writer {
for (IndentVal ival : iVals) {
refreshIndent(ival);
}
-
+
refreshIndent(defIVal);
} else {
refreshIndent(iVals.get(lvl));
@@ -382,8 +381,11 @@ public class ReportWriter extends Writer {
/**
* Duplicate this writers settings.
- * @param contents The internal writer to use.
- * @return A new writer, sharing this ones settings, but writing to the provided Writer instead.
+ *
+ * @param contents
+ * The internal writer to use.
+ * @return A new writer, sharing this ones settings, but writing to the provided
+ * Writer instead.
*/
public ReportWriter duplicate(Writer contents) {
ReportWriter rw = new ReportWriter(contents);
@@ -417,9 +419,12 @@ public class ReportWriter extends Writer {
public ReportWriter() {
this(new StringWriter());
}
+
/**
* Create a new ReportWriter.
- * @param write The place to write to.
+ *
+ * @param write
+ * The place to write to.
*/
public ReportWriter(Writer write) {
this(write, 0, "\t");
@@ -427,9 +432,13 @@ public class ReportWriter extends Writer {
/**
* Create a new ReportWriter with the specified default indentation values.
- * @param write The place to write to.
- * @param level The current indentation level.
- * @param indentStr The indentation string.
+ *
+ * @param write
+ * The place to write to.
+ * @param level
+ * The current indentation level.
+ * @param indentStr
+ * The indentation string.
*/
public ReportWriter(Writer write, int level, String indentStr) {
super();
@@ -446,7 +455,9 @@ public class ReportWriter extends Writer {
/**
* Indent a specific number of levels.
- * @param lvl The number of levels to indent.
+ *
+ * @param lvl
+ * The number of levels to indent.
*/
public void indent(int lvl) {
indentLevel += lvl;
@@ -461,7 +472,9 @@ public class ReportWriter extends Writer {
/**
* Dedent a specific number of levels.
- * @param lvl The number of levels to dedent.
+ *
+ * @param lvl
+ * The number of levels to dedent.
*/
public void dedent(int lvl) {
// @NOTE 9/5/18
@@ -480,8 +493,11 @@ public class ReportWriter extends Writer {
/**
* Writes a buffer to the output, then clears it.
- * @param sb The buffer to write and clear.
- * @throws IOException If something goes wrong writing the buffer.
+ *
+ * @param sb
+ * The buffer to write and clear.
+ * @throws IOException
+ * If something goes wrong writing the buffer.
*/
public void writeBuffer(StringBuffer sb) throws IOException {
write(sb.toString());
@@ -514,7 +530,8 @@ public class ReportWriter extends Writer {
// If we're printing CRLF pairs, make sure that we don't
// print incomplete pairs.
if (i < lineSpacing - 1) {
- if (c == '\n' && lastChar == '\r') contained.write('\r');
+ if (c == '\n' && lastChar == '\r')
+ contained.write('\r');
}
}
@@ -532,7 +549,8 @@ public class ReportWriter extends Writer {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
// Skip empty writes
- if (len == 0) return;
+ if (len == 0)
+ return;
// Last character was a new line, print the indent string
if (lastCharWasNL) {
@@ -546,7 +564,7 @@ public class ReportWriter extends Writer {
char c = cbuf[idx];
- if ((c == '\n' && lastChar != '\r') || c == '\n' || c == '\r' || c == '\f') {
+ if ((c == '\n' && lastChar != '\r') || c == '\n' || c == '\r' || c == '\f') {
writeNL(c);
} else {
if (lastCharWasNL) {
@@ -577,7 +595,8 @@ public class ReportWriter extends Writer {
if (printTabsAsSpaces)
contained.write(ival.indentStrSpacedTabs);
- else contained.write(ival.indentStr);
+ else
+ contained.write(ival.indentStr);
linePos += ival.indentStrPos;
indentPos += ival.indentStrPos;
diff --git a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java
index 2ee25d1..88a3b81 100644
--- a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java
@@ -22,7 +22,7 @@ import bjc.funcdata.IMap;
* @author ben
*
* @param <E>
- * The type of the state object to use
+ * The type of the state object to use
*
*/
public class RuleBasedConfigReader<E> {
@@ -58,14 +58,16 @@ public class RuleBasedConfigReader<E> {
* Create a new rule-based config reader
*
* @param start
- * The action to fire when starting a rule
+ * The action to fire when starting a rule
* @param continueRule
- * The action to fire when continuing a rule
+ * The action to fire when continuing a rule
* @param end
- * The action to fire when ending a rule
+ * The action to fire when ending a rule
*/
- public RuleBasedConfigReader(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start,
- final BiConsumer<FunctionalStringTokenizer, E> continueRule, final Consumer<E> end) {
+ public RuleBasedConfigReader(
+ final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start,
+ final BiConsumer<FunctionalStringTokenizer, E> continueRule,
+ final Consumer<E> end) {
this.start = start;
this.continueRule = continueRule;
this.end = end;
@@ -77,25 +79,28 @@ public class RuleBasedConfigReader<E> {
* Add a pragma to this reader
*
* @param name
- * The name of the pragma to add
+ * The name of the pragma to add
* @param action
- * The function to execute when this pragma is read
+ * The function to execute when this pragma is read
*/
- public void addPragma(final String name, final BiConsumer<FunctionalStringTokenizer, E> action) {
- if(name == null)
+ public void addPragma(final String name,
+ final BiConsumer<FunctionalStringTokenizer, E> action) {
+ if (name == null)
throw new NullPointerException("Pragma name must not be null");
- else if(action == null)
+ else if (action == null)
throw new NullPointerException("Pragma action must not be null");
pragmas.put(name, action);
}
- private void continueRule(final E state, final boolean isRuleOpen, final String line) {
+ private void continueRule(final E state, final boolean isRuleOpen,
+ final String line) {
// Make sure our input is correct
- if(isRuleOpen == false)
+ if (isRuleOpen == false)
throw new InputMismatchException("Cannot continue rule with no rule open");
- else if(continueRule == null)
- throw new InputMismatchException("Rule continuation not supported for current grammar");
+ else if (continueRule == null)
+ throw new InputMismatchException(
+ "Rule continuation not supported for current grammar");
/*
* Accept the rule
@@ -107,7 +112,7 @@ public class RuleBasedConfigReader<E> {
/*
* Ignore blank line without an open rule
*/
- if(isRuleOpen == false) {
+ if (isRuleOpen == false) {
/*
* Do nothing
*/
@@ -117,7 +122,7 @@ public class RuleBasedConfigReader<E> {
/*
* Nothing happens on rule end
*/
- if(end != null) {
+ if (end != null) {
/*
* Process the rule ending
*/
@@ -134,13 +139,14 @@ public class RuleBasedConfigReader<E> {
* Run a stream through this reader
*
* @param input
- * The stream to get input
+ * The stream to get input
* @param initialState
- * The initial state of the reader
+ * The initial state of the reader
* @return The final state of the reader
*/
public E fromStream(final InputStream input, final 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
@@ -150,7 +156,7 @@ public class RuleBasedConfigReader<E> {
/*
* 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
@@ -160,27 +166,28 @@ public class RuleBasedConfigReader<E> {
/*
* Do something for every line of the file
*/
- source.forEachRemaining((line) -> {
+ 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")) {
/*
* Skip comment lines.
*/
- if(line.startsWith("#") || line.startsWith("//"))
+ if (line.startsWith("#") || line.startsWith("//"))
/*
- * It's a comment. */
+ * It's a comment.
+ */
return;
/*
@@ -206,9 +213,10 @@ public class RuleBasedConfigReader<E> {
* Set the action to execute when continuing a rule
*
* @param continueRule
- * The action to execute on continuation of a rule
+ * The action to execute on continuation of a rule
*/
- public void setContinueRule(final BiConsumer<FunctionalStringTokenizer, E> continueRule) {
+ public void
+ setContinueRule(final BiConsumer<FunctionalStringTokenizer, E> continueRule) {
this.continueRule = continueRule;
}
@@ -216,7 +224,7 @@ public class RuleBasedConfigReader<E> {
* Set the action to execute when ending a rule
*
* @param end
- * The action to execute on ending of a rule
+ * The action to execute on ending of a rule
*/
public void setEndRule(final Consumer<E> end) {
this.end = end;
@@ -226,10 +234,12 @@ public class RuleBasedConfigReader<E> {
* Set the action to execute when starting a rule
*
* @param start
- * The action to execute on starting of a rule
+ * The action to execute on starting of a rule
*/
- public void setStartRule(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) {
- if(start == null) throw new NullPointerException("Action on rule start must be non-null");
+ public void setStartRule(
+ final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) {
+ if (start == null)
+ throw new NullPointerException("Action on rule start must be non-null");
this.start = start;
}
@@ -238,7 +248,8 @@ public class RuleBasedConfigReader<E> {
/*
* Create the line tokenizer
*/
- final FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(line, " ");
+ final FunctionalStringTokenizer tokenizer
+ = new FunctionalStringTokenizer(line, " ");
/*
* Get the initial token
@@ -248,7 +259,7 @@ public class RuleBasedConfigReader<E> {
/*
* Handle pragmas
*/
- if(nextToken.equals("pragma")) {
+ if (nextToken.equals("pragma")) {
/*
* Get the pragma name
*/
@@ -264,8 +275,9 @@ public class RuleBasedConfigReader<E> {
/*
* Make sure input is correct
*/
- if(isRuleOpen == true)
- throw new InputMismatchException("Nested rules are currently not supported");
+ if (isRuleOpen == true)
+ throw new InputMismatchException(
+ "Nested rules are currently not supported");
/*
* Start a rule
diff --git a/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java
index 7e7550e..42a01a4 100644
--- a/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java
+++ b/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java
@@ -18,20 +18,21 @@ public class RuleBasedReaderPragmas {
* Creates a pragma that takes a single integer argument
*
* @param <StateType>
- * The type of state that goes along with this pragma
+ * The type of state that goes along with this pragma
* @param name
- * The name of this pragma, for error message purpose
+ * The name of this pragma, for error message purpose
* @param consumer
- * The function to invoke with the parsed integer
+ * The function to invoke with the parsed integer
* @return A pragma that functions as described above.
*/
- public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildInteger(final String name,
- final BiConsumer<Integer, StateType> consumer) {
+ public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType>
+ buildInteger(final String name,
+ final BiConsumer<Integer, StateType> consumer) {
return (tokenizer, state) -> {
/*
* Check our input is correct
*/
- if(!tokenizer.hasMoreTokens()) {
+ if (!tokenizer.hasMoreTokens()) {
String fmt = "Pragma %s requires one integer argument";
throw new PragmaFormatException(String.format(fmt, name));
@@ -47,14 +48,15 @@ public class RuleBasedReaderPragmas {
* Run the pragma
*/
consumer.accept(Integer.parseInt(token), state);
- } catch(final NumberFormatException nfex) {
+ } catch (final NumberFormatException nfex) {
/*
* Tell the user their argument isn't correct
*/
- String fmt = "Argument %s to %s pragma isn't a valid integer, and this pragma requires an integer argument.";
+ String fmt
+ = "Argument %s to %s pragma isn't a valid integer, and this pragma requires an integer argument.";
- final PragmaFormatException pfex = new PragmaFormatException(
- String.format(fmt, token, name));
+ final PragmaFormatException pfex
+ = new PragmaFormatException(String.format(fmt, token, name));
pfex.initCause(nfex);
@@ -64,24 +66,25 @@ public class RuleBasedReaderPragmas {
}
/**
- * Creates a pragma that takes any number of arguments and collapses
- * them all into a single string
+ * Creates a pragma that takes any number of arguments and collapses them all
+ * into a single string
*
* @param <StateType>
- * The type of state that goes along with this pragma
+ * The type of state that goes along with this pragma
* @param name
- * The name of this pragma, for error message purpose
+ * The name of this pragma, for error message purpose
* @param consumer
- * The function to invoke with the parsed string
+ * The function to invoke with the parsed string
* @return A pragma that functions as described above.
*/
- public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildStringCollapser(
- final String name, final BiConsumer<String, StateType> consumer) {
+ public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType>
+ buildStringCollapser(final String name,
+ final BiConsumer<String, StateType> consumer) {
return (tokenizer, state) -> {
/*
* Check our input
*/
- if(!tokenizer.hasMoreTokens()) {
+ if (!tokenizer.hasMoreTokens()) {
String fmt = "Pragma %s requires one or more string arguments.";
throw new PragmaFormatException(String.format(fmt, name));
diff --git a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java
index 3a07fbc..be8cda7 100644
--- a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java
+++ b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java
@@ -19,7 +19,7 @@ import java.util.Set;
public class SimpleProperties implements Map<String, String> {
/**
* Exception thrown when there is a duplicate key, when they are forbidden.
- *
+ *
* @author 15405
*
*/
@@ -28,22 +28,25 @@ public class SimpleProperties implements Map<String, String> {
/**
* Create a new duplicate key exception.
- *
+ *
* @param keyName
- * The name of the key that has been duplicated.
+ * The name of the key that has been duplicated.
*/
public DuplicateKeys(String keyName) {
super(String.format("Duplicate value encountered for key '%s'", keyName));
}
}
-
+
public static class InvalidLineFormat extends RuntimeException {
private static final long serialVersionUID = 5332131472090792841L;
-
+
public InvalidLineFormat(String lne) {
- super(String.format("Line '%s' is improperly formatted.\n\tExpected format is a string key, followed by a single space, followed by the value", ""));
+ super(String.format(
+ "Line '%s' is improperly formatted.\n\tExpected format is a string key, followed by a single space, followed by the value",
+ ""));
}
}
+
private final Map<String, String> props;
/**
@@ -52,22 +55,22 @@ public class SimpleProperties implements Map<String, String> {
public SimpleProperties() {
props = new HashMap<>();
}
-
+
/**
* Load properties from an input stream.
- *
- * Delegates to {@link SimpleProperties#loadFrom(Reader, boolean)} to allow
- * you to pass a input stream instead of a reader.
- *
- * @param is
- * The stream to read from.
+ *
+ * Delegates to {@link SimpleProperties#loadFrom(Reader, boolean)} to allow you
+ * to pass a input stream instead of a reader.
+ *
+ * @param is
+ * The stream to read from.
* @param allowDuplicates
- * Whether or not duplicate keys should be allowed.
+ * Whether or not duplicate keys should be allowed.
*/
public void loadFrom(final InputStream is, final boolean allowDuplicates) {
loadFrom(new InputStreamReader(is), allowDuplicates);
}
-
+
/**
* Load properties from the provided input reader.
*
@@ -76,23 +79,26 @@ public class SimpleProperties implements Map<String, String> {
* All leading/trailing spaces from the name &amp; body are removed.
*
* @param rdr
- * The reader to read from.
+ * The reader to read from.
*
* @param allowDuplicates
- * Whether or not duplicate keys should be allowed. If they are,
- * the end-value of the property will be what the last one was.
- *
- * @throws DuplicateKeys If duplicate keys have been found when they are prohibited.
+ * Whether or not duplicate keys should be allowed. If
+ * they are, the end-value of the property will be what
+ * the last one was.
+ *
+ * @throws DuplicateKeys
+ * If duplicate keys have been found when they are
+ * prohibited.
*/
public void loadFrom(final Reader rdr, final boolean allowDuplicates) {
- try(Scanner scn = new Scanner(rdr)) {
- while(scn.hasNextLine()) {
+ try (Scanner scn = new Scanner(rdr)) {
+ while (scn.hasNextLine()) {
final String ln = scn.nextLine().trim();
/*
* Skip blank lines/comments
*/
- if(ln.equals("") || ln.startsWith("#")) {
+ if (ln.equals("") || ln.startsWith("#")) {
continue;
}
@@ -101,7 +107,7 @@ public class SimpleProperties implements Map<String, String> {
/*
* Complain about improperly formatted lines.
*/
- if(sepIdx == -1) {
+ if (sepIdx == -1) {
throw new InvalidLineFormat(ln);
}
@@ -111,7 +117,7 @@ public class SimpleProperties implements Map<String, String> {
/*
* Complain about duplicates, if that is wanted.
*/
- if(!allowDuplicates && containsKey(name)) {
+ if (!allowDuplicates && containsKey(name)) {
throw new DuplicateKeys(name);
}
@@ -122,7 +128,7 @@ public class SimpleProperties implements Map<String, String> {
/**
* Output the set of read properties.
- *
+ *
* Uses System.out, since one isn't specified.
*/
public void outputProperties() {
@@ -131,13 +137,14 @@ public class SimpleProperties implements Map<String, String> {
/**
* Output the set of read properties.
- *
- * @param strim The stream to output properties to.
+ *
+ * @param strim
+ * The stream to output properties to.
*/
public void outputProperties(PrintStream strim) {
strim.println("Read properties:");
- for(final Entry<String, String> entry : entrySet()) {
+ for (final Entry<String, String> entry : entrySet()) {
strim.printf("\t'%s'\t'%s'\n", entry.getKey(), entry.getValue());
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/Block.java b/base/src/main/java/bjc/utils/ioutils/blocks/Block.java
index bf0257e..b8c611b 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/Block.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/Block.java
@@ -29,10 +29,10 @@ public class Block {
/**
* The line offset number for this block.
- *
- * Essentially, this is the absolute number of lines that this block is
- * into whatever source it came from, where as startLine and endLine are
- * relative to the BlockReader this Block is from.
+ *
+ * Essentially, this is the absolute number of lines that this block is into
+ * whatever source it came from, where as startLine and endLine are relative to
+ * the BlockReader this Block is from.
*/
public int lineOffset;
@@ -40,15 +40,16 @@ public class Block {
* Create a new block.
*
* @param blockNo
- * The number of this block.
+ * The number of this block.
* @param contents
- * The contents of this block.
+ * The contents of this block.
* @param startLine
- * The line this block started on.
+ * The line this block started on.
* @param endLine
- * The line this block ended.
+ * The line this block ended.
*/
- public Block(final int blockNo, final String contents, final int startLine, final int endLine) {
+ public Block(final int blockNo, final String contents, final int startLine,
+ final int endLine) {
this.contents = contents;
this.startLine = startLine;
this.endLine = endLine;
@@ -58,12 +59,13 @@ public class Block {
@Override
public String toString() {
if (lineOffset != -1) {
- String fmt = "Block #%d (from lines %d (%d) to %d (%d)), length: %d characters";
+ String fmt
+ = "Block #%d (from lines %d (%d) to %d (%d)), length: %d characters";
- return String.format(fmt, blockNo, startLine + lineOffset, startLine, endLine + lineOffset,
- endLine + lineOffset, contents.length());
+ return String.format(fmt, blockNo, startLine + lineOffset, startLine,
+ endLine + lineOffset, endLine + lineOffset, contents.length());
}
-
+
String fmt = "Block #%d (from lines %d to %d), length: %d characters";
return String.format(fmt, blockNo, startLine, endLine, contents.length());
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java
index c6d709c..f111244 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java
@@ -51,10 +51,10 @@ public interface BlockReader extends AutoCloseable, Iterator<Block>, Iterable<Bl
* Execute an action for each remaining block.
*
* @param action
- * The action to execute for each block
+ * The action to execute for each block
*/
default void forEachBlock(final Consumer<Block> action) {
- while(hasNext()) {
+ while (hasNext()) {
action.accept(next());
}
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java
index f1dfc3c..615af85 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java
@@ -13,10 +13,10 @@ public class BlockReaders {
* Create a new simple block reader that works off a regex.
*
* @param blockDelim
- * The regex that separates blocks.
+ * The regex that separates blocks.
*
* @param source
- * The reader to get blocks from.
+ * The reader to get blocks from.
*
* @return A configured simple reader.
*/
@@ -28,7 +28,7 @@ public class BlockReaders {
* Create a new pushback block reader.
*
* @param src
- * The block reader to read blocks from.
+ * The block reader to read blocks from.
*
* @return A configured pushback reader.
*/
@@ -40,10 +40,10 @@ public class BlockReaders {
* Create a new triggered block reader.
*
* @param source
- * The block reader to read blocks from.
+ * The block reader to read blocks from.
*
* @param action
- * The action to execute before reading a block.
+ * The action to execute before reading a block.
*
* @return A configured triggered block reader.
*/
@@ -55,14 +55,15 @@ public class BlockReaders {
* Create a new layered block reader.
*
* @param primary
- * The first source to read blocks from.
+ * The first source to read blocks from.
*
* @param secondary
- * The second source to read blocks from.
+ * The second source to read blocks from.
*
* @return A configured layered block reader.
*/
- public static BlockReader layered(final BlockReader primary, final BlockReader secondary) {
+ public static BlockReader layered(final BlockReader primary,
+ final BlockReader secondary) {
return new LayeredBlockReader(primary, secondary);
}
@@ -70,7 +71,7 @@ public class BlockReaders {
* Create a new serial block reader.
*
* @param readers
- * The readers to pull from, in the order to pull from them.
+ * The readers to pull from, in the order to pull from them.
*
* @return A configured serial block reader.
*/
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/BoundBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/BoundBlockReader.java
index ba2c7ab..0bd0991 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/BoundBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/BoundBlockReader.java
@@ -6,14 +6,14 @@ import java.util.function.Supplier;
/**
* A block reader composed from functions.
- *
+ *
* @author EVE
*
*/
public class BoundBlockReader implements BlockReader {
/**
* A function that serves to close an I/O source.
- *
+ *
* @author EVE
*
*/
@@ -21,9 +21,9 @@ public class BoundBlockReader implements BlockReader {
public interface Closer {
/**
* Close the I/O source this is attached to.
- *
+ *
* @throws IOException
- * If something goes wrong
+ * If something goes wrong
*/
public void close() throws IOException;
}
@@ -38,15 +38,16 @@ public class BoundBlockReader implements BlockReader {
/**
* Create a new bound block reader.
- *
+ *
* @param blockChecker
- * Predicate for checking if a block is available
+ * Predicate for checking if a block is available
* @param blockGetter
- * Function to retrieve a block
+ * Function to retrieve a block
* @param blockCloser
- * Function to close a block source
+ * Function to close a block source
*/
- public BoundBlockReader(BooleanSupplier blockChecker, Supplier<Block> blockGetter, Closer blockCloser) {
+ public BoundBlockReader(BooleanSupplier blockChecker, Supplier<Block> blockGetter,
+ Closer blockCloser) {
checker = blockChecker;
getter = blockGetter;
closer = blockCloser;
@@ -66,7 +67,7 @@ public class BoundBlockReader implements BlockReader {
@Override
public boolean nextBlock() {
- if(checker.getAsBoolean()) {
+ if (checker.getAsBoolean()) {
current = getter.get();
blockNo += 1;
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/FilteredBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/FilteredBlockReader.java
index 7a6eddc..5520f1f 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/FilteredBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/FilteredBlockReader.java
@@ -6,7 +6,7 @@ import java.util.function.Predicate;
/**
* A block reader that only yields blocks that pass a predicate.
- *
+ *
* @author EVE
*
*/
@@ -41,28 +41,29 @@ public class FilteredBlockReader implements BlockReader {
/**
* Create a new filtered block reader with a given filter.
- *
+ *
* @param src
- * The place to read blocks from.
+ * The place to read blocks from.
* @param predic
- * The predicate to use to pass blocks.
+ * The predicate to use to pass blocks.
*/
public FilteredBlockReader(BlockReader src, Predicate<Block> predic) {
this(src, predic, null);
}
/**
- * Create a new filtered block reader with a given filter that executes
- * a specific action when a block fails.
- *
+ * Create a new filtered block reader with a given filter that executes a
+ * specific action when a block fails.
+ *
* @param src
- * The place to read blocks from.
+ * The place to read blocks from.
* @param predic
- * The predicate to use to pass blocks.
+ * The predicate to use to pass blocks.
* @param failAct
- * The action to take when a block fails.
+ * The action to take when a block fails.
*/
- public FilteredBlockReader(BlockReader src, Predicate<Block> predic, Consumer<Block> failAct) {
+ public FilteredBlockReader(BlockReader src, Predicate<Block> predic,
+ Consumer<Block> failAct) {
source = src;
pred = predic;
failAction = failAct;
@@ -72,16 +73,16 @@ public class FilteredBlockReader implements BlockReader {
@Override
public boolean hasNextBlock() {
- if(pending != null) return true;
+ if (pending != null)
+ return true;
- while(source.hasNextBlock()) {
+ while (source.hasNextBlock()) {
/*
- * Only say we have a next block if the next block would
- * pass the predicate.
+ * Only say we have a next block if the next block would pass the predicate.
*/
pending = source.next();
- if(pred.test(pending)) {
+ if (pred.test(pending)) {
blockNo += 1;
return true;
}
@@ -99,7 +100,7 @@ public class FilteredBlockReader implements BlockReader {
@Override
public boolean nextBlock() {
- if(pending != null || hasNextBlock()) {
+ if (pending != null || hasNextBlock()) {
current = pending;
pending = null;
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java
index 9c1bcd5..e08d360 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java
@@ -36,11 +36,11 @@ public class FlatMappedBlockReader implements BlockReader {
/**
* Create a new flat-mapping block reader.
- *
+ *
* @param source
- * The source to read blocks from
+ * The source to read blocks from
* @param trans
- * The transform to use.
+ * The transform to use.
*/
public FlatMappedBlockReader(BlockReader source, Function<Block, List<Block>> trans) {
reader = source;
@@ -62,11 +62,11 @@ public class FlatMappedBlockReader implements BlockReader {
@Override
public boolean nextBlock() {
/*
- * Attempt to get a new pending list if the one we have isn't
- * valid.
+ * Attempt to get a new pending list if the one we have isn't valid.
*/
- while(pending == null || !pending.hasNext()) {
- if(!reader.hasNext()) return false;
+ while (pending == null || !pending.hasNext()) {
+ if (!reader.hasNext())
+ return false;
pending = transform.apply(reader.next()).iterator();
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java
index 48c4963..847e298 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java
@@ -29,10 +29,10 @@ public class LayeredBlockReader implements BlockReader {
* Create a new layered block reader.
*
* @param primary
- * The first source to read blocks from.
+ * The first source to read blocks from.
*
* @param secondary
- * The second source to read blocks from.
+ * The second source to read blocks from.
*/
public LayeredBlockReader(final BlockReader primary, final BlockReader secondary) {
first = primary;
@@ -49,8 +49,8 @@ public class LayeredBlockReader implements BlockReader {
final Block firstBlock = first.getBlock();
/*
- * Only drain a block from the second reader if none are
- * available in the first reader.
+ * Only drain a block from the second reader if none are available in the first
+ * reader.
*/
return firstBlock == null ? second.getBlock() : firstBlock;
}
@@ -60,7 +60,7 @@ public class LayeredBlockReader implements BlockReader {
final boolean gotFirst = first.nextBlock();
final boolean succ = gotFirst ? gotFirst : second.nextBlock();
- if(succ) {
+ if (succ) {
blockNo += 1;
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java
index 4439da2..8b3e0c5 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java
@@ -5,7 +5,7 @@ import java.util.function.UnaryOperator;
/**
* A block reader that applies a transform to each block.
- *
+ *
* @author EVE
*
*/
@@ -20,11 +20,11 @@ public class MappedBlockReader implements BlockReader {
/**
* Create a new mapped block reader.
- *
+ *
* @param source
- * The source for blocks
+ * The source for blocks
* @param trans
- * The transform to apply.
+ * The transform to apply.
*/
public MappedBlockReader(BlockReader source, UnaryOperator<Block> trans) {
reader = source;
@@ -45,7 +45,7 @@ public class MappedBlockReader implements BlockReader {
@Override
public boolean nextBlock() {
- if(hasNextBlock()) {
+ if (hasNextBlock()) {
current = transform.apply(reader.next());
blockNo += 1;
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java
index 924df39..cdd6760 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/PushbackBlockReader.java
@@ -27,7 +27,7 @@ public class PushbackBlockReader implements BlockReader {
* Create a new pushback block reader.
*
* @param src
- * The block reader to use when no blocks are queued.
+ * The block reader to use when no blocks are queued.
*/
public PushbackBlockReader(final BlockReader src) {
source = src;
@@ -50,7 +50,7 @@ public class PushbackBlockReader implements BlockReader {
/*
* Drain pushed-back blocks first.
*/
- if(!waiting.isEmpty()) {
+ if (!waiting.isEmpty()) {
curBlock = waiting.pop();
blockNo += 1;
@@ -61,7 +61,7 @@ public class PushbackBlockReader implements BlockReader {
final boolean succ = source.nextBlock();
curBlock = source.getBlock();
- if(succ) {
+ if (succ) {
blockNo += 1;
}
@@ -82,7 +82,7 @@ public class PushbackBlockReader implements BlockReader {
* Insert a block at the back of the queue of pending blocks.
*
* @param blk
- * The block to put at the back.
+ * The block to put at the back.
*/
public void addBlock(final Block blk) {
waiting.add(blk);
@@ -92,7 +92,7 @@ public class PushbackBlockReader implements BlockReader {
* Insert a block at the front of the queue of pending blocks.
*
* @param blk
- * The block to put at the front.
+ * The block to put at the front.
*/
public void pushBlock(final Block blk) {
waiting.push(blk);
@@ -100,7 +100,7 @@ public class PushbackBlockReader implements BlockReader {
@Override
public String toString() {
- return String.format("PushbackBlockReader [waiting=%s, curBlock=%s, blockNo=%s]", waiting, curBlock,
- blockNo);
+ return String.format("PushbackBlockReader [waiting=%s, curBlock=%s, blockNo=%s]",
+ waiting, curBlock, blockNo);
}
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java
index 66ebd66..265a781 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java
@@ -19,19 +19,20 @@ public class SerialBlockReader implements BlockReader {
* Create a new serial block reader.
*
* @param readers
- * The readers to pull from, in the order to pull from them.
+ * The readers to pull from, in the order to pull from them.
*/
public SerialBlockReader(final BlockReader... readers) {
readerQueue = new LinkedList<>();
-
- for(final BlockReader reader : readers) {
+
+ for (final BlockReader reader : readers) {
readerQueue.add(reader);
}
}
@Override
public boolean hasNextBlock() {
- if(readerQueue.isEmpty()) return false;
+ if (readerQueue.isEmpty())
+ return false;
/*
* Attempt to get a block from the first reader.
@@ -42,11 +43,12 @@ public class SerialBlockReader implements BlockReader {
/*
* Close/dispose of readers until we get an open one.
*/
- while(!cont) {
+ while (!cont) {
try {
readerQueue.pop().close();
- } catch(final IOException ioex) {
- throw new IllegalStateException("Exception thrown by discarded reader", ioex);
+ } catch (final IOException ioex) {
+ throw new IllegalStateException("Exception thrown by discarded reader",
+ ioex);
}
hasBlock = readerQueue.peek().hasNextBlock();
@@ -58,7 +60,7 @@ public class SerialBlockReader implements BlockReader {
@Override
public Block getBlock() {
- if(readerQueue.isEmpty()) {
+ if (readerQueue.isEmpty()) {
return null;
}
@@ -67,23 +69,25 @@ public class SerialBlockReader implements BlockReader {
@Override
public boolean nextBlock() {
- if(readerQueue.isEmpty()) return false;
+ if (readerQueue.isEmpty())
+ return false;
boolean gotBlock = readerQueue.peek().nextBlock();
boolean cont = gotBlock || readerQueue.isEmpty();
- while(!cont) {
+ while (!cont) {
try {
readerQueue.pop().close();
- } catch(final IOException ioex) {
- throw new IllegalStateException("Exception thrown by discarded reader", ioex);
+ } catch (final IOException ioex) {
+ throw new IllegalStateException("Exception thrown by discarded reader",
+ ioex);
}
gotBlock = readerQueue.peek().nextBlock();
cont = gotBlock || readerQueue.isEmpty();
}
- if(cont) {
+ if (cont) {
blockNo += 1;
}
@@ -97,7 +101,7 @@ public class SerialBlockReader implements BlockReader {
@Override
public void close() throws IOException {
- while(!readerQueue.isEmpty()) {
+ while (!readerQueue.isEmpty()) {
final BlockReader reader = readerQueue.pop();
reader.close();
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java
index ac77f97..94405c9 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java
@@ -38,11 +38,11 @@ public class SimpleBlockReader implements BlockReader {
* Create a new block reader.
*
* @param blockDelim
- * The pattern that separates blocks. Note that the end of file
- * is always considered to end a block.
+ * The pattern that separates blocks. Note that the end of
+ * file is always considered to end a block.
*
* @param source
- * The source to read blocks from.
+ * The source to read blocks from.
*/
public SimpleBlockReader(final String blockDelim, final Reader source) {
blockReader = new Scanner(source);
@@ -59,12 +59,12 @@ public class SimpleBlockReader implements BlockReader {
* Create a new block reader.
*
* @param blockDelim
- * The pattern that separates blocks. Note that the end of file
- * is always considered to end a block.
+ * The pattern that separates blocks. Note that the end of
+ * file is always considered to end a block.
*
* @param source
- * The source to read blocks from.
- * NOTE: This does modify the provided scanner.
+ * The source to read blocks from. NOTE: This does modify the
+ * provided scanner.
*/
public SimpleBlockReader(final String blockDelim, final Scanner source) {
blockReader = source;
@@ -96,7 +96,8 @@ public class SimpleBlockReader implements BlockReader {
final String blockContents = blockReader.next();
final int blockStartLine = lineNo;
- final int blockEndLine = lineNo + StringUtils.countMatches(blockContents, "\\R");
+ final int blockEndLine
+ = lineNo + StringUtils.countMatches(blockContents, "\\R");
lineNo = blockEndLine;
blockNo += 1;
@@ -104,10 +105,10 @@ public class SimpleBlockReader implements BlockReader {
currBlock = new Block(blockNo, blockContents, blockStartLine, blockEndLine);
return true;
- } catch(final NoSuchElementException nseex) {
+ } catch (final NoSuchElementException nseex) {
// Don't null out the current block, let it be the last
// one
- //currBlock = null;
+ // currBlock = null;
return false;
}
@@ -127,7 +128,7 @@ public class SimpleBlockReader implements BlockReader {
* Set the delimiter used to separate blocks.
*
* @param delim
- * The delimiter used to separate blocks.
+ * The delimiter used to separate blocks.
*/
public void setDelimiter(final String delim) {
blockReader.useDelimiter(delim);
@@ -135,6 +136,7 @@ public class SimpleBlockReader implements BlockReader {
@Override
public String toString() {
- return String.format("SimpleBlockReader [currBlock=%s, blockNo=%s]", currBlock, blockNo);
+ return String.format("SimpleBlockReader [currBlock=%s, blockNo=%s]", currBlock,
+ blockNo);
}
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java
index 456a445..12568c8 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java
@@ -6,7 +6,7 @@ import bjc.data.BooleanToggle;
/**
* A block reader that toggles between two sources.
- *
+ *
* @author EVE
*
*/
@@ -21,11 +21,11 @@ public class ToggledBlockReader implements BlockReader {
/**
* Create a new toggling block reader.
- *
+ *
* @param left
- * The first block reader to use.
+ * The first block reader to use.
* @param right
- * The second block reader to use.
+ * The second block reader to use.
*/
public ToggledBlockReader(BlockReader left, BlockReader right) {
leftSource = left;
@@ -38,7 +38,7 @@ public class ToggledBlockReader implements BlockReader {
@Override
public boolean hasNextBlock() {
- if(leftToggle.peek()) {
+ if (leftToggle.peek()) {
return leftSource.hasNextBlock();
}
@@ -47,7 +47,7 @@ public class ToggledBlockReader implements BlockReader {
@Override
public Block getBlock() {
- if(leftToggle.peek()) {
+ if (leftToggle.peek()) {
return leftSource.getBlock();
}
@@ -58,13 +58,14 @@ public class ToggledBlockReader implements BlockReader {
public boolean nextBlock() {
boolean succ;
- if(leftToggle.get()) {
+ if (leftToggle.get()) {
succ = leftSource.nextBlock();
} else {
succ = rightSource.nextBlock();
}
- if(succ) blockNo += 1;
+ if (succ)
+ blockNo += 1;
return succ;
}
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java
index a066f9c..b4accec 100644
--- a/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java
+++ b/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java
@@ -22,10 +22,10 @@ public class TriggeredBlockReader implements BlockReader {
* Create a new triggered reader with the specified source/action.
*
* @param source
- * The block reader to read blocks from.
+ * The block reader to read blocks from.
*
* @param action
- * The action to execute before reading a block.
+ * The action to execute before reading a block.
*/
public TriggeredBlockReader(final BlockReader source, final Runnable action) {
this.source = source;
diff --git a/base/src/main/java/bjc/utils/ioutils/properties/Property.java b/base/src/main/java/bjc/utils/ioutils/properties/Property.java
index 7cc9369..77d990a 100644
--- a/base/src/main/java/bjc/utils/ioutils/properties/Property.java
+++ b/base/src/main/java/bjc/utils/ioutils/properties/Property.java
@@ -8,8 +8,8 @@ public class Property {
public String value;
public Property(String name, String comment, String value) {
- this.name = name;
+ this.name = name;
this.comment = comment;
- this.value = value;
+ this.value = value;
}
}
diff --git a/base/src/main/java/bjc/utils/ioutils/properties/PropertyDB.java b/base/src/main/java/bjc/utils/ioutils/properties/PropertyDB.java
index 0996b58..4126d80 100644
--- a/base/src/main/java/bjc/utils/ioutils/properties/PropertyDB.java
+++ b/base/src/main/java/bjc/utils/ioutils/properties/PropertyDB.java
@@ -2,7 +2,7 @@ package bjc.utils.ioutils.properties;
/**
* A database of properties.
- *
+ *
* @author bjculkin
*
*/
diff --git a/base/src/main/java/bjc/utils/math/CardinalState.java b/base/src/main/java/bjc/utils/math/CardinalState.java
index 3c97b68..de2224c 100644
--- a/base/src/main/java/bjc/utils/math/CardinalState.java
+++ b/base/src/main/java/bjc/utils/math/CardinalState.java
@@ -7,21 +7,21 @@ import java.util.function.LongPredicate;
/*
* @TODO 2/12/18 Ben Culkin :AdditionalCardinals
- *
+ *
* Add some built-in implementations for various things.
*
* By this, I mean for various unit scales, like custom and metric weights
*/
/**
* Customizations for number cardinalization.
- *
+ *
* @author EVE
*
*/
public class CardinalState {
/**
* Alias type for converting numbers to cardinals.
- *
+ *
* @author EVE
*
*/
@@ -44,31 +44,32 @@ public class CardinalState {
/**
* Create a new set of cardinalization customizations.
- *
+ *
* @param customNumbers
- * The custom numbers to use.
+ * The custom numbers to use.
* @param customScales
- * The custom scales to use.
+ * The custom scales to use.
*/
- public CardinalState(Map<Long, String> customNumbers, Map<LongPredicate, Cardinalizer> customScales) {
+ public CardinalState(Map<Long, String> customNumbers,
+ Map<LongPredicate, Cardinalizer> customScales) {
this.customNumbers = customNumbers;
this.customScales = customScales;
}
/**
* Handle a custom cardinal number
- *
+ *
* @param number
- * The number to handle
+ * The number to handle
* @return The number as a cardinal, or null if we don't handle it.
*/
public String handleCustom(long number) {
- if(customNumbers.containsKey(number)) {
+ if (customNumbers.containsKey(number)) {
return customNumbers.get(number);
}
- for(Entry<LongPredicate, Cardinalizer> ent : customScales.entrySet()) {
- if(ent.getKey().test(number)) {
+ for (Entry<LongPredicate, Cardinalizer> ent : customScales.entrySet()) {
+ if (ent.getKey().test(number)) {
return ent.getValue().apply(number, this);
}
}
diff --git a/base/src/main/java/bjc/utils/math/Dual.java b/base/src/main/java/bjc/utils/math/Dual.java
index 7eea6a9..4a81e8a 100644
--- a/base/src/main/java/bjc/utils/math/Dual.java
+++ b/base/src/main/java/bjc/utils/math/Dual.java
@@ -3,8 +3,8 @@ package bjc.utils.math;
/**
* Represents a 'dual' number.
*
- * Think imaginary numbers, where instead of i, we add a value d such that
- * d^2 = 0.
+ * Think imaginary numbers, where instead of i, we add a value d such that d^2 =
+ * 0.
*/
public class Dual {
/**
@@ -28,7 +28,7 @@ public class Dual {
* Create a new dual number with a zero dual part.
*
* @param real
- * The real part of the number.
+ * The real part of the number.
*/
public Dual(double real) {
this.real = real;
@@ -39,9 +39,9 @@ public class Dual {
* Create a new dual number with a specified dual part.
*
* @param real
- * The real part of the number.
+ * The real part of the number.
* @param dual
- * The dual part of the number.
+ * The dual part of the number.
*/
public Dual(double real, double dual) {
this.real = real;
@@ -67,12 +67,17 @@ public class Dual {
@Override
public boolean equals(Object obj) {
- if(this == obj) return true;
- if(obj == null) return false;
- if(getClass() != obj.getClass()) return false;
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
Dual other = (Dual) obj;
- if(Double.doubleToLongBits(dual) != Double.doubleToLongBits(other.dual)) return false;
- if(Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real)) return false;
+ if (Double.doubleToLongBits(dual) != Double.doubleToLongBits(other.dual))
+ return false;
+ if (Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real))
+ return false;
return true;
}
}
diff --git a/base/src/main/java/bjc/utils/math/DualExpr.java b/base/src/main/java/bjc/utils/math/DualExpr.java
index 81ee31c..a682814 100644
--- a/base/src/main/java/bjc/utils/math/DualExpr.java
+++ b/base/src/main/java/bjc/utils/math/DualExpr.java
@@ -83,7 +83,8 @@ public class DualExpr {
/**
* Create a new constant dual number.
*
- * @param num The value of the dual number.
+ * @param num
+ * The value of the dual number.
*/
public DualExpr(Dual num) {
this.type = ExprType.CONSTANT;
@@ -94,8 +95,10 @@ public class DualExpr {
/**
* Create a new unary dual number.
*
- * @param type The type of operation to perform.
- * @param val The parameter to the value.
+ * @param type
+ * The type of operation to perform.
+ * @param val
+ * The parameter to the value.
*/
public DualExpr(DualExpr.ExprType type, DualExpr val) {
this.type = type;
@@ -106,9 +109,12 @@ public class DualExpr {
/**
* Create a new binary dual number.
*
- * @param type The type of operation to perform.
- * @param left The left hand side of the expression.
- * @param right The right hand side of the expression.
+ * @param type
+ * The type of operation to perform.
+ * @param left
+ * The left hand side of the expression.
+ * @param right
+ * The right hand side of the expression.
*/
public DualExpr(DualExpr.ExprType type, DualExpr left, DualExpr right) {
this.type = type;
@@ -189,7 +195,8 @@ public class DualExpr {
lval = left.evaluate();
if (lval.real <= 0) {
- throw new IllegalArgumentException("ERROR: Attempted to take non-positive log.");
+ throw new IllegalArgumentException(
+ "ERROR: Attempted to take non-positive log.");
}
return new Dual(Math.log(lval.real), lval.dual / lval.real);
@@ -197,7 +204,8 @@ public class DualExpr {
// @TODO Ben Culkin 3/27/2020 :RealPower
// Make this no longer a special case; since it doesn't have to be one.
//
- // 3/28/2020 - This is less of a special case, but I've not implemented the bit for variable exponents.
+ // 3/28/2020 - This is less of a special case, but I've not implemented the
+ // bit for variable exponents.
lval = left.evaluate();
rval = right.evaluate();
diff --git a/base/src/main/java/bjc/utils/math/DualExprParser.java b/base/src/main/java/bjc/utils/math/DualExprParser.java
index d90024f..f130a9a 100644
--- a/base/src/main/java/bjc/utils/math/DualExprParser.java
+++ b/base/src/main/java/bjc/utils/math/DualExprParser.java
@@ -1,5 +1,5 @@
/**
- *
+ *
*/
package bjc.utils.math;
@@ -16,19 +16,20 @@ import bjc.utils.math.DualExpr.ExprType;
/**
* Create DualExprs from strings.
- *
+ *
* @author Ben Culkin
*
*/
public class DualExprParser {
/**
* Result class from parsing exprs.
+ *
* @author Ben Culkin
*
*/
public static class Result {
/**
- * The resulting expression.
+ * The resulting expression.
*/
public DualExpr expr;
/**
@@ -46,10 +47,10 @@ public class DualExprParser {
/**
* Parses a dual expression from a postfix expression string.
- *
+ *
* @param expr
* The string to parse the dual expression from.
- *
+ *
* @return Both the parsed expression, and a map of all the variables used
*/
public static Result parseExpression(String expr) {
@@ -58,17 +59,17 @@ public class DualExprParser {
/**
* Parses a dual expression from a postfix expression string.
- *
+ *
* @param expr
* The string to parse the dual expression from.
*
* @param preVars
* Any pre-existing variables to use.
- *
+ *
* @return Both the parsed expression, and a map of all the variables used
- *
+ *
* @throws StackUnderflow
- * If the expression is not properly formatted.
+ * If the expression is not properly formatted.
*/
public static Result parseExpression(String expr, Map<String, DualExpr> preVars) {
Result res = new Result();
diff --git a/base/src/main/java/bjc/utils/math/NumberUtils.java b/base/src/main/java/bjc/utils/math/NumberUtils.java
index 7dc2ff3..7d138fb 100644
--- a/base/src/main/java/bjc/utils/math/NumberUtils.java
+++ b/base/src/main/java/bjc/utils/math/NumberUtils.java
@@ -2,26 +2,26 @@ package bjc.utils.math;
/**
* A variety of functions for doing useful stuff with numbers.
- *
+ *
* @author EVE
*
*/
public class NumberUtils {
/*
* @TODO 2/12/18 Ben Culkin :RomanExpansion
- *
- * Use U+305 for large roman numerals, as well as excels 'concise'
- * numerals (as implemented by roman()).
+ *
+ * Use U+305 for large roman numerals, as well as excels 'concise' numerals (as
+ * implemented by roman()).
*/
/**
* Convert a number into a roman numeral.
- *
+ *
* @param number
- * The number to convert.
+ * The number to convert.
* @param classic
- * Whether to use classic roman numerals (use IIII instead of IV,
- * and such).
+ * Whether to use classic roman numerals (use IIII instead of IV,
+ * and such).
* @return The number as a roman numeral.
*/
public static String toRoman(long number, boolean classic) {
@@ -29,102 +29,102 @@ public class NumberUtils {
long currNumber = number;
- if(currNumber == 0) {
+ if (currNumber == 0) {
return "N";
}
- if(currNumber < 0) {
+ if (currNumber < 0) {
currNumber *= -1;
work.append("-");
}
- if(currNumber >= 1000) {
+ if (currNumber >= 1000) {
int numM = (int) (currNumber / 1000);
currNumber = currNumber % 1000;
- for(int i = 0; i < numM; i++) {
+ for (int i = 0; i < numM; i++) {
work.append("M");
}
}
- if(currNumber >= 900 && !classic) {
+ if (currNumber >= 900 && !classic) {
currNumber = currNumber % 900;
work.append("CM");
}
- if(currNumber >= 500) {
+ if (currNumber >= 500) {
currNumber = currNumber % 500;
work.append("D");
}
- if(currNumber >= 400 && !classic) {
+ if (currNumber >= 400 && !classic) {
currNumber = currNumber % 400;
work.append("CD");
}
- if(currNumber >= 100) {
+ if (currNumber >= 100) {
int numC = (int) (currNumber / 100);
currNumber = currNumber % 100;
- for(int i = 0; i < numC; i++) {
+ for (int i = 0; i < numC; i++) {
work.append("C");
}
}
- if(currNumber >= 90 && !classic) {
+ if (currNumber >= 90 && !classic) {
currNumber = currNumber % 90;
work.append("XC");
}
- if(currNumber >= 50) {
+ if (currNumber >= 50) {
currNumber = currNumber % 50;
work.append("L");
}
- if(currNumber >= 40 && !classic) {
+ if (currNumber >= 40 && !classic) {
currNumber = currNumber % 40;
work.append("XL");
}
- if(currNumber >= 10) {
+ if (currNumber >= 10) {
int numX = (int) (currNumber / 10);
currNumber = currNumber % 10;
- for(int i = 0; i < numX; i++) {
+ for (int i = 0; i < numX; i++) {
work.append("X");
}
}
- if(currNumber >= 9 && !classic) {
+ if (currNumber >= 9 && !classic) {
currNumber = currNumber % 9;
work.append("IX");
}
- if(currNumber >= 5) {
+ if (currNumber >= 5) {
currNumber = currNumber % 5;
work.append("V");
}
- if(currNumber >= 4 && !classic) {
+ if (currNumber >= 4 && !classic) {
currNumber = currNumber % 4;
work.append("IV");
}
- if(currNumber >= 1) {
+ if (currNumber >= 1) {
int numI = (int) (currNumber / 1);
currNumber = currNumber % 1;
- for(int i = 0; i < numI; i++) {
+ for (int i = 0; i < numI; i++) {
work.append("I");
}
}
@@ -134,9 +134,9 @@ public class NumberUtils {
/**
* Convert a number into a cardinal number.
- *
+ *
* @param number
- * The number to convert
+ * The number to convert
* @return The number as a cardinal.
*/
public static String toCardinal(long number) {
@@ -144,34 +144,37 @@ public class NumberUtils {
}
private static String[] cardinals = new String[] {
- "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
- "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
- "twenty",
+ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
+ "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
+ "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
};
/**
* Convert a number into a cardinal number.
- *
+ *
* @param number
- * The number to convert to a cardinal.
+ * The number to convert to a cardinal.
* @param custom
- * The customizations to use.
+ * The customizations to use.
* @return The number as a cardinal.
*/
public static String toCardinal(long number, CardinalState custom) {
- if(custom != null) {
+ if (custom != null) {
String res = custom.handleCustom(number);
- if(res != null) return res;
+ if (res != null)
+ return res;
}
- if(number < 0) return "negative " + toCardinal(number * -1, custom);
+ if (number < 0)
+ return "negative " + toCardinal(number * -1, custom);
- if(number <= 20) return cardinals[(int) number];
+ if (number <= 20)
+ return cardinals[(int) number];
- if(number < 100) {
- if(number % 10 == 0) {
- switch((int) number) {
+ if (number < 100) {
+ if (number % 10 == 0) {
+ switch ((int) number) {
case 30:
return "thirty";
case 40:
@@ -200,35 +203,39 @@ public class NumberUtils {
return toCardinal(numTens, custom) + "-" + toCardinal(numOnes, custom);
}
- if(number < 1000) {
+ if (number < 1000) {
long numHundreds = number / 100;
long rest = number % 100;
- return toCardinal(numHundreds, custom) + " hundred and " + toCardinal(rest, custom);
+ return toCardinal(numHundreds, custom) + " hundred and "
+ + toCardinal(rest, custom);
}
long MILLION = (long) (Math.pow(10, 6));
- if(number < MILLION) {
+ if (number < MILLION) {
long numThousands = number / 1000;
long rest = number % 1000;
- return toCardinal(numThousands, custom) + " thousand, " + toCardinal(rest, custom);
+ return toCardinal(numThousands, custom) + " thousand, "
+ + toCardinal(rest, custom);
}
long BILLION = (long) (Math.pow(10, 9));
- if(number < BILLION) {
+ if (number < BILLION) {
long numMillions = number / MILLION;
long rest = number % MILLION;
- return toCardinal(numMillions, custom) + " million, " + toCardinal(rest, custom);
+ return toCardinal(numMillions, custom) + " million, "
+ + toCardinal(rest, custom);
}
long TRILLION = (long) (Math.pow(10, 12));
- if(number < TRILLION) {
+ if (number < TRILLION) {
long numBillions = number / BILLION;
long rest = number % BILLION;
- return toCardinal(numBillions, custom) + " billion, " + toCardinal(rest, custom);
+ return toCardinal(numBillions, custom) + " billion, "
+ + toCardinal(rest, custom);
}
throw new IllegalArgumentException(
@@ -237,18 +244,18 @@ public class NumberUtils {
/**
* Convert a number into an ordinal.
- *
+ *
* @param number
- * The number to convert to an ordinal.
+ * The number to convert to an ordinal.
* @return The number as an ordinal.
*/
public static String toOrdinal(long number) {
- if(number < 0) {
+ if (number < 0) {
return "minus " + toOrdinal(number);
}
- if(number < 20) {
- switch((int) number) {
+ if (number < 20) {
+ switch ((int) number) {
case 0:
return "zeroth";
case 1:
@@ -297,9 +304,9 @@ public class NumberUtils {
}
}
- if(number < 100) {
- if(number % 10 == 0) {
- switch((int) number) {
+ if (number < 100) {
+ if (number % 10 == 0) {
+ switch ((int) number) {
case 20:
return "twentieth";
case 30:
@@ -317,7 +324,8 @@ public class NumberUtils {
case 90:
return "ninetieth";
default:
- throw new IllegalArgumentException(String.format("Illegal number %d", number));
+ throw new IllegalArgumentException(
+ String.format("Illegal number %d", number));
}
}
@@ -329,11 +337,11 @@ public class NumberUtils {
long tens = procNum / 10;
long ones = procNum % 10;
- if(tens == 1) {
+ if (tens == 1) {
return Long.toString(number) + "th";
}
- switch((int) ones) {
+ switch ((int) ones) {
case 1:
return Long.toString(number) + "st";
case 2:
@@ -349,19 +357,19 @@ public class NumberUtils {
static {
int idx = 0;
- for(char i = 0; i < 10; i++) {
+ for (char i = 0; i < 10; i++) {
radixChars[idx] = (char) ('0' + i);
idx += 1;
}
- for(char i = 0; i < 26; i++) {
+ for (char i = 0; i < 26; i++) {
radixChars[idx] = (char) ('A' + i);
idx += 1;
}
- for(char i = 0; i < 26; i++) {
+ for (char i = 0; i < 26; i++) {
radixChars[idx] = (char) ('a' + i);
idx += 1;
@@ -370,58 +378,61 @@ public class NumberUtils {
/**
* Convert a number into a commafied string.
- *
+ *
* @param val
- * The number to convert.
+ * The number to convert.
* @param mincols
- * The minimum number of columns to use.
+ * The minimum number of columns to use.
* @param padchar
- * The padding char to use.
+ * The padding char to use.
* @param commaInterval
- * The interval to place commas at.
+ * The interval to place commas at.
* @param commaChar
- * The character to use as a comma
+ * The character to use as a comma
* @param signed
- * Whether or not to always display a sign
+ * Whether or not to always display a sign
* @param radix
- * The radix to use
+ * The radix to use
* @return The number as a commafied string.
*/
- public static String toCommaString(long val, int mincols, char padchar, int commaInterval, char commaChar,
- boolean signed, int radix) {
- if(radix > radixChars.length) {
+ public static String toCommaString(long val, int mincols, char padchar,
+ int commaInterval, char commaChar, boolean signed, int radix) {
+ if (radix > radixChars.length) {
throw new IllegalArgumentException(
- String.format("Radix %d is larger than largest supported radix %d", radix,
- radixChars.length));
+ String.format("Radix %d is larger than largest supported radix %d",
+ radix, radixChars.length));
}
StringBuilder work = new StringBuilder();
boolean isNeg = false;
long currVal = val;
- if(currVal < 0) {
- isNeg = true;
+ if (currVal < 0) {
+ isNeg = true;
currVal *= -1;
}
- if(currVal == 0) {
+ if (currVal == 0) {
work.append(radixChars[0]);
} else {
int valCounter = 0;
- while(currVal != 0) {
+ while (currVal != 0) {
valCounter += 1;
int radDigit = (int) (currVal % radix);
work.append(radixChars[radDigit]);
currVal = currVal / radix;
- if(commaInterval != 0 && valCounter % commaInterval == 0 && currVal != 0) work.append(commaChar);
+ if (commaInterval != 0 && valCounter % commaInterval == 0 && currVal != 0)
+ work.append(commaChar);
}
}
- if(isNeg) work.append("-");
- else if(signed) work.append("+");
+ if (isNeg)
+ work.append("-");
+ else if (signed)
+ work.append("+");
work.reverse();
@@ -430,25 +441,24 @@ public class NumberUtils {
*
* Should we have some way to specify how to pad?
*
- * By this, I mean specify padding direction (left, right,
- * balanced...)
+ * By this, I mean specify padding direction (left, right, balanced...)
*/
StringBuilder pad = new StringBuilder();
- if(work.length() < mincols) {
+ if (work.length() < mincols) {
@SuppressWarnings("unused")
int padCount = 0;
- for(int i = work.length(); i < mincols; i++) {
+ for (int i = work.length(); i < mincols; i++) {
// @NOTE 9/6/18 :CommaPad
//
// I have no idea if this is the intended
// behavior, or if something is wrong with the
// example case in the menu
// if (commaInterval != 0 && padCount != 0) {
- // if (Character.isDigit(padchar) && padCount % commaInterval == 0)
- // pad.append(commaChar);
- // else
- pad.append(padchar);
+ // if (Character.isDigit(padchar) && padCount % commaInterval == 0)
+ // pad.append(commaChar);
+ // else
+ pad.append(padchar);
// }
padCount++;
@@ -460,20 +470,21 @@ public class NumberUtils {
/**
* Convert a number to a normal commafied string.
- *
+ *
* @param val
- * The value to convert.
+ * The value to convert.
* @param mincols
- * The minimum number of columns.
+ * The minimum number of columns.
* @param padchar
- * The padding char to use.
+ * The padding char to use.
* @param signed
- * Whether or not to display the sign.
+ * Whether or not to display the sign.
* @param radix
- * The radix to use.
+ * The radix to use.
* @return The number as a normal commafied string.
*/
- public static String toNormalString(long val, int mincols, char padchar, boolean signed, int radix) {
+ public static String toNormalString(long val, int mincols, char padchar,
+ boolean signed, int radix) {
return toCommaString(val, mincols, padchar, 0, ',', signed, radix);
}
}
diff --git a/base/src/main/java/bjc/utils/misc/Direction.java b/base/src/main/java/bjc/utils/misc/Direction.java
index b8a982e..6455d8d 100644
--- a/base/src/main/java/bjc/utils/misc/Direction.java
+++ b/base/src/main/java/bjc/utils/misc/Direction.java
@@ -11,10 +11,10 @@ import bjc.funcdata.IList;
/**
* A set of cardinal directions
- *
- * The particular axis assigned to the coordinates are based off of x being
- * the bottom left axis on a conventional 3D plot
- *
+ *
+ * The particular axis assigned to the coordinates are based off of x being the
+ * bottom left axis on a conventional 3D plot
+ *
* @author ben
*
*/
@@ -51,7 +51,7 @@ public enum Direction {
/**
* Get a list of all the cardinal directions
- *
+ *
* @return A list of all the cardinal directions
*/
public static IList<Direction> cardinals() {
@@ -59,9 +59,8 @@ public enum Direction {
}
/**
- * Perform the specified action once with each of the cardinal
- * directions
- *
+ * Perform the specified action once with each of the cardinal directions
+ *
* @param act
* The action to perform for each cardinal direction
*/
@@ -71,15 +70,14 @@ public enum Direction {
/**
* Perform a specified action for a random number of cardinals.
- *
+ *
* @param nCardinals
- * The number of cardinal directions to act on. Must be
- * greater than 0 and less then 5
+ * The number of cardinal directions to act on. Must be
+ * greater than 0 and less then 5
* @param act
- * The action to perform for each of the cardinals
+ * The action to perform for each of the cardinals
*/
- public static void forRandomCardinals(int nCardinals,
- Consumer<Direction> act) {
+ public static void forRandomCardinals(int nCardinals, Consumer<Direction> act) {
if (nCardinals <= 0 || nCardinals > 4) {
throw new IllegalArgumentException(
"Tried to do things with incorrect number of cardinal directions. Tried with "
@@ -99,9 +97,9 @@ public enum Direction {
/**
* Create a value of the enumeration from a string
- *
+ *
* @param value
- * The string to turn into a value
+ * The string to turn into a value
* @return The direction corresponding to the given value
*/
public static Direction properValueOf(String value) {
@@ -110,103 +108,97 @@ public enum Direction {
/**
* Test if this direction is a cardinal direction
- *
+ *
* @return If the direction is cardinal or not
*/
public boolean isCardinal() {
switch (this) {
- case EAST:
- case NORTH:
- case SOUTH:
- case WEST:
- return true;
- case DOWN:
- case UP:
- return false;
- default:
- throw new InvalidDirectionException(
- "WAT. Somehow ended up with an invalid direction "
- + this);
+ case EAST:
+ case NORTH:
+ case SOUTH:
+ case WEST:
+ return true;
+ case DOWN:
+ case UP:
+ return false;
+ default:
+ throw new InvalidDirectionException(
+ "WAT. Somehow ended up with an invalid direction " + this);
}
}
/**
* Get the direction that opposes the current one
- *
- * @return The direction that is in the opposite direction of the
- * current one
+ *
+ * @return The direction that is in the opposite direction of the current one
*/
public Direction opposing() {
switch (this) {
- case NORTH:
- return SOUTH;
- case EAST:
- return WEST;
- case SOUTH:
- return NORTH;
- case WEST:
- return WEST;
- case UP:
- return DOWN;
- case DOWN:
- return UP;
- default:
- throw new IllegalStateException(
- "Enumeration got into a invalid state. WAT");
+ case NORTH:
+ return SOUTH;
+ case EAST:
+ return WEST;
+ case SOUTH:
+ return NORTH;
+ case WEST:
+ return WEST;
+ case UP:
+ return DOWN;
+ case DOWN:
+ return UP;
+ default:
+ throw new IllegalStateException("Enumeration got into a invalid state. WAT");
}
}
/**
* Get the direction that is clockwise on the compass from this one.
- *
+ *
* Only works on cardinals.
- *
+ *
* @return The cardinal clockwise from this one
*/
public Direction rotateClockwise() {
switch (this) {
- case NORTH:
- return EAST;
- case EAST:
- return SOUTH;
- case SOUTH:
- return WEST;
- case WEST:
- return NORTH;
- case UP:
- case DOWN:
- default:
- throw new InvalidDirectionException(
- "Can't rotate non-cardinal direction clockwise: "
- + this);
+ case NORTH:
+ return EAST;
+ case EAST:
+ return SOUTH;
+ case SOUTH:
+ return WEST;
+ case WEST:
+ return NORTH;
+ case UP:
+ case DOWN:
+ default:
+ throw new InvalidDirectionException(
+ "Can't rotate non-cardinal direction clockwise: " + this);
}
}
/**
- * Get the direction that is counter-clockwise on the compass from this
- * one.
- *
+ * Get the direction that is counter-clockwise on the compass from this one.
+ *
* Only works on cardinals.
- *
+ *
* @return The cardinal counter-clockwise from this one
*/
public Direction rotateCounterClockwise() {
switch (this) {
- case NORTH:
- return WEST;
- case EAST:
- return NORTH;
- case SOUTH:
- return EAST;
- case WEST:
- return SOUTH;
- case UP:
- case DOWN:
- default:
- throw new InvalidDirectionException(
- "Can't rotate non-cardinal direction counterclockwise: "
- + this);
+ case NORTH:
+ return WEST;
+ case EAST:
+ return NORTH;
+ case SOUTH:
+ return EAST;
+ case WEST:
+ return SOUTH;
+ case UP:
+ case DOWN:
+ default:
+ throw new InvalidDirectionException(
+ "Can't rotate non-cardinal direction counterclockwise: " + this);
}
}
diff --git a/base/src/main/java/bjc/utils/misc/PropertyDB.java b/base/src/main/java/bjc/utils/misc/PropertyDB.java
index 09e1999..09c136c 100644
--- a/base/src/main/java/bjc/utils/misc/PropertyDB.java
+++ b/base/src/main/java/bjc/utils/misc/PropertyDB.java
@@ -16,8 +16,8 @@ import bjc.utils.ioutils.SimpleProperties;
*/
public class PropertyDB {
/* Regex storage. */
- private static SimpleProperties regexes;
- private static Map<String, Pattern> compiledRegexes;
+ private static SimpleProperties regexes;
+ private static Map<String, Pattern> compiledRegexes;
/* Format string storage. */
private static SimpleProperties formats;
@@ -40,33 +40,35 @@ public class PropertyDB {
/**
* Reload all the properties from their files.
*
- * NOTE: Any attempts to read from the property DB while properties are
- * being loaded will block, to prevent reads from partial states.
+ * NOTE: Any attempts to read from the property DB while properties are being
+ * loaded will block, to prevent reads from partial states.
*/
public static void reloadProperties() {
/* * Do the load with the write lock taken. */
loadLock.write(() -> {
- if(LOGLOAD) {
+ if (LOGLOAD) {
System.out.println("Reading regex properties:");
}
/* * Load regexes. */
regexes = new SimpleProperties();
- regexes.loadFrom(PropertyDB.class.getResourceAsStream("/regexes.sprop"), false);
- if(LOGLOAD) {
+ regexes.loadFrom(PropertyDB.class.getResourceAsStream("/regexes.sprop"),
+ false);
+ if (LOGLOAD) {
regexes.outputProperties(System.out);
System.out.println();
}
compiledRegexes = new HashMap<>();
- if(LOGLOAD) {
+ if (LOGLOAD) {
System.out.println("Reading format properties:");
}
/* * Load formats. */
formats = new SimpleProperties();
- formats.loadFrom(PropertyDB.class.getResourceAsStream("/formats.sprop"), false);
- if(LOGLOAD) {
+ formats.loadFrom(PropertyDB.class.getResourceAsStream("/formats.sprop"),
+ false);
+ if (LOGLOAD) {
formats.outputProperties(System.out);
System.out.println();
}
@@ -77,14 +79,15 @@ public class PropertyDB {
* Retrieve a persisted regular expression.
*
* @param key
- * The name of the regular expression.
+ * The name of the regular expression.
*
* @return The regular expression with that name.
*/
public static String getRegex(final String key) {
return loadLock.read(() -> {
- if(!regexes.containsKey(key)) {
- final String msg = String.format("No regular expression named '%s' found", key);
+ if (!regexes.containsKey(key)) {
+ final String msg
+ = String.format("No regular expression named '%s' found", key);
throw new NoSuchElementException(msg);
}
@@ -94,26 +97,24 @@ public class PropertyDB {
}
/**
- * Retrieve a persisted regular expression, compiled into a regular
- * expression.
+ * Retrieve a persisted regular expression, compiled into a regular expression.
*
* @param key
- * The name of the regular expression.
+ * The name of the regular expression.
*
* @return The regular expression with that name.
*/
public static Pattern getCompiledRegex(final String key) {
return loadLock.read(() -> {
- if(!regexes.containsKey(key)) {
- final String msg = String.format("No regular expression named '%s' found", key);
+ if (!regexes.containsKey(key)) {
+ final String msg
+ = String.format("No regular expression named '%s' found", key);
throw new NoSuchElementException(msg);
}
/* * Get the regex, and cache a compiled version. */
- return compiledRegexes.computeIfAbsent(key, strang -> {
- return Pattern.compile(regexes.get(strang));
- });
+ return compiledRegexes.computeIfAbsent(key, strang -> Pattern.compile(regexes.get(strang)));
});
}
@@ -121,14 +122,15 @@ public class PropertyDB {
* Retrieve a persisted format string.
*
* @param key
- * The name of the format string.
+ * The name of the format string.
*
* @return The format string with that name.
*/
public static String getFormat(final String key) {
return loadLock.read(() -> {
- if(!formats.containsKey(key)) {
- final String msg = String.format("No format string named '%s' found", key);
+ if (!formats.containsKey(key)) {
+ final String msg
+ = String.format("No format string named '%s' found", key);
throw new NoSuchElementException(msg);
}
@@ -138,14 +140,13 @@ public class PropertyDB {
}
/**
- * Retrieve a persisted format string, and apply it to a set of
- * arguments.
+ * Retrieve a persisted format string, and apply it to a set of arguments.
*
* @param key
- * The name of the format string.
+ * The name of the format string.
*
* @param objects
- * The parameters to the format string.
+ * The parameters to the format string.
*
* @return The format string with that name.
*/
diff --git a/base/src/main/java/bjc/utils/misc/RelativeDirection.java b/base/src/main/java/bjc/utils/misc/RelativeDirection.java
index 515ddea..7012377 100644
--- a/base/src/main/java/bjc/utils/misc/RelativeDirection.java
+++ b/base/src/main/java/bjc/utils/misc/RelativeDirection.java
@@ -9,7 +9,7 @@ import bjc.funcdata.IList;
/**
* Represents a direction that is relative to another direction
- *
+ *
* @author ben
*
*/
@@ -34,17 +34,17 @@ public enum RelativeDirection {
private static Random RNG = new Random();
/**
- * Perform a specified action for a random number of relative
- * directions.
- *
+ * Perform a specified action for a random number of relative directions.
+ *
* @param numDirections
- * The number of cardinal directions to act on. Must be
- * greater than 0 and less then 5
+ * The number of cardinal directions to act on. Must be
+ * greater than 0 and less then 5
* @param action
- * The action to perform for each of the relative directions
+ * The action to perform for each of the relative
+ * directions
* @param ignoreBackwards
- * Whether or not to not have a chance of one of the
- * directions being backwards
+ * Whether or not to not have a chance of one of the
+ * directions being backwards
*/
public static void forRandomDirections(int numDirections,
Consumer<RelativeDirection> action, boolean ignoreBackwards) {
@@ -62,16 +62,14 @@ public enum RelativeDirection {
+ numDirections);
}
- IList<RelativeDirection> relativeDirs =
- new FunctionalList<>(values());
+ IList<RelativeDirection> relativeDirs = new FunctionalList<>(values());
if (ignoreBackwards) {
relativeDirs.removeMatching(BACKWARD);
}
for (int i = 0; i <= maxNDirections - numDirections; i++) {
- RelativeDirection relativeDir =
- relativeDirs.randItem(RNG::nextInt);
+ RelativeDirection relativeDir = relativeDirs.randItem(RNG::nextInt);
relativeDirs.removeMatching(relativeDir);
}
@@ -81,9 +79,9 @@ public enum RelativeDirection {
/**
* Properly convert a string to a relative direction
- *
+ *
* @param value
- * The string to convert
+ * The string to convert
* @return The relative direction represented by the string
*/
public static RelativeDirection properValueOf(String value) {
@@ -92,7 +90,7 @@ public enum RelativeDirection {
/**
* Change another direction by turning the way this direction specifies
- *
+ *
* @param dir
* The direction to change
* @return The direction after turning this way
@@ -101,18 +99,18 @@ public enum RelativeDirection {
// Only cardinal directions can be truly absolutized
if (dir.isCardinal()) {
switch (this) {
- case BACKWARD:
- return dir;
- case FORWARD:
- return dir.opposing();
- case LEFT:
- return dir.rotateCounterClockwise();
- case RIGHT:
- return dir.rotateClockwise();
- default:
- throw new InvalidDirectionException(
- "Attempted to make absolute a direction in a unknown way "
- + this);
+ case BACKWARD:
+ return dir;
+ case FORWARD:
+ return dir.opposing();
+ case LEFT:
+ return dir.rotateCounterClockwise();
+ case RIGHT:
+ return dir.rotateClockwise();
+ default:
+ throw new InvalidDirectionException(
+ "Attempted to make absolute a direction in a unknown way "
+ + this);
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java b/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java
index 3618c50..1bf9b24 100644
--- a/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java
+++ b/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java
@@ -16,13 +16,16 @@ class DoubleMatcher {
*/
private static final String rDecDigits = getRegex("fpDigits");
private static final String rHexDigits = getRegex("fpHexDigits");
- private static final String rExponent = applyFormat("fpExponent", getRegex("fpExponent"), rDecDigits);
+ private static final String rExponent
+ = applyFormat("fpExponent", getRegex("fpExponent"), rDecDigits);
/*
* Decimal floating point numbers.
*/
- private static final String rSimpleDec = applyFormat("fpDecimalDecimal", rDecDigits, rExponent);
- private static final String rSimpleIntDec = applyFormat("fpDecimalInteger", rDecDigits, rExponent);
+ private static final String rSimpleDec
+ = applyFormat("fpDecimalDecimal", rDecDigits, rExponent);
+ private static final String rSimpleIntDec
+ = applyFormat("fpDecimalInteger", rDecDigits, rExponent);
/*
* Hex floating point numbers.
@@ -30,13 +33,15 @@ class DoubleMatcher {
private static final String rHexInt = applyFormat("fpHexInteger", rHexDigits);
private static final String rHexDec = applyFormat("fpHexDecimal", rHexDigits);
private static final String rHexLead = applyFormat("fpHexLeader", rHexInt, rHexDec);
- private static final String rHexString = applyFormat("fpHexString", rHexLead, rDecDigits);
+ private static final String rHexString
+ = applyFormat("fpHexString", rHexLead, rDecDigits);
/*
* Floating point components.
*/
private static final String rFPLeader = getRegex("fpLeader");
- private static final String rFPNum = applyFormat("fpNumber", rSimpleIntDec, rSimpleDec, rHexString);
+ private static final String rFPNum
+ = applyFormat("fpNumber", rSimpleIntDec, rSimpleDec, rHexString);
/*
* Full double.
diff --git a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java b/base/src/main/java/bjc/utils/parserutils/IPrecedent.java
index 0deab5d..eb164b3 100644
--- a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java
+++ b/base/src/main/java/bjc/utils/parserutils/IPrecedent.java
@@ -12,7 +12,7 @@ public interface IPrecedent {
* Create a new object with set precedence
*
* @param precedence
- * The precedence of the object to handle
+ * The precedence of the object to handle
* @return A new object with set precedence
*/
public static IPrecedent newSimplePrecedent(final int precedence) {
diff --git a/base/src/main/java/bjc/utils/parserutils/ParserException.java b/base/src/main/java/bjc/utils/parserutils/ParserException.java
index 5e53a8b..e17e3c1 100644
--- a/base/src/main/java/bjc/utils/parserutils/ParserException.java
+++ b/base/src/main/java/bjc/utils/parserutils/ParserException.java
@@ -13,7 +13,7 @@ public class ParserException extends Exception {
* Create a new exception with the provided message.
*
* @param msg
- * The message for the exception.
+ * The message for the exception.
*/
public ParserException(final String msg) {
super(msg);
@@ -23,9 +23,9 @@ public class ParserException extends Exception {
* Create a new exception with the provided message and cause.
*
* @param msg
- * The message for the exception.
+ * The message for the exception.
* @param cause
- * The cause of the exception.
+ * The cause of the exception.
*/
public ParserException(final String msg, final Exception cause) {
super(msg, cause);
diff --git a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java
index bf332f5..2418517 100644
--- a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java
+++ b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java
@@ -16,7 +16,7 @@ import bjc.utils.funcutils.StringUtils;
* @author ben
*
* @param <TokenType>
- * The type of tokens being shunted.
+ * The type of tokens being shunted.
*/
public class ShuntingYard<TokenType> {
/**
@@ -65,8 +65,8 @@ public class ShuntingYard<TokenType> {
* Create a new shunting yard with a default set of operators.
*
* @param configureBasics
- * Whether or not basic math operators should be
- * provided.
+ * Whether or not basic math operators should be
+ * provided.
*/
public ShuntingYard(final boolean configureBasics) {
operators = new FunctionalMap<>();
@@ -86,10 +86,10 @@ public class ShuntingYard<TokenType> {
* Add an operator to the list of shuntable operators.
*
* @param operator
- * The token representing the operator.
+ * The token representing the operator.
*
* @param precedence
- * The precedence of the operator to add.
+ * The precedence of the operator to add.
*/
public void addOp(final String operator, final int precedence) {
/*
@@ -104,10 +104,10 @@ public class ShuntingYard<TokenType> {
* Add an operator to the list of shuntable operators.
*
* @param operator
- * The token representing the operator.
+ * The token representing the operator.
*
* @param precedence
- * The precedence of the operator.
+ * The precedence of the operator.
*/
public void addOp(final String operator, final IPrecedent precedence) {
/*
@@ -115,7 +115,8 @@ public class ShuntingYard<TokenType> {
*/
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
@@ -133,7 +134,8 @@ public class ShuntingYard<TokenType> {
/*
* If it doesn't, the left is higher precedence.
*/
- if (!exists) return false;
+ if (!exists)
+ return false;
/*
* Get the precedence of operators
@@ -151,20 +153,22 @@ public class ShuntingYard<TokenType> {
* Transform a string of tokens from infix notation to postfix.
*
* @param input
- * The string to transform.
+ * The string to transform.
*
* @param transformer
- * The function to use to transform strings to tokens.
+ * The function to use to transform strings to tokens.
*
* @return A list of tokens in postfix notation.
*/
- public IList<TokenType> postfix(final IList<String> input, final Function<String, TokenType> transformer) {
+ public IList<TokenType> postfix(final IList<String> input,
+ final Function<String, TokenType> transformer) {
/*
* Check our input
*/
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
@@ -182,8 +186,7 @@ public class ShuntingYard<TokenType> {
*/
if (operators.containsKey(token)) {
/*
- * Pop operators while there isn't a higher
- * precedence one
+ * Pop operators while there isn't a higher precedence one
*/
while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) {
output.add(transformer.apply(stack.pop()));
@@ -195,14 +198,12 @@ public class ShuntingYard<TokenType> {
stack.push(token);
} else if (StringUtils.containsOnly(token, "\\(")) {
/*
- * Handle groups of parenthesis for multiple
- * nesting levels
+ * Handle groups of parenthesis for multiple nesting levels
*/
stack.push(token);
} else if (StringUtils.containsOnly(token, "\\)")) {
/*
- * Handle groups of parenthesis for multiple
- * nesting levels
+ * Handle groups of parenthesis for multiple nesting levels
*/
final String swappedToken = token.replace(')', '(');
@@ -236,8 +237,8 @@ public class ShuntingYard<TokenType> {
* Remove an operator from the list of shuntable operators.
*
* @param operator
- * The token representing the operator. If null, remove
- * all operators.
+ * The token representing the operator. If null, remove all
+ * operators.
*/
public void removeOp(final String operator) {
/*
diff --git a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java
index 8d5dda4..0895ad5 100644
--- a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java
+++ b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java
@@ -12,8 +12,7 @@ import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
-<<<<<<< Updated upstream
- * Customizable string escapes.
+ * <<<<<<< Updated upstream Customizable string escapes.
*
* @author Benjamin Culkin
*/
@@ -46,7 +45,8 @@ public class StringDescaper {
specialEscapes = new HashMap<>();
/* Set up the hard-coded escapes. */
- rEscapeString = String.format("\\\\(%1$s|%2$s|%3$s)", rShortEscape, rOctalEscape, rUnicodeEscape);
+ rEscapeString = String.format("\\\\(%1$s|%2$s|%3$s)", rShortEscape, rOctalEscape,
+ rUnicodeEscape);
escapePatt = Pattern.compile(rEscapeString);
}
@@ -54,12 +54,12 @@ public class StringDescaper {
* Add a new literal escape.
*
* @param escape
- * The custom escape to add.
+ * The custom escape to add.
* @param val
- * The value for the escape.
+ * The value for the escape.
*/
public void addLiteralEscape(String escape, String val) {
- if(literalEscapes.containsKey(escape)) {
+ if (literalEscapes.containsKey(escape)) {
LOGGER.warning(String.format("Shadowing literal escape '%s'\n", escape));
}
@@ -68,11 +68,11 @@ public class StringDescaper {
/**
* Create a new custom escape.
- *
+ *
* @param escape
- * The escape to add.
+ * The escape to add.
* @param val
- * The implementation of the escape.
+ * The implementation of the escape.
*/
public void addSpecialEscape(String escape, UnaryOperator<String> val) {
/*
@@ -82,7 +82,7 @@ public class StringDescaper {
Pattern patt = null;
try {
patt = Pattern.compile(escape);
- } catch(PatternSyntaxException psex) {
+ } catch (PatternSyntaxException psex) {
String msg = String.format("Invalid special escape '%s'", escape);
IllegalArgumentException iaex = new IllegalArgumentException(msg);
@@ -91,7 +91,7 @@ public class StringDescaper {
throw psex;
}
- if(specialEscapes.containsKey(patt)) {
+ if (specialEscapes.containsKey(patt)) {
LOGGER.warning(String.format("Shadowing special escape '%s'\n", escape));
}
@@ -104,24 +104,24 @@ public class StringDescaper {
public void compileEscapes() {
StringBuilder work = new StringBuilder();
- for(String litEscape : literalEscapes.keySet()) {
+ for (String litEscape : literalEscapes.keySet()) {
work.append("|(?:");
work.append(Pattern.quote(litEscape));
work.append(")");
}
- for(Pattern specEscape : specialEscapes.keySet()) {
+ for (Pattern specEscape : specialEscapes.keySet()) {
work.append("|(?:");
work.append(specEscape.toString());
work.append(")");
}
/*
- * Convert user-defined escapes to a regex for matching. We
- * don't need a bar before %4 because the string has it.
+ * Convert user-defined escapes to a regex for matching. We don't need a bar
+ * before %4 because the string has it.
*/
- rEscapeString = String.format("\\(%1$s|%2$s|%3$s%4$s)", rShortEscape, rOctalEscape, rUnicodeEscape,
- work.toString());
+ rEscapeString = String.format("\\(%1$s|%2$s|%3$s%4$s)", rShortEscape,
+ rOctalEscape, rUnicodeEscape, work.toString());
escapePatt = Pattern.compile(rEscapeString);
}
@@ -129,13 +129,13 @@ public class StringDescaper {
* Replace escape characters with their actual equivalents.
*
* @param inp
- * The string to replace escape sequences in.
+ * The string to replace escape sequences in.
*
* @return The string with escape sequences replaced by their equivalent
* characters.
*/
public String descapeString(final String inp) {
- if(inp == null) {
+ if (inp == null) {
throw new NullPointerException("Input to descapeString must not be null");
}
@@ -147,11 +147,10 @@ public class StringDescaper {
final Matcher escapeFinder = escapePatt.matcher(inp);
/* Go through each escape. */
- while(possibleEscapeFinder.find()) {
- if(!escapeFinder.find()) {
+ while (possibleEscapeFinder.find()) {
+ if (!escapeFinder.find()) {
/*
- * Found a possible escape that isn't actually
- * an escape.
+ * Found a possible escape that isn't actually an escape.
*/
final String msg = String.format(
"Illegal escape sequence '%s' at position %d of string '%s'",
@@ -165,7 +164,7 @@ public class StringDescaper {
* Convert the escape to a string.
*/
String escapeRep = "";
- switch(escapeSeq) {
+ switch (escapeSeq) {
case "\\b":
escapeRep = "\b";
break;
@@ -195,22 +194,23 @@ public class StringDescaper {
escapeRep = "\\";
break;
default:
- if(escapeSeq.startsWith("u")) {
+ if (escapeSeq.startsWith("u")) {
/* Handle a unicode escape. */
escapeRep = handleUnicodeEscape(escapeSeq.substring(1));
- } else if(escapeSeq.startsWith("O")) {
+ } else if (escapeSeq.startsWith("O")) {
/* Handle an octal escape. */
escapeRep = handleOctalEscape(escapeSeq.substring(1));
- } else if(literalEscapes.containsKey(escapeSeq)) {
+ } else if (literalEscapes.containsKey(escapeSeq)) {
/* Handle a custom literal escape. */
escapeRep = literalEscapes.get(escapeSeq);
} else {
/* Handle a custom special escape. */
- for(Entry<Pattern, UnaryOperator<String>> ent : specialEscapes.entrySet()) {
+ for (Entry<Pattern, UnaryOperator<String>> ent : specialEscapes
+ .entrySet()) {
Pattern pat = ent.getKey();
Matcher mat = pat.matcher(escapeSeq);
- if(mat.matches()) {
+ if (mat.matches()) {
escapeRep = ent.getValue().apply(escapeSeq);
break;
}
@@ -234,8 +234,9 @@ public class StringDescaper {
final int codepoint = Integer.parseInt(seq, 16);
return new String(Character.toChars(codepoint));
- } catch(final IllegalArgumentException iaex) {
- final String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq);
+ } catch (final IllegalArgumentException iaex) {
+ final String msg
+ = String.format("'%s' is not a valid Unicode escape sequence'", seq);
final IllegalArgumentException reiaex = new IllegalArgumentException(msg);
@@ -252,7 +253,7 @@ public class StringDescaper {
try {
final int codepoint = Integer.parseInt(seq, 8);
- if(codepoint > 255) {
+ if (codepoint > 255) {
final String msg = String
.format("'%d' is outside the range of octal escapes', codepoint");
@@ -260,8 +261,9 @@ public class StringDescaper {
}
return new String(Character.toChars(codepoint));
- } catch(final IllegalArgumentException iaex) {
- final String msg = String.format("'%s' is not a valid octal escape sequence'", seq);
+ } catch (final IllegalArgumentException iaex) {
+ final String msg
+ = String.format("'%s' is not a valid octal escape sequence'", seq);
final IllegalArgumentException reiaex = new IllegalArgumentException(msg);
diff --git a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java
index 7ad8b91..6cf2da5 100644
--- a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java
+++ b/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java
@@ -20,7 +20,8 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
/*
* Handle operators
*/
- private final class OperatorHandler implements UnaryOperator<ConstructorState<TokenType>> {
+ private final class OperatorHandler
+ implements UnaryOperator<ConstructorState<TokenType>> {
/* The handled element. */
private final TokenType element;
@@ -32,14 +33,14 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
@Override
public ConstructorState<TokenType> apply(final ConstructorState<TokenType> pair) {
/*
- * Replace the current AST with the result of handling
- * an operator
+ * Replace the current AST with the result of handling an operator
*/
- return new ConstructorState<>(pair.bindLeft(
- queuedASTs -> handleOperator(queuedASTs)));
+ return new ConstructorState<>(
+ pair.bindLeft(queuedASTs -> handleOperator(queuedASTs)));
}
- private ConstructorState<TokenType> handleOperator(final Deque<ITree<TokenType>> queuedASTs) {
+ private ConstructorState<TokenType>
+ handleOperator(final Deque<ITree<TokenType>> queuedASTs) {
/*
* The AST we're going to hand back
*/
@@ -48,14 +49,13 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
/*
* 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
+ * Error if we don't have enough for a binary operator
*/
- if(queuedASTs.size() < 2) {
+ if (queuedASTs.size() < 2) {
final String msg = String.format(
"Attempted to parse binary operator without enough operands\n\tProblem operator is: %s\n\tPossible operand is: %s",
element.toString(), queuedASTs.peek().toString());
@@ -67,7 +67,7 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
* Grab the two operands
*/
final ITree<TokenType> right = queuedASTs.pop();
- final ITree<TokenType> left = queuedASTs.pop();
+ final ITree<TokenType> left = queuedASTs.pop();
/*
* Create a new AST
@@ -94,27 +94,30 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
private final Predicate<TokenType> operatorPredicate;
/* The predicate for detecting special operators. */
- private final Predicate<TokenType> isSpecialOperator;
+ private final Predicate<TokenType> isSpecialOperator;
/* The function for handling special operators. */
- private final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator;
+ private final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator;
/**
* Create a new transformer
*
* @param initialState
- * The initial state of the transformer.
+ * The initial state of the transformer.
*
* @param operatorPredicate
- * The predicate to use to identify operators.
+ * The predicate to use to identify operators.
*
* @param isSpecialOperator
- * The predicate used to identify special operators.
+ * The predicate used to identify special
+ * operators.
*
* @param handleSpecialOperator
- * The function used for handling special operators.
+ * The function used for handling special
+ * operators.
*/
public TokenTransformer(final IHolder<ConstructorState<TokenType>> initialState,
- final Predicate<TokenType> operatorPredicate, final Predicate<TokenType> isSpecialOperator,
+ final Predicate<TokenType> operatorPredicate,
+ final Predicate<TokenType> isSpecialOperator,
final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) {
this.initialState = initialState;
this.operatorPredicate = operatorPredicate;
@@ -127,7 +130,7 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
/*
* Handle operators
*/
- if(operatorPredicate.test(element)) {
+ if (operatorPredicate.test(element)) {
initialState.transform(new OperatorHandler(element));
} else {
final ITree<TokenType> newAST = new Tree<>(element);
@@ -135,18 +138,11 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> {
/*
* Insert the new tree into the AST
*/
- initialState.transform(pair -> {
- /*
- * Transform the pair, ignoring the current AST
- * in favor of the one consisting of the current
- * element
- */
- return new ConstructorState<>(pair.bindLeft(queue -> {
- queue.push(newAST);
+ initialState.transform(pair -> new ConstructorState<>(pair.bindLeft(queue -> {
+ queue.push(newAST);
- return new Pair<>(queue, newAST);
- }));
- });
+ return new Pair<>(queue, newAST);
+ })));
}
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java
index fbffd82..7c3c2ab 100644
--- a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java
+++ b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java
@@ -21,9 +21,8 @@ import bjc.utils.parserutils.splitter.TokenSplitter;
*/
public class TokenUtils {
/**
- * Simple implementation of TokenSplitter for removing double-quoted
- * strings.
- *
+ * Simple implementation of TokenSplitter for removing double-quoted strings.
+ *
* @author EVE
*
*/
@@ -39,17 +38,17 @@ public class TokenUtils {
*/
/* Possible string escapes. */
- private static String rPossibleEscapeString = getRegex("possibleStringEscape");
- private static Pattern possibleEscapePatt = Pattern.compile(rPossibleEscapeString);
+ private static String rPossibleEscapeString = getRegex("possibleStringEscape");
+ private static Pattern possibleEscapePatt = Pattern.compile(rPossibleEscapeString);
/* Non-single char escapes. */
- private static String rShortEscape = getRegex("shortFormStringEscape");
- private static String rOctalEscape = getRegex("octalStringEscape");
- private static String rUnicodeEscape = getRegex("unicodeStringEscape");
+ private static String rShortEscape = getRegex("shortFormStringEscape");
+ private static String rOctalEscape = getRegex("octalStringEscape");
+ private static String rUnicodeEscape = getRegex("unicodeStringEscape");
/* All string escapes. */
- private static String rEscapeString = applyFormat("stringEscape",
- rShortEscape, rOctalEscape, rUnicodeEscape);
+ private static String rEscapeString
+ = applyFormat("stringEscape", rShortEscape, rOctalEscape, rUnicodeEscape);
private static Pattern escapePatt = Pattern.compile(rEscapeString);
@@ -61,7 +60,7 @@ public class TokenUtils {
private static Pattern quotePatt = getCompiledRegex("unescapedQuote");
/* This may do something. */
- //private static Pattern intLitPattern = getCompiledRegex("intLiteral");
+ // private static Pattern intLitPattern = getCompiledRegex("intLiteral");
/**
* Remove double quoted strings from a string.
@@ -69,29 +68,29 @@ public class TokenUtils {
* Splits a string around instances of java-style double-quoted strings.
*
* @param inp
- * The string to split.
+ * The string to split.
*
- * @return
- * An list containing alternating bits of the string and the embedded double-quoted
- * strings that separated them.
+ * @return An list containing alternating bits of the string and the embedded
+ * double-quoted strings that separated them.
*/
public static List<String> removeDQuotedStrings(final String inp) {
/* Validate input. */
- if (inp == null) throw new NullPointerException("inp must not be null");
+ if (inp == null)
+ throw new NullPointerException("inp must not be null");
/*
* What we need for piece-by-piece string building
*/
- StringBuffer work = new StringBuffer();
+ StringBuffer work = new StringBuffer();
final List<String> res = new LinkedList<>();
/*
* Matcher for proper strings and single quotes.
*/
- final Matcher mt = doubleQuotePatt.matcher(inp);
+ final Matcher mt = doubleQuotePatt.matcher(inp);
final Matcher corr = quotePatt.matcher(inp);
- if(corr.find() && !corr.find()) {
+ if (corr.find() && !corr.find()) {
/*
* There's a unmatched opening quote with no strings.
*/
@@ -110,8 +109,8 @@ public class TokenUtils {
mt.appendReplacement(work, "");
/*
- * Add the string preceding the double-quoted string and
- * the double-quoted string to the list.
+ * Add the string preceding the double-quoted string and the double-quoted
+ * string to the list.
*/
res.add(work.toString());
res.add(mt.group(1));
@@ -128,10 +127,9 @@ public class TokenUtils {
mt.appendTail(work);
final String tail = work.toString();
- if(tail.contains("\"")) {
+ if (tail.contains("\"")) {
/*
- * There's a unmatched opening quote with at least one
- * string.
+ * There's a unmatched opening quote with at least one string.
*/
final String msg = String.format(
"Unclosed string literal '%s'. Opening quote was at position %d", inp,
@@ -143,7 +141,7 @@ public class TokenUtils {
/*
* Only add an empty tail if the string was empty.
*/
- if(!tail.equals("") || res.isEmpty()) {
+ if (!tail.equals("") || res.isEmpty()) {
res.add(tail);
}
@@ -153,34 +151,35 @@ public class TokenUtils {
/**
* Replace escape characters with their actual equivalents.
*
- * Use {@link StringDescaper} for customizable escapes. This only handles the ones that are
- * built into Java strings.
+ * Use {@link StringDescaper} for customizable escapes. This only handles the
+ * ones that are built into Java strings.
*
* @param inp
- * The string to replace escape sequences in.
+ * The string to replace escape sequences in.
*
* @return The string with escape sequences replaced by their equivalent
* characters.
*/
public static String descapeString(final String inp) {
/* Validate input. */
- if (inp == null) throw new NullPointerException("inp must not be null");
+ if (inp == null)
+ throw new NullPointerException("inp must not be null");
/*
* Prepare the buffer and escape finder.
*/
- final StringBuffer work = new StringBuffer();
+ final StringBuffer work = new StringBuffer();
final Matcher possibleEscapeFinder = possibleEscapePatt.matcher(inp);
- final Matcher escapeFinder = escapePatt.matcher(inp);
+ final Matcher escapeFinder = escapePatt.matcher(inp);
/* Go through all possible escapes. */
while (possibleEscapeFinder.find()) {
if (!escapeFinder.find()) {
/*
- * Found a possible escape that isn't actually
- * an escape.
+ * Found a possible escape that isn't actually an escape.
*/
- final String msg = String.format("Illegal escape sequence '%s' at position %d",
+ final String msg = String.format(
+ "Illegal escape sequence '%s' at position %d",
possibleEscapeFinder.group(), possibleEscapeFinder.start());
throw new IllegalArgumentException(msg);
@@ -192,7 +191,7 @@ public class TokenUtils {
* Convert the escape to a string.
*/
String escapeRep = "";
- switch(escapeSeq) {
+ switch (escapeSeq) {
case "\\b":
escapeRep = "\b";
break;
@@ -247,8 +246,9 @@ public class TokenUtils {
final int codepoint = Integer.parseInt(seq, 16);
return new String(Character.toChars(codepoint));
- } catch(final IllegalArgumentException iaex) {
- final String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq);
+ } catch (final IllegalArgumentException iaex) {
+ final String msg
+ = String.format("'%s' is not a valid Unicode escape sequence'", seq);
final IllegalArgumentException reiaex = new IllegalArgumentException(msg);
@@ -265,7 +265,7 @@ public class TokenUtils {
try {
final int codepoint = Integer.parseInt(seq, 8);
- if(codepoint > 255) {
+ if (codepoint > 255) {
final String msg = String
.format("'%d' is outside the range of octal escapes', codepoint");
@@ -273,8 +273,9 @@ public class TokenUtils {
}
return new String(Character.toChars(codepoint));
- } catch(final IllegalArgumentException iaex) {
- final String msg = String.format("'%s' is not a valid octal escape sequence'", seq);
+ } catch (final IllegalArgumentException iaex) {
+ final String msg
+ = String.format("'%s' is not a valid octal escape sequence'", seq);
final IllegalArgumentException reiaex = new IllegalArgumentException(msg);
@@ -285,11 +286,11 @@ public class TokenUtils {
}
/**
- * Check if a given string would be successfully converted to a double
- * by {@link Double#parseDouble(String)}.
+ * Check if a given string would be successfully converted to a double by
+ * {@link Double#parseDouble(String)}.
*
* @param inp
- * The string to check.
+ * The string to check.
* @return Whether the string is a valid double or not.
*/
public static boolean isDouble(final String inp) {
@@ -297,21 +298,21 @@ public class TokenUtils {
}
/**
- * Check if a given string would be successfully converted to a integer
- * by {@link Integer#parseInt(String)}.
+ * Check if a given string would be successfully converted to a integer by
+ * {@link Integer#parseInt(String)}.
*
- * NOTE: This only checks syntax. Using values out of the range of
- * integers will still cause errors.
+ * NOTE: This only checks syntax. Using values out of the range of integers will
+ * still cause errors.
*
* @param inp
- * The input to check.
+ * The input to check.
* @return Whether the string is a valid integer or not.
*/
public static boolean isInt(final String inp) {
try {
Integer.parseInt(inp);
return true;
- } catch(NumberFormatException nfex) {
+ } catch (NumberFormatException nfex) {
return false;
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java
index 1ebc2d5..3c7509b 100644
--- a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java
+++ b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java
@@ -23,21 +23,25 @@ public class TreeConstructor {
* Alias interface for special operator types.
*
* @param <TokenType>
- * The token type of the tree.
+ * The token type of the tree.
*/
- public interface QueueFlattener<TokenType> extends Function<Deque<ITree<TokenType>>, ITree<TokenType>> {
+ public interface QueueFlattener<TokenType>
+ extends Function<Deque<ITree<TokenType>>, ITree<TokenType>> {
/*
* Alias
*/
}
/* Alias for constructor state. */
- static final class ConstructorState<TokenType> extends Pair<Deque<ITree<TokenType>>, ITree<TokenType>> {
- public ConstructorState(final Deque<ITree<TokenType>> left, final ITree<TokenType> right) {
+ static final class ConstructorState<TokenType>
+ extends Pair<Deque<ITree<TokenType>>, ITree<TokenType>> {
+ public ConstructorState(final Deque<ITree<TokenType>> left,
+ final ITree<TokenType> right) {
super(left, right);
}
- public ConstructorState(final IPair<Deque<ITree<TokenType>>, ITree<TokenType>> par) {
+ public ConstructorState(
+ final IPair<Deque<ITree<TokenType>>, ITree<TokenType>> par) {
super(par.getLeft(), par.getRight());
}
}
@@ -48,19 +52,19 @@ public class TreeConstructor {
* Only binary operators are accepted.
*
* @param <TokenType>
- * The elements of the parse tree.
+ * The elements of the parse tree.
*
* @param tokens
- * The list of tokens to build a tree from.
+ * The list of tokens to build a tree from.
*
* @param isOperator
- * The predicate to use to determine if something is a
- * operator.
+ * The predicate to use to determine if something is a
+ * operator.
*
* @return A AST from the expression.
*/
- public static <TokenType> ITree<TokenType> constructTree(final IList<TokenType> tokens,
- final Predicate<TokenType> isOperator) {
+ public static <TokenType> ITree<TokenType> constructTree(
+ final IList<TokenType> tokens, final Predicate<TokenType> isOperator) {
/* Construct a tree with no special operators */
return constructTree(tokens, isOperator, op -> false, null);
}
@@ -68,43 +72,47 @@ 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.
+ * Only binary operators are accepted by default. Use the last two parameters to
+ * handle non-binary operators.
*
* @param <TokenType>
- * The elements of the parse tree.
+ * The elements of the parse tree.
*
* @param tokens
- * The list of tokens to build a tree from.
+ * The list of tokens to build a tree from.
*
* @param isOperator
- * The predicate to use to determine if something is a operator.
+ * The predicate to use to determine if something
+ * is a operator.
*
* @param isSpecialOperator
- * The predicate to use to determine if an operator needs special
- * handling.
+ * The predicate to use to determine if an operator
+ * needs special handling.
*
* @param handleSpecialOperator
- * The function to use to handle special case operators.
+ * The function to use to handle special case
+ * operators.
*
* @return A AST from the expression.
*
*/
- public static <TokenType> ITree<TokenType> constructTree(final IList<TokenType> tokens,
- final Predicate<TokenType> isOperator, final Predicate<TokenType> isSpecialOperator,
+ public static <TokenType> ITree<TokenType> constructTree(
+ final IList<TokenType> tokens, final Predicate<TokenType> isOperator,
+ final Predicate<TokenType> isSpecialOperator,
final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) {
/*
* Make sure our parameters are valid
*/
- if(tokens == null)
+ if (tokens == null)
throw new NullPointerException("Tokens must not be null");
- else if(isOperator == null)
+ else if (isOperator == null)
throw new NullPointerException("Operator predicate must not be null");
- else if(isSpecialOperator == null)
- throw new NullPointerException("Special operator determiner must not be null");
+ else if (isSpecialOperator == null)
+ throw new NullPointerException(
+ "Special operator determiner must not be null");
- final ConstructorState<TokenType> cstate = new ConstructorState<>(
- new LinkedList<>(), null);
+ final ConstructorState<TokenType> cstate
+ = new ConstructorState<>(new LinkedList<>(), null);
/* Here is the state for the tree construction */
final IHolder<ConstructorState<TokenType>> initialState = new Identity<>(cstate);
@@ -116,6 +124,6 @@ public class TreeConstructor {
tokens.forEach(trans);
/* Grab the tree from the state */
- return initialState.unwrap(pair -> pair.getRight());
+ return initialState.unwrap(ConstructorState::getRight);
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java b/base/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java
index a939971..2dad9c6 100644
--- a/base/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java
+++ b/base/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java
@@ -22,12 +22,12 @@ public class IteratedDefine implements UnaryOperator<String> {
* Create a new iterated define.
*
* @param pattern
- * The pattern to use for matching.
+ * The pattern to use for matching.
* @param circular
- * Whether or not to loop through the list of replacers, or just
- * repeat the last one.
+ * Whether or not to loop through the list of replacers, or
+ * just repeat the last one.
* @param replacers
- * The set of replacement strings to use.
+ * The set of replacement strings to use.
*/
public IteratedDefine(Pattern pattern, boolean circular, String... replacers) {
patt = pattern;
@@ -40,7 +40,7 @@ public class IteratedDefine implements UnaryOperator<String> {
Matcher mat = patt.matcher(ln);
StringBuffer sb = new StringBuffer();
- while(mat.find()) {
+ while (mat.find()) {
String repl = repls.next();
mat.appendReplacement(sb, repl);
diff --git a/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java b/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java
index 032c33e..b31d937 100644
--- a/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java
+++ b/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java
@@ -17,9 +17,9 @@ public class SimpleDefine implements UnaryOperator<String> {
* Create a new simple define.
*
* @param pattern
- * The pattern to match against.
+ * The pattern to match against.
* @param replace
- * The text to use as a replacement.
+ * The text to use as a replacement.
*/
public SimpleDefine(Pattern pattern, String replace) {
patt = pattern;
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java
index 427b4cf..9c4d4bc 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java
@@ -10,7 +10,7 @@ public class DelimiterException extends RuntimeException {
* Create a new generic delimiter exception.
*
* @param res
- * The reason for this exception.
+ * The reason for this exception.
*/
public DelimiterException(final String res) {
super(res);
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java
index 96830b2..ba61531 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java
@@ -24,7 +24,7 @@ import bjc.funcdata.IList;
* @author EVE
*
* @param <T>
- * The type of items in the sequence.
+ * The type of items in the sequence.
*/
public class DelimiterGroup<T> {
/**
@@ -54,10 +54,10 @@ public class DelimiterGroup<T> {
* Create a new instance of a delimiter group.
*
* @param open
- * The item that opened this group.
+ * The item that opened this group.
*
* @param parms
- * Any parameters from the opener.
+ * Any parameters from the opener.
*/
public OpenGroup(final T open, final T[] parms) {
opener = open;
@@ -72,7 +72,7 @@ public class DelimiterGroup<T> {
* Add an item to this group instance.
*
* @param itm
- * The item to add to this group instance.
+ * The item to add to this group instance.
*/
public void addItem(final ITree<T> itm) {
currentGroup.add(itm);
@@ -82,33 +82,33 @@ public class DelimiterGroup<T> {
* Mark a subgroup.
*
* @param marker
- * The item that indicated this subgroup.
+ * The item that indicated this subgroup.
*
* @param chars
- * The characteristics for building the tree.
+ * The characteristics for building the tree.
*/
public void markSubgroup(final T marker, final SequenceCharacteristics<T> chars) {
/*
* Add all of the contents to the subgroup.
*/
final ITree<T> subgroupContents = new Tree<>(chars.contents);
- for(final ITree<T> itm : currentGroup) {
+ for (final ITree<T> itm : currentGroup) {
subgroupContents.addChild(itm);
}
/*
* Handle subordinate sub-groups.
*/
- while(!contents.isEmpty()) {
+ while (!contents.isEmpty()) {
final ITree<T> possibleSubordinate = contents.peek();
/*
* Subordinate lower priority subgroups.
*/
- if(possibleSubordinate.getHead().equals(chars.subgroup)) {
+ if (possibleSubordinate.getHead().equals(chars.subgroup)) {
final T otherMarker = possibleSubordinate.getChild(1).getHead();
- if(subgroups.get(marker) > subgroups.get(otherMarker)) {
+ if (subgroups.get(marker) > subgroups.get(otherMarker)) {
subgroupContents.prependChild(contents.pop());
} else {
break;
@@ -118,7 +118,8 @@ public class DelimiterGroup<T> {
}
}
- final Tree<T> subgroup = new Tree<>(chars.subgroup, subgroupContents, new Tree<>(marker));
+ final Tree<T> subgroup
+ = new Tree<>(chars.subgroup, subgroupContents, new Tree<>(marker));
contents.push(subgroup);
@@ -129,10 +130,10 @@ public class DelimiterGroup<T> {
* Convert this group into a tree.
*
* @param closer
- * The item that closed this group.
+ * The item that closed this group.
*
* @param chars
- * The characteristics for building the tree.
+ * The characteristics for building the tree.
*
* @return This group as a tree.
*/
@@ -140,7 +141,7 @@ public class DelimiterGroup<T> {
/*
* Mark any implied subgroups.
*/
- if(impliedSubgroups.containsKey(closer)) {
+ if (impliedSubgroups.containsKey(closer)) {
markSubgroup(impliedSubgroups.get(closer), chars);
}
@@ -148,13 +149,13 @@ public class DelimiterGroup<T> {
final ITree<T> res = new Tree<>(chars.contents);
/*
- * Add either the contents of the current group, or
- * subgroups if they're there.
+ * Add either the contents of the current group, or subgroups if they're
+ * there.
*/
- if(contents.isEmpty()) {
+ if (contents.isEmpty()) {
currentGroup.forEach(res::addChild);
} else {
- while(!contents.isEmpty()) {
+ while (!contents.isEmpty()) {
res.prependChild(contents.poll());
}
@@ -183,7 +184,7 @@ public class DelimiterGroup<T> {
* Check if a group is excluded at the top level of this group.
*
* @param grupName
- * The group to check.
+ * The group to check.
*
* @return Whether or not the provided group is excluded.
*/
@@ -195,16 +196,17 @@ public class DelimiterGroup<T> {
* Check if the provided delimiter would close this group.
*
* @param del
- * The string to check as a closing delimiter.
+ * The string to check as a closing delimiter.
*
- * @return Whether or not the provided delimiter closes this
- * group.
+ * @return Whether or not the provided delimiter closes this group.
*/
public boolean isClosing(final T del) {
- if(closingDelimiters.contains(del)) return true;
+ if (closingDelimiters.contains(del))
+ return true;
- for(final BiPredicate<T, T[]> pred : predClosers) {
- if(pred.test(del, params)) return true;
+ for (final BiPredicate<T, T[]> pred : predClosers) {
+ if (pred.test(del, params))
+ return true;
}
return closingDelimiters.contains(del);
@@ -229,11 +231,9 @@ public class DelimiterGroup<T> {
}
/**
- * Get the groups that are allowed to open anywhere inside this
- * group.
+ * Get the groups that are allowed to open anywhere inside this group.
*
- * @return The groups allowed to open anywhere inside this
- * group.
+ * @return The groups allowed to open anywhere inside this group.
*/
public Map<T, T> getNestingOpeners() {
return nestedOpenDelimiters;
@@ -243,7 +243,7 @@ public class DelimiterGroup<T> {
* Checks if a given token marks a subgroup.
*
* @param tok
- * The token to check.
+ * The token to check.
*
* @return Whether or not the token marks a subgroup.
*/
@@ -255,18 +255,19 @@ public class DelimiterGroup<T> {
* Checks if a given token opens a group.
*
* @param marker
- * The token to check.
+ * The token to check.
*
- * @return The name of the group T opens, or null if it doesn't
- * open one.
+ * @return The name of the group T opens, or null if it doesn't open one.
*/
public IPair<T, T[]> doesOpen(final T marker) {
- if(openDelimiters.containsKey(marker)) return new Pair<>(openDelimiters.get(marker), null);
+ if (openDelimiters.containsKey(marker))
+ return new Pair<>(openDelimiters.get(marker), null);
- for(final Function<T, IPair<T, T[]>> pred : predOpeners) {
+ for (final Function<T, IPair<T, T[]>> pred : predOpeners) {
final IPair<T, T[]> par = pred.apply(marker);
- if(par.getLeft() != null) return par;
+ if (par.getLeft() != null)
+ return par;
}
return new Pair<>(null, null);
@@ -303,8 +304,7 @@ public class DelimiterGroup<T> {
private final Set<T> groupExclusions;
/*
- * Mapping from sub-group delimiters, to any sub-groups enclosed in
- * them.
+ * Mapping from sub-group delimiters, to any sub-groups enclosed in them.
*/
private final Map<T, Integer> subgroups;
@@ -324,10 +324,11 @@ public class DelimiterGroup<T> {
* Create a new empty delimiter group.
*
* @param name
- * The name of the delimiter group
+ * The name of the delimiter group
*/
public DelimiterGroup(final T name) {
- if(name == null) throw new NullPointerException("Group name must not be null");
+ if (name == null)
+ throw new NullPointerException("Group name must not be null");
groupName = name;
@@ -350,22 +351,22 @@ public class DelimiterGroup<T> {
* Adds one or more delimiters that close this group.
*
* @param closers
- * Delimiters that close this group.
+ * Delimiters that close this group.
*/
@SafeVarargs
public final void addClosing(final T... closers) {
final List<T> closerList = Arrays.asList(closers);
- for(final T closer : closerList) {
- if(closer == null) {
+ for (final T closer : closerList) {
+ if (closer == null) {
throw new NullPointerException("Closing delimiter must not be null");
- } else if(closer.equals("")) {
+ } else if (closer.equals("")) {
/*
- * We can do this because equals works on
- * arbitrary objects, not just those of the same
- * type.
+ * We can do this because equals works on arbitrary objects, not just
+ * those of the same type.
*/
- throw new IllegalArgumentException("Empty string is not a valid exclusion");
+ throw new IllegalArgumentException(
+ "Empty string is not a valid exclusion");
} else {
closingDelimiters.add(closer);
}
@@ -373,24 +374,23 @@ public class DelimiterGroup<T> {
}
/**
- * Adds one or more groups that cannot occur in the top level of this
- * group.
+ * Adds one or more groups that cannot occur in the top level of this group.
*
* @param exclusions
- * The groups forbidden in the top level of this group.
+ * The groups forbidden in the top level of this group.
*/
@SafeVarargs
public final void addTopLevelForbid(final T... exclusions) {
- for(final T exclusion : exclusions) {
- if(exclusion == null) {
+ for (final T exclusion : exclusions) {
+ if (exclusion == null) {
throw new NullPointerException("Exclusion must not be null");
- } else if(exclusion.equals("")) {
+ } else if (exclusion.equals("")) {
/*
- * We can do this because equals works on
- * arbitrary objects, not just those of the same
- * type.
+ * We can do this because equals works on arbitrary objects, not just
+ * those of the same type.
*/
- throw new IllegalArgumentException("Empty string is not a valid exclusion");
+ throw new IllegalArgumentException(
+ "Empty string is not a valid exclusion");
} else {
topLevelExclusions.add(exclusion);
}
@@ -401,20 +401,20 @@ public class DelimiterGroup<T> {
* Adds one or more groups that cannot occur at all in this group.
*
* @param exclusions
- * The groups forbidden inside this group.
+ * The groups forbidden inside this group.
*/
@SafeVarargs
public final void addGroupForbid(final T... exclusions) {
- for(final T exclusion : exclusions) {
- if(exclusion == null) {
+ for (final T exclusion : exclusions) {
+ if (exclusion == null) {
throw new NullPointerException("Exclusion must not be null");
- } else if(exclusion.equals("")) {
+ } else if (exclusion.equals("")) {
/*
- * We can do this because equals works on
- * arbitrary objects, not just those of the same
- * type.
+ * We can do this because equals works on arbitrary objects, not just
+ * those of the same type.
*/
- throw new IllegalArgumentException("Empty string is not a valid exclusion");
+ throw new IllegalArgumentException(
+ "Empty string is not a valid exclusion");
} else {
groupExclusions.add(exclusion);
}
@@ -425,13 +425,14 @@ public class DelimiterGroup<T> {
* Adds sub-group markers to this group.
*
* @param subgroup
- * The token to mark a sub-group.
+ * The token to mark a sub-group.
*
* @param priority
- * The priority of this sub-group.
+ * The priority of this sub-group.
*/
public void addSubgroup(final T subgroup, final int priority) {
- if(subgroup == null) throw new NullPointerException("Subgroup marker must not be null");
+ if (subgroup == null)
+ throw new NullPointerException("Subgroup marker must not be null");
subgroups.put(subgroup, priority);
}
@@ -440,15 +441,16 @@ public class DelimiterGroup<T> {
* Adds a marker that opens a group at the top level of this group.
*
* @param opener
- * The marker that opens the group.
+ * The marker that opens the group.
*
* @param group
- * The group opened by the marker.
+ * The group opened by the marker.
*/
public void addOpener(final T opener, final T group) {
- if(opener == null)
+ if (opener == null)
throw new NullPointerException("Opener must not be null");
- else if(group == null) throw new NullPointerException("Group to open must not be null");
+ else if (group == null)
+ throw new NullPointerException("Group to open must not be null");
openDelimiters.put(opener, group);
}
@@ -457,15 +459,15 @@ public class DelimiterGroup<T> {
* Adds a marker that opens a group inside of this group.
*
* @param opener
- * The marker that opens the group.
+ * The marker that opens the group.
*
* @param group
- * The group opened by the marker.
+ * The group opened by the marker.
*/
public void addNestedOpener(final T opener, final T group) {
- if(opener == null) {
+ if (opener == null) {
throw new NullPointerException("Opener must not be null");
- } else if(group == null) {
+ } else if (group == null) {
throw new NullPointerException("Group to open must not be null");
}
@@ -476,20 +478,22 @@ public class DelimiterGroup<T> {
* Mark a closing delimiter as implying a subgroup.
*
* @param closer
- * The closing delimiter.
+ * The closing delimiter.
*
* @param subgroup
- * The subgroup to imply.
+ * The subgroup to imply.
*/
public void implySubgroup(final T closer, final T subgroup) {
- if(closer == null) {
+ if (closer == null) {
throw new NullPointerException("Closer must not be null");
- } else if(subgroup == null) {
+ } else if (subgroup == null) {
throw new NullPointerException("Subgroup must not be null");
- } else if(!closingDelimiters.contains(closer)) {
- throw new IllegalArgumentException(String.format("No closing delimiter '%s' defined", closer));
- } else if(!subgroups.containsKey(subgroup)) {
- throw new IllegalArgumentException(String.format("No subgroup '%s' defined", subgroup));
+ } else if (!closingDelimiters.contains(closer)) {
+ throw new IllegalArgumentException(
+ String.format("No closing delimiter '%s' defined", closer));
+ } else if (!subgroups.containsKey(subgroup)) {
+ throw new IllegalArgumentException(
+ String.format("No subgroup '%s' defined", subgroup));
}
impliedSubgroups.put(closer, subgroup);
@@ -506,26 +510,26 @@ public class DelimiterGroup<T> {
builder.append("], ");
builder.append("closingDelimiters=[");
- for(final T closer : closingDelimiters) {
+ for (final T closer : closingDelimiters) {
builder.append(closer + ",");
}
builder.deleteCharAt(builder.length() - 1);
builder.append("]");
- if(topLevelExclusions != null && !topLevelExclusions.isEmpty()) {
+ if (topLevelExclusions != null && !topLevelExclusions.isEmpty()) {
builder.append(", ");
builder.append("topLevelExclusions=[");
- for(final T exclusion : topLevelExclusions) {
+ for (final T exclusion : topLevelExclusions) {
builder.append(exclusion + ",");
}
builder.deleteCharAt(builder.length() - 1);
builder.append("]");
}
- if(groupExclusions != null && !groupExclusions.isEmpty()) {
+ if (groupExclusions != null && !groupExclusions.isEmpty()) {
builder.append(", ");
builder.append("groupExclusions=[");
- for(final T exclusion : groupExclusions) {
+ for (final T exclusion : groupExclusions) {
builder.append(exclusion + ",");
}
builder.deleteCharAt(builder.length() - 1);
@@ -541,10 +545,10 @@ public class DelimiterGroup<T> {
* Open an instance of this group.
*
* @param opener
- * The item that opened this group.
+ * The item that opened this group.
*
* @param parms
- * The parameters that opened this group
+ * The parameters that opened this group
*
* @return An opened instance of this group.
*/
@@ -556,7 +560,7 @@ public class DelimiterGroup<T> {
* Adds a predicated opener to the top level of this group.
*
* @param pred
- * The predicate that defines the opener and its parameters.
+ * The predicate that defines the opener and its parameters.
*/
public void addPredOpener(final Function<T, IPair<T, T[]>> pred) {
predOpeners.add(pred);
@@ -566,7 +570,7 @@ public class DelimiterGroup<T> {
* Adds a predicated closer to the top level of this group.
*
* @param pred
- * The predicate that defines the closer.
+ * The predicate that defines the closer.
*/
public void addPredCloser(final BiPredicate<T, T[]> pred) {
predClosers.add(pred);
@@ -576,7 +580,7 @@ public class DelimiterGroup<T> {
* Set whether or not this group starts a new nesting set.
*
* @param forgetful
- * Whether this group starts a new nesting set.
+ * Whether this group starts a new nesting set.
*/
public void setForgetful(final boolean forgetful) {
this.forgetful = forgetful;
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java b/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java
index a3c831e..8cc08ad 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java
@@ -16,7 +16,7 @@ public class RegexCloser implements BiPredicate<String, String[]> {
* Create a new regex closer.
*
* @param closer
- * The format string to use for closing.
+ * The format string to use for closing.
*/
public RegexCloser(final String closer) {
rep = closer;
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java
index 64dc81c..f08201c 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java
@@ -23,10 +23,10 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> {
* Create a new regex opener.
*
* @param groupName
- * The name of the opened group.
+ * The name of the opened group.
*
* @param groupRegex
- * The regex that matches the opener.
+ * The regex that matches the opener.
*/
public RegexOpener(final String groupName, final String groupRegex) {
name = groupName;
@@ -38,12 +38,12 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> {
public IPair<String, String[]> apply(final String str) {
final Matcher m = patt.matcher(str);
- if(m.matches()) {
+ if (m.matches()) {
final int numGroups = m.groupCount();
final String[] parms = new String[numGroups + 1];
- for(int i = 0; i <= numGroups; i++) {
+ for (int i = 0; i <= numGroups; i++) {
parms[i] = m.group(i);
}
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java b/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java
index 9e4c167..e48e341 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java
@@ -6,7 +6,7 @@ package bjc.utils.parserutils.delims;
* @author EVE
*
* @param <T>
- * The type of item in the tree.
+ * The type of item in the tree.
*/
public class SequenceCharacteristics<T> {
/**
@@ -29,11 +29,11 @@ public class SequenceCharacteristics<T> {
* Create a new set of parameters for building a tree.
*
* @param root
- * The root marker.
+ * The root marker.
* @param contents
- * The group/subgroup contents marker.
+ * The group/subgroup contents marker.
* @param subgroup
- * The subgroup marker.
+ * The subgroup marker.
*/
public SequenceCharacteristics(final T root, final T contents, final T subgroup) {
this.root = root;
@@ -55,23 +55,32 @@ public class SequenceCharacteristics<T> {
@Override
public boolean equals(final Object obj) {
- if(this == obj) return true;
- if(obj == null) return false;
- if(!(obj instanceof SequenceCharacteristics)) return false;
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (!(obj instanceof SequenceCharacteristics))
+ return false;
final SequenceCharacteristics<?> other = (SequenceCharacteristics<?>) obj;
- if(contents == null) {
- if(other.contents != null) return false;
- } else if(!contents.equals(other.contents)) return false;
-
- if(root == null) {
- if(other.root != null) return false;
- } else if(!root.equals(other.root)) return false;
-
- if(subgroup == null) {
- if(other.subgroup != null) return false;
- } else if(!subgroup.equals(other.subgroup)) return false;
+ if (contents == null) {
+ if (other.contents != null)
+ return false;
+ } else if (!contents.equals(other.contents))
+ return false;
+
+ if (root == null) {
+ if (other.root != null)
+ return false;
+ } else if (!root.equals(other.root))
+ return false;
+
+ if (subgroup == null) {
+ if (other.subgroup != null)
+ return false;
+ } else if (!subgroup.equals(other.subgroup))
+ return false;
return true;
}
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java
index 7424770..3e87abe 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java
@@ -24,7 +24,7 @@ import bjc.utils.funcutils.StringUtils;
* @author EVE
*
* @param <T>
- * The type of items in the sequence.
+ * The type of items in the sequence.
*/
public class SequenceDelimiter<T> {
/* Mapping from group names to actual groups. */
@@ -39,11 +39,10 @@ public class SequenceDelimiter<T> {
}
/**
- * Convert a linear sequence into a tree that matches the delimiter
- * structure.
+ * Convert a linear sequence into a tree that matches the delimiter structure.
*
- * Essentially, creates a parse tree of the expression against the
- * following grammar while obeying the defined grouping rules.
+ * Essentially, creates a parse tree of the expression against the following
+ * grammar while obeying the defined grouping rules.
*
* <pre>
* <tree> → (<data> | <subgroup> | <group>)*
@@ -57,39 +56,37 @@ public class SequenceDelimiter<T> {
* </pre>
*
* @param chars
- * The parameters on how to mark certain portions of the tree.
+ * The parameters on how to mark certain portions of the tree.
* @param seq
- * The sequence to delimit.
+ * The sequence to delimit.
*
- * @return The sequence as a tree that matches its group structure. Each
- * node in the tree is either a data node, a subgroup node, or a
- * group node.
+ * @return The sequence as a tree that matches its group structure. Each node in
+ * the tree is either a data node, a subgroup node, or a group node.
*
- * A data node is a leaf node whose data is the string it
- * represents.
+ * A data node is a leaf node whose data is the string it represents.
*
- * A subgroup node is a node with two children, and the name of
- * the sub-group as its label. The first child is the contents
- * of the sub-group, and the second is the marker that started
- * the subgroup. The marker is a leaf node labeled with its
- * contents, and the contents contains a recursive tree.
+ * A subgroup node is a node with two children, and the name of the
+ * sub-group as its label. The first child is the contents of the
+ * sub-group, and the second is the marker that started the subgroup.
+ * The marker is a leaf node labeled with its contents, and the contents
+ * contains a recursive tree.
*
- * A group node is a node with three children, and the name of
- * the group as its label. The first child is the opening
- * delimiter, the second is the group contents, and the third is
- * the closing delimiter. The delimiters are leaf nodes labeled
- * with their contents, while the group node contains a
- * recursive tree.
+ * A group node is a node with three children, and the name of the group
+ * as its label. The first child is the opening delimiter, the second is
+ * the group contents, and the third is the closing delimiter. The
+ * delimiters are leaf nodes labeled with their contents, while the
+ * group node contains a recursive tree.
*
* @throws DelimiterException
- * Thrown if something went wrong during sequence delimitation.
+ * Thrown if something went wrong during sequence
+ * delimitation.
*
*/
public ITree<T> delimitSequence(final SequenceCharacteristics<T> chars,
@SuppressWarnings("unchecked") final T... seq) throws DelimiterException {
- if(initialGroup == null) {
+ if (initialGroup == null) {
throw new NullPointerException("Initial group must be specified.");
- } else if(chars == null) {
+ } else if (chars == null) {
throw new NullPointerException("Sequence characteristics must not be null");
}
@@ -113,21 +110,20 @@ public class SequenceDelimiter<T> {
/*
* Process each member of the sequence.
*/
- for(int i = 0; i < seq.length; i++) {
+ for (int i = 0; i < seq.length; i++) {
final T tok = seq[i];
/* Check if this token could open a group. */
final IPair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok);
T possibleOpen = possibleOpenPar.getLeft();
- if(possibleOpen == null) {
+ if (possibleOpen == null) {
/*
* Handle nested openers.
*
- * Local openers take priority over nested ones
- * if they overlap.
+ * Local openers take priority over nested ones if they overlap.
*/
- if(allowedDelimiters.top().containsKey(tok)) {
+ if (allowedDelimiters.top().containsKey(tok)) {
possibleOpen = allowedDelimiters.top().get(tok).iterator().next();
}
}
@@ -135,59 +131,61 @@ public class SequenceDelimiter<T> {
/*
* If we have an opening delimiter, handle it.
*/
- if(possibleOpen != null) {
+ if (possibleOpen != null) {
final DelimiterGroup<T> group = groups.get(possibleOpen);
/*
- * Error on groups that can't open in this
- * context.
+ * Error on groups that can't open in this context.
*
- * This means groups that can't occur at the
- * top-level of this group, as well as nested
- * exclusions from all enclosing groups.
+ * This means groups that can't occur at the top-level of this group, as
+ * well as nested exclusions from all enclosing groups.
*/
- if(isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) {
+ if (isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) {
T forbiddenBy;
- if(whoForbid.containsKey(tok)) {
+ if (whoForbid.containsKey(tok)) {
forbiddenBy = whoForbid.get(tok);
} else {
forbiddenBy = groupStack.top().getName();
}
- final String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then");
+ final String ctxList
+ = StringUtils.toEnglishList(groupStack.toArray(), "then");
- final String fmt = "Group '%s' can't be opened in this context. (forbidden by '%s')\nContext Stack: %s";
+ final String fmt
+ = "Group '%s' can't be opened in this context. (forbidden by '%s')\nContext Stack: %s";
- throw new DelimiterException(String.format(fmt, group, forbiddenBy, ctxList));
+ throw new DelimiterException(
+ String.format(fmt, group, forbiddenBy, ctxList));
}
/* Add an open group. */
- final DelimiterGroup<T>.OpenGroup open = group.open(tok, possibleOpenPar.getRight());
+ final DelimiterGroup<T>.OpenGroup open
+ = group.open(tok, possibleOpenPar.getRight());
groupStack.push(open);
/*
* Handle 'forgetful' groups that reset nesting
*/
- if(open.isForgetful()) {
+ if (open.isForgetful()) {
allowedDelimiters.push(HashMultimap.create());
forbiddenDelimiters.push(HashMultiset.create());
}
/* Add the nested opens from this group. */
final Multimap<T, T> currentAllowed = allowedDelimiters.top();
- for(final Entry<T, T> opener : open.getNestingOpeners().entrySet()) {
+ for (final Entry<T, T> opener : open.getNestingOpeners().entrySet()) {
currentAllowed.put(opener.getKey(), opener.getValue());
}
/* Add the nested exclusions from this group */
final Multiset<T> currentForbidden = forbiddenDelimiters.top();
- for(final T exclusion : open.getNestingExclusions()) {
+ for (final T exclusion : open.getNestingExclusions()) {
currentForbidden.add(exclusion);
whoForbid.put(exclusion, possibleOpen);
}
- } else if(!groupStack.isEmpty() && groupStack.top().isClosing(tok)) {
+ } else if (!groupStack.isEmpty() && groupStack.top().isClosing(tok)) {
/*
* Close the group.
*/
@@ -197,7 +195,7 @@ public class SequenceDelimiter<T> {
/* Remove nested exclusions from this group. */
final Multiset<T> currentForbidden = forbiddenDelimiters.top();
- for(final T excludedGroup : closed.getNestingExclusions()) {
+ for (final T excludedGroup : closed.getNestingExclusions()) {
currentForbidden.remove(excludedGroup);
whoForbid.remove(excludedGroup);
@@ -205,18 +203,18 @@ public class SequenceDelimiter<T> {
/* Remove the nested opens from this group. */
final Multimap<T, T> currentAllowed = allowedDelimiters.top();
- for(final Entry<T, T> closer : closed.getNestingOpeners().entrySet()) {
+ for (final Entry<T, T> closer : closed.getNestingOpeners().entrySet()) {
currentAllowed.remove(closer.getKey(), closer.getValue());
}
/*
* Handle 'forgetful' groups that reset nesting.
*/
- if(closed.isForgetful()) {
+ if (closed.isForgetful()) {
allowedDelimiters.drop();
forbiddenDelimiters.drop();
}
- } else if(!groupStack.isEmpty() && groupStack.top().marksSubgroup(tok)) {
+ } else if (!groupStack.isEmpty() && groupStack.top().marksSubgroup(tok)) {
/*
* Mark a subgroup.
*/
@@ -230,17 +228,20 @@ public class SequenceDelimiter<T> {
/*
* Error if not all groups were closed.
*/
- if(groupStack.size() > 1) {
+ if (groupStack.size() > 1) {
final DelimiterGroup<T>.OpenGroup group = groupStack.top();
- final String closingDelims = StringUtils.toEnglishList(group.getNestingExclusions().toArray(),
- false);
+ final String closingDelims = StringUtils
+ .toEnglishList(group.getNestingExclusions().toArray(), false);
- final String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then");
+ final String ctxList
+ = StringUtils.toEnglishList(groupStack.toArray(), "then");
- final String fmt = "Unclosed group '%s'. Expected one of %s to close it.\nOpen groups: %n";
+ final String fmt
+ = "Unclosed group '%s'. Expected one of %s to close it.\nOpen groups: %n";
- throw new DelimiterException(String.format(fmt, group.getName(), closingDelims, ctxList));
+ throw new DelimiterException(
+ String.format(fmt, group.getName(), closingDelims, ctxList));
}
return groupStack.pop().toTree(chars.root, chars);
@@ -254,7 +255,7 @@ public class SequenceDelimiter<T> {
/*
* Check if a delimiter is locally forbidden.
*/
- if(groupStack.isEmpty()) {
+ if (groupStack.isEmpty()) {
localForbid = false;
} else {
localForbid = groupStack.top().excludes(groupName);
@@ -267,10 +268,10 @@ public class SequenceDelimiter<T> {
* Add a delimiter group.
*
* @param group
- * The delimiter group.
+ * The delimiter group.
*/
public void addGroup(final DelimiterGroup<T> group) {
- if(group == null) {
+ if (group == null) {
throw new NullPointerException("Group must not be null");
}
@@ -281,20 +282,21 @@ public class SequenceDelimiter<T> {
* Creates and adds a delimiter group using the provided settings.
*
* @param openers
- * The tokens that open this group
+ * The tokens that open this group
* @param groupName
- * The name of the group
+ * The name of the group
* @param closers
- * The tokens that close this group
+ * The tokens that close this group
*/
- public void addGroup(final T[] openers, final T groupName, @SuppressWarnings("unchecked") final T... closers) {
+ public void addGroup(final T[] openers, final T groupName,
+ @SuppressWarnings("unchecked") final T... closers) {
final DelimiterGroup<T> group = new DelimiterGroup<>(groupName);
group.addClosing(closers);
addGroup(group);
- for(final T open : openers) {
+ for (final T open : openers) {
group.addOpener(open, groupName);
}
}
@@ -305,13 +307,13 @@ public class SequenceDelimiter<T> {
builder.append("SequenceDelimiter [");
- if(groups != null) {
+ if (groups != null) {
builder.append("groups=");
builder.append(groups);
builder.append(",");
}
- if(initialGroup != null) {
+ if (initialGroup != null) {
builder.append("initialGroup=");
builder.append(initialGroup);
}
@@ -325,7 +327,7 @@ public class SequenceDelimiter<T> {
* Set the initial group of this delimiter.
*
* @param initialGroup
- * The initial group of this delimiter.
+ * The initial group of this delimiter.
*/
public void setInitialGroup(final DelimiterGroup<T> initialGroup) {
this.initialGroup = initialGroup;
diff --git a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java
index 1f8f166..6035ede 100644
--- a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java
+++ b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java
@@ -16,16 +16,18 @@ public class StringDelimiter extends SequenceDelimiter<String> {
* for ease of use for strings.
*
* @param seq
- * The sequence to delimit.
+ * The sequence to delimit.
*
* @return The sequence as a tree.
*
* @throws DelimiterException
- * if something went wrong with delimiting the sequence.
+ * if something went wrong with delimiting the
+ * sequence.
*
* @see SequenceDelimiter
*/
public ITree<String> delimitSequence(final String... seq) throws DelimiterException {
- return super.delimitSequence(new SequenceCharacteristics<>("root", "contents", "subgroup"), seq);
+ return super.delimitSequence(
+ new SequenceCharacteristics<>("root", "contents", "subgroup"), seq);
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java
index a5a044a..0844b5b 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java
@@ -23,7 +23,7 @@ public class ChainTokenSplitter implements TokenSplitter {
* Append a series of splitters to the chain.
*
* @param splitters
- * The splitters to append to the chain.
+ * The splitters to append to the chain.
*/
public void appendSplitters(final TokenSplitter... splitters) {
spliters.addAll(splitters);
@@ -33,7 +33,7 @@ public class ChainTokenSplitter implements TokenSplitter {
* Prepend a series of splitters to the chain.
*
* @param splitters
- * The splitters to append to the chain.
+ * The splitters to append to the chain.
*/
public void prependSplitters(final TokenSplitter... splitters) {
spliters.prependAll(splitters);
@@ -43,8 +43,6 @@ public class ChainTokenSplitter implements TokenSplitter {
public IList<String> split(final String input) {
final IList<String> initList = new FunctionalList<>(input);
- return spliters.reduceAux(initList, (splitter, strangs) -> {
- return strangs.flatMap(splitter::split);
- });
+ return spliters.reduceAux(initList, (splitter, strangs) -> strangs.flatMap(splitter::split));
}
} \ No newline at end of file
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java
index 603c214..16c1dc3 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java
@@ -16,15 +16,15 @@ import bjc.funcdata.IList;
*
*/
public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
- private final Set<String> simpleDelimiters;
- private final Set<String> multipleDelimiters;
- private final Set<String> rRawDelimiters;
+ private final Set<String> simpleDelimiters;
+ private final Set<String> multipleDelimiters;
+ private final Set<String> rRawDelimiters;
/**
* Create a new token splitter with blank configuration.
*
* @param keepDelims
- * Whether or not to keep delimiters.
+ * Whether or not to keep delimiters.
*/
public ConfigurableTokenSplitter(final boolean keepDelims) {
super(null, keepDelims);
@@ -50,7 +50,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
* Simple delimiters match one occurrence of themselves as literals.
*
* @param simpleDelims
- * The simple delimiters to add.
+ * The simple delimiters to add.
*/
public void addSimpleDelimiters(final String... simpleDelims) {
for (final String simpleDelim : simpleDelims) {
@@ -61,11 +61,10 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Add a set of multiple delimiters to this splitter.
*
- * Multiple delimiters match one or more occurrences of themselves as
- * literals.
+ * Multiple delimiters match one or more occurrences of themselves as literals.
*
* @param multiDelims
- * The multiple delimiters to add.
+ * The multiple delimiters to add.
*/
public void addMultiDelimiters(final String... multiDelims) {
for (final String multiDelim : multiDelims) {
@@ -76,11 +75,10 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Add a set of raw delimiters to this splitter.
*
- * Raw delimiters match one occurrence of themselves as regular
- * expressions.
+ * Raw delimiters match one occurrence of themselves as regular expressions.
*
* @param rRawDelims
- * The raw delimiters to add.
+ * The raw delimiters to add.
*/
public void addRawDelimiters(final String... rRawDelims) {
for (final String rRawDelim : rRawDelims) {
@@ -89,8 +87,8 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
}
/**
- * Take the configuration and compile it into a regular expression to
- * use when splitting.
+ * Take the configuration and compile it into a regular expression to use when
+ * splitting.
*/
public void compile() {
final StringBuilder rPattern = new StringBuilder();
@@ -114,22 +112,25 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
@Override
public IList<String> split(final String input) {
- if (spliter == null) throw new IllegalStateException("Must compile splitter before use");
+ if (spliter == null)
+ throw new IllegalStateException("Must compile splitter before use");
return super.split(input);
}
@Override
public String toString() {
- final String fmt = "ConfigurableTokenSplitter [simpleDelimiters=%s, multipleDelimiters=%s,"
- + " rRawDelimiters=%s, spliter=%s]";
+ final String fmt
+ = "ConfigurableTokenSplitter [simpleDelimiters=%s, multipleDelimiters=%s,"
+ + " rRawDelimiters=%s, spliter=%s]";
- return String.format(fmt, simpleDelimiters, multipleDelimiters, rRawDelimiters, spliter);
+ return String.format(fmt, simpleDelimiters, multipleDelimiters, rRawDelimiters,
+ spliter);
}
/**
* Builder class for the configurable token splitter.
- *
+ *
* @author bjculkin
*
*/
@@ -138,9 +139,9 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Create a new splitter builder.
- *
+ *
* @param keepDelims
- * Whether or not to keep the delimited splitter.
+ * Whether or not to keep the delimited splitter.
*/
public Builder(boolean keepDelims) {
cts = new ConfigurableTokenSplitter(keepDelims);
@@ -148,7 +149,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Add a set of simple delimiters.
- *
+ *
* @param strings
* The simple delimiters to use.
* @return The builder, for chaining.
@@ -161,7 +162,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Add a set of multiple delimiters.
- *
+ *
* @param strings
* The multiple delimiters to use.
* @return The builder, for chaining.
@@ -174,7 +175,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Add a set of raw delimiters.
- *
+ *
* @param strings
* The raw delimiters to use.
* @return The builder, for chaining.
@@ -187,14 +188,14 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter {
/**
* Build the splitter.
- *
+ *
* @return The built splitter.
*/
public ConfigurableTokenSplitter build() {
ConfigurableTokenSplitter ret = new ConfigurableTokenSplitter(cts.keepDelim,
cts.simpleDelimiters, cts.multipleDelimiters, cts.rRawDelimiters);
ret.compile();
-
+
return ret;
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java
index 8bdb176..9a0cd65 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java
@@ -23,7 +23,7 @@ public class ExcludingTokenSplitter implements TokenSplitter {
* Create a new excluding token splitter.
*
* @param splitter
- * The splitter to apply to non-excluded strings.
+ * The splitter to apply to non-excluded strings.
*/
public ExcludingTokenSplitter(final TokenSplitter splitter) {
spliter = splitter;
@@ -37,33 +37,32 @@ public class ExcludingTokenSplitter implements TokenSplitter {
* Exclude literal strings from splitting.
*
* @param exclusions
- * The strings to exclude from splitting.
+ * The strings to exclude from splitting.
*/
public final void addLiteralExclusions(final String... exclusions) {
- for(final String exclusion : exclusions) {
+ for (final String exclusion : exclusions) {
literalExclusions.add(exclusion);
}
}
/**
- * Exclude all of the strings matching any of the predicates from
- * splitting.
+ * Exclude all of the strings matching any of the predicates from splitting.
*
* @param exclusions
- * The predicates to use for exclusions.
+ * The predicates to use for exclusions.
*/
@SafeVarargs
public final void addPredicateExclusion(final Predicate<String>... exclusions) {
- for(final Predicate<String> exclusion : exclusions) {
+ for (final Predicate<String> exclusion : exclusions) {
predExclusions.add(exclusion);
}
}
@Override
public IList<String> split(final String input) {
- if(literalExclusions.contains(input))
+ if (literalExclusions.contains(input))
return new FunctionalList<>(input);
- else if(predExclusions.anyMatch(pred -> pred.test(input)))
+ else if (predExclusions.anyMatch(pred -> pred.test(input)))
return new FunctionalList<>(input);
else
return spliter.split(input);
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java
index 3bcbea2..85d72e2 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java
@@ -7,7 +7,7 @@ import bjc.funcdata.IList;
/**
* A token splitter that removes tokens that match a predicate from the stream
* of tokens.
- *
+ *
* @author bjculkin
*
*/
@@ -18,12 +18,12 @@ public class FilteredTokenSplitter implements TokenSplitter {
/**
* Create a new filtered token splitter.
- *
+ *
* @param source
- * The splitter to get tokens from.
- *
+ * The splitter to get tokens from.
+ *
* @param filter
- * The filter to pass tokens through.
+ * The filter to pass tokens through.
*/
public FilteredTokenSplitter(TokenSplitter source, Predicate<String> filter) {
this.source = source;
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java
index 8f4fb6c..43793e3 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java
@@ -21,10 +21,10 @@ public class SimpleTokenSplitter implements TokenSplitter {
* Create a new simple token splitter.
*
* @param splitter
- * The pattern to split around.
+ * The pattern to split around.
*
* @param keepDelims
- * Whether or not delimiters should be kept.
+ * Whether or not delimiters should be kept.
*/
public SimpleTokenSplitter(final Pattern splitter, final boolean keepDelims) {
spliter = splitter;
@@ -34,7 +34,7 @@ public class SimpleTokenSplitter implements TokenSplitter {
@Override
public IList<String> split(final String input) {
- if(keepDelim) {
+ if (keepDelim) {
return RegexStringEditor.mapOccurances(input, spliter, ID.id(), ID.id());
}
@@ -43,6 +43,7 @@ public class SimpleTokenSplitter implements TokenSplitter {
@Override
public String toString() {
- return String.format("SimpleTokenSplitter [spliter=%s, keepDelim=%s]", spliter, keepDelim);
+ return String.format("SimpleTokenSplitter [spliter=%s, keepDelim=%s]", spliter,
+ keepDelim);
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java
index f2d9c73..59e73e8 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java
@@ -13,7 +13,7 @@ public interface TokenSplitter {
* Split a string into a list of pieces.
*
* @param input
- * The string to split.
+ * The string to split.
*
* @return The pieces of the string.
*/
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java
index c8827b6..15d6b8b 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java
@@ -4,16 +4,16 @@ import java.util.function.UnaryOperator;
/**
* Factory methods for producing token splitters.
- *
+ *
* @author student
*
*/
public class TokenSplitters {
/**
* Create a new chained token splitter.
- *
+ *
* @param splitters
- * The series of splitters to chain together.
+ * The series of splitters to chain together.
* @return A chained-together series of splitters.
*/
public static TokenSplitter chainSplitter(final TokenSplitter... splitters) {
@@ -26,16 +26,17 @@ public class TokenSplitters {
/**
* Create a new transforming token splitter.
- *
+ *
* @param splitter
- * The splitter to gain tokens from
- *
+ * The splitter to gain tokens from
+ *
* @param transform
- * The transform to apply to the strings.
- *
+ * The transform to apply to the strings.
+ *
* @return A splitter that applies the chosen transform to the tokens.
*/
- public static TokenSplitter transformSplitter(final TokenSplitter splitter, UnaryOperator<String> transform) {
+ public static TokenSplitter transformSplitter(final TokenSplitter splitter,
+ UnaryOperator<String> transform) {
return new TransformTokenSplitter(splitter, transform);
}
}
diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java
index 3cbe103..b9fbedc 100644
--- a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java
+++ b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java
@@ -7,7 +7,7 @@ import bjc.funcdata.IList;
/**
* A token splitter that performs a transform on the tokens from another
* splitter.
- *
+ *
* @author bjculkin
*
*/
@@ -18,12 +18,12 @@ public class TransformTokenSplitter implements TokenSplitter {
/**
* Create a new transforming splitter.
- *
+ *
* @param source
- * The splitter to use as a source.
- *
+ * The splitter to use as a source.
+ *
* @param transform
- * The transform to apply to tokens.
+ * The transform to apply to tokens.
*/
public TransformTokenSplitter(TokenSplitter source, UnaryOperator<String> transform) {
this.source = source;