diff --git a/SpecsUtils/src/pt/up/fe/specs/util/DotRenderFormat.java b/SpecsUtils/src/pt/up/fe/specs/util/DotRenderFormat.java index ee3d3ec0..5f4d8876 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/DotRenderFormat.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/DotRenderFormat.java @@ -46,7 +46,8 @@ public String getFlag() { /** * Gets the file extension associated with the rendering format. *

- * The extension is used for naming output files generated by graph rendering utilities. + * The extension is used for naming output files generated by graph rendering + * utilities. *

* * @return the file extension for the rendering format diff --git a/SpecsUtils/src/pt/up/fe/specs/util/ExtensionFilter.java b/SpecsUtils/src/pt/up/fe/specs/util/ExtensionFilter.java index 96224054..cb857ed3 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/ExtensionFilter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/ExtensionFilter.java @@ -40,7 +40,6 @@ public ExtensionFilter(String extension) { public ExtensionFilter(String extension, boolean followSymlinks) { this.extension = extension; - // this.separator = SpecsIo.DEFAULT_EXTENSION_SEPARATOR; this.separator = "."; this.followSymlinks = followSymlinks; } @@ -62,5 +61,4 @@ public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(suffix); } - -} \ No newline at end of file +} diff --git a/SpecsUtils/src/pt/up/fe/specs/util/Preconditions.java b/SpecsUtils/src/pt/up/fe/specs/util/Preconditions.java index 0a2b6b19..181f0d3e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/Preconditions.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/Preconditions.java @@ -14,11 +14,14 @@ package pt.up.fe.specs.util; /** - * Static convenience methods that help a method or constructor check whether it was invoked correctly (whether its - * preconditions have been met). These methods generally accept a {@code boolean} expression which is expected to - * be {@code true} (or in the case of {@code checkNotNull}, an object reference which is expected to be non-null). When - * {@code false} (or {@code null}) is passed instead, the {@code Preconditions} method throws an unchecked exception, - * which helps the calling method communicate to its caller that that caller has made a mistake. Example: + * Static convenience methods that help a method or constructor check whether it + * was invoked correctly (whether its preconditions have been met). These + * methods generally accept a {@code boolean} expression which is expected to + * be {@code true} (or in the case of {@code checkNotNull}, an object reference + * which is expected to be non-null). When {@code false} (or {@code null}) is + * passed instead, the {@code Preconditions} method throws an unchecked + * exception, which helps the calling method communicate to its caller + * that that caller has made a mistake. Example: * *
  * {@code
@@ -38,72 +41,87 @@
  *   }}
  * 
* - * In this example, {@code checkArgument} throws an {@code IllegalArgumentException} to indicate that - * {@code exampleBadCaller} made an error in its call to {@code sqrt}. + * In this example, {@code checkArgument} throws an + * {@code IllegalArgumentException} to indicate that {@code exampleBadCaller} + * made an error in its call to {@code sqrt}. * *

Warning about performance

* *

- * The goal of this class is to improve readability of code, but in some circumstances this may come at a significant - * performance cost. Remember that parameter values for message construction must all be computed eagerly, and - * autoboxing and varargs array creation may happen as well, even when the precondition check then succeeds (as it - * should almost always do in production). In some circumstances these wasted CPU cycles and allocations can add up to a - * real problem. Performance-sensitive precondition checks can always be converted to the customary form: - * + * The goal of this class is to improve readability of code, but in some + * circumstances this may come at a significant performance cost. Remember that + * parameter values for message construction must all be computed eagerly, and + * autoboxing and varargs array creation may happen as well, even when the + * precondition check then succeeds (as it should almost always do in + * production). In some circumstances these wasted CPU cycles and allocations + * can add up to a real problem. Performance-sensitive precondition checks can + * always be converted to the customary form: + * *

  * {@code
  * 
- *   if (value < 0.0) {
+ * if (value < 0.0) {
  *     throw new IllegalArgumentException("negative value: " + value);
- *   }}
+ * }
+ * }
  * 
* *

Other types of preconditions

* *

- * Not every type of precondition failure is supported by these methods. Continue to throw standard JDK exceptions such - * as {@link java.util.NoSuchElementException} or {@link UnsupportedOperationException} in the situations they are - * intended for. + * Not every type of precondition failure is supported by these methods. + * Continue to throw standard JDK exceptions such as + * {@link java.util.NoSuchElementException} or + * {@link UnsupportedOperationException} in the situations they are intended + * for. * *

Non-preconditions

* *

- * It is of course possible to use the methods of this class to check for invalid conditions which are not the - * caller's fault. Doing so is not recommended because it is misleading to future readers of the code and of - * stack traces. See Conditional - * failures explained in the Guava User Guide for more advice. + * It is of course possible to use the methods of this class to check for + * invalid conditions which are not the caller's fault. Doing so is + * not recommended because it is misleading to future readers of the + * code and of stack traces. See + * Conditional failures explained in the Guava User Guide for more advice. * *

{@code java.util.Objects.requireNonNull()}

* *

- * Projects which use {@code com.google.common} should generally avoid the use of - * {@link java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link #checkNotNull(Object)} or - * {@link Verify#verifyNotNull(Object)} is appropriate to the situation. (The same goes for the message-accepting + * Projects which use {@code com.google.common} should generally avoid the use + * of {@link java.util.Objects#requireNonNull(Object)}. Instead, use whichever + * of {@link #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is + * appropriate to the situation. (The same goes for the message-accepting * overloads.) * *

Only {@code %s} is supported

* *

- * In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is supported, not the full - * range of {@link java.util.Formatter} specifiers. However, note that if the number of arguments does not match the - * number of occurrences of {@code "%s"} in the format string, {@code Preconditions} will still behave as expected, and - * will still include all argument values in the error message; the message will simply not be formatted exactly as - * intended. + * In {@code Preconditions} error message template strings, only the + * {@code "%s"} specifier is supported, not the full + * range of {@link java.util.Formatter} specifiers. However, note that if the + * number of arguments does not match the number of occurrences of {@code "%s"} + * in the format string, {@code Preconditions} will still behave as expected, + * and will still include all argument values in the error message; the message + * will simply not be formatted exactly as intended. * *

More information

* *

- * See the Guava User Guide on using + * See the Guava User Guide on using * {@code Preconditions}. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) * *

- * SPeCS note: this file has not been modified apart from this comment and the package name. This file has been - * copied as-is, to avoid adding Guava as a dependency to this project, SpecsUtils (this project has no external - * dependencies).
- * This class should be used internally by this project alone. When Java 9 is released, modularize project and do + * SPeCS note: this file has not been modified apart from this comment + * and the package name. This file has been copied as-is, to avoid adding + * Guava as a dependency to this project, SpecsUtils (this project has no + * external dependencies).
+ * This class should be used internally by this project alone. When Java + * 9 is released, modularize project and do * not export this class. */ public final class Preconditions { @@ -111,12 +129,11 @@ private Preconditions() { } /** - * Ensures the truth of an expression involving one or more parameters to the calling method. + * Ensures the truth of an expression involving one or more parameters to the + * calling method. * - * @param expression - * a boolean expression - * @throws IllegalArgumentException - * if {@code expression} is false + * @param expression a boolean expression + * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { @@ -125,15 +142,14 @@ public static void checkArgument(boolean expression) { } /** - * Ensures the truth of an expression involving one or more parameters to the calling method. + * Ensures the truth of an expression involving one or more parameters to the + * calling method. * - * @param expression - * a boolean expression - * @param errorMessage - * the exception message to use if the check fails; will be converted to a string using - * {@link String#valueOf(Object)} - * @throws IllegalArgumentException - * if {@code expression} is false + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be + * converted to a string using + * {@link String#valueOf(Object)} + * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, Object errorMessage) { if (!expression) { @@ -142,23 +158,29 @@ public static void checkArgument(boolean expression, Object errorMessage) { } /** - * Ensures the truth of an expression involving one or more parameters to the calling method. + * Ensures the truth of an expression involving one or more parameters to the + * calling method. * - * @param expression - * a boolean expression - * @param errorMessageTemplate - * a template for the exception message should the check fail. The message is formed by replacing each - * {@code %s} placeholder in the template with an argument. These are matched by position - the first - * {@code %s} gets {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the - * formatted message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs - * the arguments to be substituted into the message template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. - * @throws IllegalArgumentException - * if {@code expression} is false - * @throws NullPointerException - * if the check fails and either {@code errorMessageTemplate} or {@code errorMessageArgs} is null (don't - * let this happen) + * @param expression a boolean expression + * @param errorMessageTemplate a template for the exception message should the + * check fail. The message is formed by replacing + * each + * {@code %s} placeholder in the template with an + * argument. These are matched by position - the + * first + * {@code %s} gets {@code errorMessageArgs[0]}, etc. + * Unmatched arguments will be appended to the + * formatted message in square braces. Unmatched + * placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message + * template. Arguments are converted to strings + * using + * {@link String#valueOf(Object)}. + * @throws IllegalArgumentException if {@code expression} is false + * @throws NullPointerException if the check fails and either + * {@code errorMessageTemplate} or + * {@code errorMessageArgs} is null (don't + * let this happen) */ public static void checkArgument(boolean expression, String errorMessageTemplate, @@ -169,13 +191,11 @@ public static void checkArgument(boolean expression, } /** - * Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters - * to the calling method. + * Ensures the truth of an expression involving the state of the calling + * instance, but not involving any parameters to the calling method. * - * @param expression - * a boolean expression - * @throws IllegalStateException - * if {@code expression} is false + * @param expression a boolean expression + * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { @@ -184,16 +204,14 @@ public static void checkState(boolean expression) { } /** - * Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters - * to the calling method. + * Ensures the truth of an expression involving the state of the calling + * instance, but not involving any parameters to the calling method. * - * @param expression - * a boolean expression - * @param errorMessage - * the exception message to use if the check fails; will be converted to a string using - * {@link String#valueOf(Object)} - * @throws IllegalStateException - * if {@code expression} is false + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be + * converted to a string using + * {@link String#valueOf(Object)} + * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression, Object errorMessage) { if (!expression) { @@ -202,24 +220,29 @@ public static void checkState(boolean expression, Object errorMessage) { } /** - * Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters - * to the calling method. + * Ensures the truth of an expression involving the state of the calling + * instance, but not involving any parameters to the calling method. * - * @param expression - * a boolean expression - * @param errorMessageTemplate - * a template for the exception message should the check fail. The message is formed by replacing each - * {@code %s} placeholder in the template with an argument. These are matched by position - the first - * {@code %s} gets {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the - * formatted message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs - * the arguments to be substituted into the message template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. - * @throws IllegalStateException - * if {@code expression} is false - * @throws NullPointerException - * if the check fails and either {@code errorMessageTemplate} or {@code errorMessageArgs} is null (don't - * let this happen) + * @param expression a boolean expression + * @param errorMessageTemplate a template for the exception message should the + * check fail. The message is formed by replacing + * each + * {@code %s} placeholder in the template with an + * argument. These are matched by position - the + * first + * {@code %s} gets {@code errorMessageArgs[0]}, etc. + * Unmatched arguments will be appended to the + * formatted message in square braces. Unmatched + * placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message + * template. Arguments are converted to strings + * using + * {@link String#valueOf(Object)}. + * @throws IllegalStateException if {@code expression} is false + * @throws NullPointerException if the check fails and either + * {@code errorMessageTemplate} or + * {@code errorMessageArgs} is null (don't + * let this happen) */ public static void checkState(boolean expression, String errorMessageTemplate, @@ -230,13 +253,12 @@ public static void checkState(boolean expression, } /** - * Ensures that an object reference passed as a parameter to the calling method is not null. + * Ensures that an object reference passed as a parameter to the calling method + * is not null. * - * @param reference - * an object reference + * @param reference an object reference * @return the non-null reference that was validated - * @throws NullPointerException - * if {@code reference} is null + * @throws NullPointerException if {@code reference} is null */ public static T checkNotNull(T reference) { if (reference == null) { @@ -246,16 +268,15 @@ public static T checkNotNull(T reference) { } /** - * Ensures that an object reference passed as a parameter to the calling method is not null. + * Ensures that an object reference passed as a parameter to the calling method + * is not null. * - * @param reference - * an object reference - * @param errorMessage - * the exception message to use if the check fails; will be converted to a string using - * {@link String#valueOf(Object)} + * @param reference an object reference + * @param errorMessage the exception message to use if the check fails; will be + * converted to a string using + * {@link String#valueOf(Object)} * @return the non-null reference that was validated - * @throws NullPointerException - * if {@code reference} is null + * @throws NullPointerException if {@code reference} is null */ public static T checkNotNull(T reference, Object errorMessage) { if (reference == null) { @@ -265,21 +286,26 @@ public static T checkNotNull(T reference, Object errorMessage) { } /** - * Ensures that an object reference passed as a parameter to the calling method is not null. + * Ensures that an object reference passed as a parameter to the calling method + * is not null. * - * @param reference - * an object reference - * @param errorMessageTemplate - * a template for the exception message should the check fail. The message is formed by replacing each - * {@code %s} placeholder in the template with an argument. These are matched by position - the first - * {@code %s} gets {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the - * formatted message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs - * the arguments to be substituted into the message template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. + * @param reference an object reference + * @param errorMessageTemplate a template for the exception message should the + * check fail. The message is formed by replacing + * each + * {@code %s} placeholder in the template with an + * argument. These are matched by position - the + * first + * {@code %s} gets {@code errorMessageArgs[0]}, etc. + * Unmatched arguments will be appended to the + * formatted message in square braces. Unmatched + * placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message + * template. Arguments are converted to strings + * using + * {@link String#valueOf(Object)}. * @return the non-null reference that was validated - * @throws NullPointerException - * if {@code reference} is null + * @throws NullPointerException if {@code reference} is null */ public static T checkNotNull(T reference, String errorMessageTemplate, @@ -295,61 +321,60 @@ public static T checkNotNull(T reference, * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { - * throw new BadException(messageExpression); + * throw new BadException(messageExpression); * } * - * refactored so that messageExpression is moved to a separate String-returning method. + * refactored so that messageExpression is moved to a separate String-returning + * method. * * if (guardExpression) { - * throw new BadException(badMsg(...)); + * throw new BadException(badMsg(...)); * } * - * The alternative natural refactorings into void or Exception-returning methods are much slower. - * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This - * is a hotspot optimizer bug, which should be fixed, but that's a separate, big project). + * The alternative natural refactorings into void or Exception-returning methods + * are much slower. This is a big deal - we're talking factors of 2-8 in + * microbenchmarks, not just 10-20%. (This is a hotspot optimizer bug, which + * should be fixed, but that's a separate, big project). * - * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a - * RangeCheckMicroBenchmark in the JDK that was used to test this. + * The coding pattern above is heavily used in java.util, e.g. in ArrayList. + * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. * - * But the methods in this class want to throw different exceptions, depending on the args, so it - * appears that this pattern is not directly applicable. But we can use the ridiculous, devious - * trick of throwing an exception in the middle of the construction of another exception. Hotspot - * is fine with that. + * But the methods in this class want to throw different exceptions, depending + * on the args, so it appears that this pattern is not directly applicable. But + * we can use the ridiculous, devious trick of throwing an exception in the + * middle of the construction of another exception. Hotspot is fine with that. */ /** - * Ensures that {@code index} specifies a valid element in an array, list or string of size {@code size}. An - * element index may range from zero, inclusive, to {@code size}, exclusive. + * Ensures that {@code index} specifies a valid element in an array, list + * or string of size {@code size}. An element index may range from zero, + * inclusive, to {@code size}, exclusive. * - * @param index - * a user-supplied index identifying an element of an array, list or string - * @param size - * the size of that array, list or string + * @param index a user-supplied index identifying an element of an array, list + * or string + * @param size the size of that array, list or string * @return the value of {@code index} - * @throws IndexOutOfBoundsException - * if {@code index} is negative or is not less than {@code size} - * @throws IllegalArgumentException - * if {@code size} is negative + * @throws IndexOutOfBoundsException if {@code index} is negative or is not less + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** - * Ensures that {@code index} specifies a valid element in an array, list or string of size {@code size}. An + * Ensures that {@code index} specifies a valid element in an array, list + * or string of size {@code size}. An * element index may range from zero, inclusive, to {@code size}, exclusive. * - * @param index - * a user-supplied index identifying an element of an array, list or string - * @param size - * the size of that array, list or string - * @param desc - * the text to use to describe this index in an error message + * @param index a user-supplied index identifying an element of an array, list + * or string + * @param size the size of that array, list or string + * @param desc the text to use to describe this index in an error message * @return the value of {@code index} - * @throws IndexOutOfBoundsException - * if {@code index} is negative or is not less than {@code size} - * @throws IllegalArgumentException - * if {@code size} is negative + * @throws IndexOutOfBoundsException if {@code index} is negative or is not less + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex( int index, int size, String desc) { @@ -371,38 +396,35 @@ private static String badElementIndex(int index, int size, String desc) { } /** - * Ensures that {@code index} specifies a valid position in an array, list or string of size {@code size}. A - * position index may range from zero to {@code size}, inclusive. + * Ensures that {@code index} specifies a valid position in an array, + * list or string of size {@code size}. A position index may range from zero to + * {@code size}, inclusive. * - * @param index - * a user-supplied index identifying a position in an array, list or string - * @param size - * the size of that array, list or string + * @param index a user-supplied index identifying a position in an array, list + * or string + * @param size the size of that array, list or string * @return the value of {@code index} - * @throws IndexOutOfBoundsException - * if {@code index} is negative or is greater than {@code size} - * @throws IllegalArgumentException - * if {@code size} is negative + * @throws IndexOutOfBoundsException if {@code index} is negative or is greater + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** - * Ensures that {@code index} specifies a valid position in an array, list or string of size {@code size}. A - * position index may range from zero to {@code size}, inclusive. + * Ensures that {@code index} specifies a valid position in an array, + * list or string of size {@code size}. A position index may range from zero to + * {@code size}, inclusive. * - * @param index - * a user-supplied index identifying a position in an array, list or string - * @param size - * the size of that array, list or string - * @param desc - * the text to use to describe this index in an error message + * @param index a user-supplied index identifying a position in an array, list + * or string + * @param size the size of that array, list or string + * @param desc the text to use to describe this index in an error message * @return the value of {@code index} - * @throws IndexOutOfBoundsException - * if {@code index} is negative or is greater than {@code size} - * @throws IllegalArgumentException - * if {@code size} is negative + * @throws IndexOutOfBoundsException if {@code index} is negative or is greater + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) @@ -423,20 +445,20 @@ private static String badPositionIndex(int index, int size, String desc) { } /** - * Ensures that {@code start} and {@code end} specify a valid positions in an array, list or string of size - * {@code size}, and are in order. A position index may range from zero to {@code size}, inclusive. + * Ensures that {@code start} and {@code end} specify a valid positions + * in an array, list or string of size {@code size}, and are in order. A + * position index may range from zero to {@code size}, inclusive. * - * @param start - * a user-supplied index identifying a starting position in an array, list or string - * @param end - * a user-supplied index identifying a ending position in an array, list or string - * @param size - * the size of that array, list or string - * @throws IndexOutOfBoundsException - * if either index is negative or is greater than {@code size}, or if {@code end} is less than - * {@code start} - * @throws IllegalArgumentException - * if {@code size} is negative + * @param start a user-supplied index identifying a starting position in an + * array, list or string + * @param end a user-supplied index identifying a ending position in an array, + * list or string + * @param size the size of that array, list or string + * @throws IndexOutOfBoundsException if either index is negative or is greater + * than {@code size}, or if {@code end} is + * less than + * {@code start} + * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) @@ -457,15 +479,16 @@ private static String badPositionIndexes(int start, int end, int size) { } /** - * Substitutes each {@code %s} in {@code template} with an argument. These are matched by position: the first - * {@code %s} gets {@code args[0]}, etc. If there are more arguments than placeholders, the unmatched arguments will - * be appended to the end of the formatted message in square braces. + * Substitutes each {@code %s} in {@code template} with an argument. These are + * matched by position: the first {@code %s} gets {@code args[0]}, etc. If there + * are more arguments than placeholders, the unmatched arguments will be + * appended to the end of the formatted message in square braces. * - * @param template - * a non-null string containing 0 or more {@code %s} placeholders. - * @param args - * the arguments to be substituted into the message template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. Arguments can be null. + * @param template a non-null string containing 0 or more {@code %s} + * placeholders. + * @param args the arguments to be substituted into the message template. + * Arguments are converted to strings using + * {@link String#valueOf(Object)}. Arguments can be null. */ // Note that this is somewhat-improperly used from Verify.java as well. static String format(String template, Object... args) { @@ -499,5 +522,4 @@ static String format(String template, Object... args) { return builder.toString(); } - -} \ No newline at end of file +} diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsAsm.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsAsm.java index 78d0c174..ab845478 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsAsm.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsAsm.java @@ -18,7 +18,8 @@ /** * Utility methods for assembly code operations. *

- * Provides static helper methods for parsing, formatting, and manipulating assembly code. + * Provides static helper methods for parsing, formatting, and manipulating + * assembly code. *

* * @author Joao Bispo @@ -30,7 +31,7 @@ public class SpecsAsm { * * @param input1 the first operand * @param input2 the second operand - * @param carry the carry value (0 or 1) + * @param carry the carry value (0 or 1) * @return the result of the addition */ public static long add64(long input1, long input2, long carry) { @@ -42,7 +43,7 @@ public static long add64(long input1, long input2, long carry) { * * @param input1 the first operand * @param input2 the second operand - * @param carry the carry value (0 or 1) + * @param carry the carry value (0 or 1) * @return the result of the reverse subtraction */ public static long rsub64(long input1, long input2, long carry) { @@ -50,11 +51,12 @@ public static long rsub64(long input1, long input2, long carry) { } /** - * Calculates the carryOut of the sum of rA with rB and carry. Operation is rA + rB + carry. + * Calculates the carryOut of the sum of rA with rB and carry. Operation is rA + + * rB + carry. * * @param input1 the first operand * @param input2 the second operand - * @param carry the carry from the previous operation. Should be 0 or 1. + * @param carry the carry from the previous operation. Should be 0 or 1. * @return an ArithmeticResult32 containing the result and carry out */ public static ArithmeticResult32 add32(int input1, int input2, int carry) { @@ -79,11 +81,12 @@ public static ArithmeticResult32 add32(int input1, int input2, int carry) { } /** - * Calculates the carryOut of the reverse subtraction of rA with rB and carry. Operation is rB + ~rA + carry. + * Calculates the carryOut of the reverse subtraction of rA with rB and carry. + * Operation is rB + ~rA + carry. * * @param input1 the first operand * @param input2 the second operand - * @param carry the carry from the previous operation. Should be 0 or 1. + * @param carry the carry from the previous operation. Should be 0 or 1. * @return an ArithmeticResult32 containing the result and carry out */ public static ArithmeticResult32 rsub32(int input1, int input2, int carry) { @@ -162,7 +165,8 @@ public static int xor32(int input1, int input2) { } /** - * Compares two signed 32-bit integers and modifies the MSB to reflect the relation. + * Compares two signed 32-bit integers and modifies the MSB to reflect the + * relation. * * @param input1 the first operand * @param input2 the second operand @@ -180,7 +184,8 @@ public static int mbCompareSigned(int input1, int input2) { } /** - * Compares two unsigned 32-bit integers and modifies the MSB to reflect the relation. + * Compares two unsigned 32-bit integers and modifies the MSB to reflect the + * relation. * * @param input1 the first operand * @param input2 the second operand @@ -232,7 +237,8 @@ public static int shiftRightLogical(int input1, int input2) { } /** - * Performs a logical left shift on a 32-bit integer, taking into account a mask. + * Performs a logical left shift on a 32-bit integer, taking into account a + * mask. * * @param input1 the operand to shift * @param input2 the number of positions to shift @@ -245,7 +251,8 @@ public static int shiftLeftLogical(int input1, int input2, int input3) { } /** - * Performs an arithmetic right shift on a 32-bit integer, taking into account a mask. + * Performs an arithmetic right shift on a 32-bit integer, taking into account a + * mask. * * @param input1 the operand to shift * @param input2 the number of positions to shift @@ -258,7 +265,8 @@ public static int shiftRightArithmetical(int input1, int input2, int input3) { } /** - * Performs a logical right shift on a 32-bit integer, taking into account a mask. + * Performs a logical right shift on a 32-bit integer, taking into account a + * mask. * * @param input1 the operand to shift * @param input2 the number of positions to shift diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsBits.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsBits.java index b3a46b24..688e59ae 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsBits.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsBits.java @@ -17,7 +17,8 @@ /** * Utility methods for bitwise operations. *

- * Provides static helper methods for manipulating bits and binary representations. + * Provides static helper methods for manipulating bits and binary + * representations. *

* * @author Joao Bispo @@ -114,18 +115,16 @@ public static long getMaskBit33() { } /** - * Pads the string with zeros on the left until it has the requested size, and prefixes "0x" to the resulting - * String. + * Pads the string with zeros on the left until it has the requested size, and + * prefixes "0x" to the resulting String. * *

* Example:
* Input - padHexString(166, 4)
* Output - 0x00A6. * - * @param hexNumber - * a long. - * @param size - * the pretended number of digits of the hexadecimal number. + * @param hexNumber a long. + * @param size the pretended number of digits of the hexadecimal number. * @return a string */ public static String padHexString(long hexNumber, int size) { @@ -133,18 +132,16 @@ public static String padHexString(long hexNumber, int size) { } /** - * Pads the string with zeros on the left until it has the requested size, and prefixes "0x" to the resulting - * String. + * Pads the string with zeros on the left until it has the requested size, and + * prefixes "0x" to the resulting String. * *

* Example:2
* Input - padHexString(A6, 4)
* Output - 0x00A6. * - * @param hexNumber - * an hexadecimal number in String format. - * @param size - * the pretended number of digits of the hexadecimal number. + * @param hexNumber an hexadecimal number in String format. + * @param size the pretended number of digits of the hexadecimal number. * @return a string */ public static String padHexString(String hexNumber, int size) { @@ -172,10 +169,8 @@ public static String padHexString(String hexNumber, int size) { * Input - padBinaryString(101, 5)
* Output - 00101. * - * @param binaryNumber - * a binary number in String format. - * @param size - * the pretended number of digits of the binary number. + * @param binaryNumber a binary number in String format. + * @param size the pretended number of digits of the binary number. * @return a string */ public static String padBinaryString(String binaryNumber, int size) { @@ -196,10 +191,8 @@ public static String padBinaryString(String binaryNumber, int size) { /** * Gets the a single bit of the integer target. * - * @param position - * a number between 0 and 31, inclusive, where 0 is the LSB - * @param target - * an integer + * @param position a number between 0 and 31, inclusive, where 0 is the LSB + * @param target an integer * @return 1 if the bit at the specified position is 1; 0 otherwise */ public static int getBit(int position, int target) { @@ -207,22 +200,19 @@ public static int getBit(int position, int target) { } /** - * Returns an integer representing the 16 bits from the long number from a specified offset. + * Returns an integer representing the 16 bits from the long number from a + * specified offset. * - * @param data - * a long number - * @param offset - * a number between 0 and 3, inclusive + * @param data a long number + * @param offset a number between 0 and 3, inclusive * @return an int representing the 16 bits of the specified offset */ public static int get16BitsAligned(long data, int offset) { // Normalize offset offset = offset % 4; - // System.out.println("offset:"+offset); + // Align the mask long mask = SpecsBits.MASK_16_BITS << 16 * offset; - // System.out.println("Mask:"+Long.toHexString(mask)); - // System.out.println("Data:"+Long.toHexString(data)); // Get the bits long result = data & mask; @@ -234,23 +224,15 @@ public static int get16BitsAligned(long data, int offset) { /** * Paul Hsieh's Hash Function, for long numbers. * - * @param data - * data to hash - * @param hash - * previous value of the hash. If this it is the start of the method, a recomended value to use is the - * length of the data. In this case because it is a long use the number 8 (8 bytes). + * @param data data to hash + * @param hash previous value of the hash. If this it is the start of the + * method, a recomended value to use is the + * length of the data. In this case because it is a long use the + * number 8 (8 bytes). * @return a hash value */ public static int superFastHash(long data, int hash) { int tmp; - // int rem; - - // if (len <= 0) { - // return 0; - // } - - // rem = len & 3; - // len >>= 2; // Main Loop for (int i = 0; i < 4; i += 2) { @@ -281,28 +263,19 @@ public static int superFastHash(long data, int hash) { /** * Paul Hsieh's Hash Function, for int numbers. * - * @param data - * data to hash - * @param hash - * previous value of the hash. If this it is the start of the method, a recomended value to use is the - * length of the data. In this case because it is an integer use the number 4 (4 bytes). + * @param data data to hash + * @param hash previous value of the hash. If this it is the start of the + * method, a recomended value to use is the + * length of the data. In this case because it is an integer use the + * number 4 (4 bytes). * @return a hash value */ public static int superFastHash(int data, int hash) { int tmp; - // int rem; - - // if (len <= 0) { - // return 0; - // } - - // rem = len & 3; - // len >>= 2; // Main Loop int i = 0; - // for (int i = 0; i < 2; i += 2) { - // System.out.println("Iteration:"+i); + // Get lower 16 bits hash += SpecsBits.get16BitsAligned(data, i); // Calculate some random value with second-lower 16 bits @@ -313,8 +286,6 @@ public static int superFastHash(int data, int hash) { // to longs (64-bit values), it is unnecessary). hash += hash >> 11; - // } - // Handle end cases // // There are no end cases, main loop is done in chuncks of 32 bits. @@ -332,10 +303,8 @@ public static int superFastHash(int data, int hash) { /** * Sets a specific bit of an int. * - * @param bit - * the bit to set. The least significant bit is bit 0 - * @param target - * the integer where the bit will be set + * @param bit the bit to set. The least significant bit is bit 0 + * @param target the integer where the bit will be set * @return the updated value of the target */ public static int setBit(int bit, int target) { @@ -348,10 +317,8 @@ public static int setBit(int bit, int target) { /** * Clears a specific bit of an int. * - * @param bit - * the bit to clear. The least significant bit is bit 0 - * @param target - * the integer where the bit will be cleared + * @param bit the bit to clear. The least significant bit is bit 0 + * @param target the integer where the bit will be cleared * @return the updated value of the target */ public static int clearBit(int bit, int target) { @@ -394,17 +361,13 @@ public static int fuseImm(int upper16, int lower16) { upper16 = upper16 << 16; // Merge int result = upper16 | lower16; - // System.out.println("Upper16:"+ParseUtils.padLeft(Integer.toBinaryString(upper16), 16, '0')); - // System.out.println("Lower16:"+ParseUtils.padLeft(Integer.toBinaryString(lower16), 16, '0')); - // System.out.println("Fused:"+ParseUtils.padLeft(Integer.toBinaryString(result), 32, '0')); return result; } /** * Converts a signed byte to an unsigned integer representation. * - * @param aByte - * the byte to convert + * @param aByte the byte to convert * @return the unsigned integer representation of the byte */ public static int getUnsignedByte(byte aByte) { @@ -419,8 +382,7 @@ public static int getUnsignedByte(byte aByte) { /** * Calculates the base-2 logarithm of the given integer, rounding up. * - * @param i - * the integer to calculate the logarithm for + * @param i the integer to calculate the logarithm for * @return the base-2 logarithm of the integer, rounded up */ public static int log2(int i) { @@ -469,12 +431,12 @@ public static int signExtend(int value, int extendSize) { binaryString.append(getBit(i, value)); } - // return Integer.parseInt(binaryString.toString(), 2); return parseSignedBinary(binaryString.toString()); } /** - * Converts a 0-based, LSB-order bit to the corresponding index in a String representation of the number. + * Converts a 0-based, LSB-order bit to the corresponding index in a String + * representation of the number. * * @param signalBit * @param stringSize @@ -488,9 +450,10 @@ public static int fromLsbToStringIndex(int signalBit, int stringSize) { * Sign-extends the given String representing a binary value (only 0s and 1s). * * @param binaryValue - * @param signalBit - * the 0-based index, counting from the LSB, that represents the signal - * @return a String with the same size but where all values higher than signalBit are the same as the value at the + * @param signalBit the 0-based index, counting from the LSB, that represents + * the signal + * @return a String with the same size but where all values higher than + * signalBit are the same as the value at the * signalBit value. */ public static String signExtend(String binaryValue, int signalBit) { @@ -501,14 +464,14 @@ public static String signExtend(String binaryValue, int signalBit) { if (signalBit < 0) { throw new IllegalArgumentException("Signal bit must be a non-negative integer."); } - - // If bit is not represented in the binary value, value does not need sign extension + + // If bit is not represented in the binary value, value does not need sign + // extension if (signalBit >= binaryValue.length()) { return binaryValue; } // Convert LSB signalBit to String index - // int lsbSignalIndex = binaryValue.length() - signalBit - 1; int lsbSignalIndex = fromLsbToStringIndex(signalBit, binaryValue.length()); // Get signal bit @@ -522,8 +485,7 @@ public static String signExtend(String binaryValue, int signalBit) { /** * Parses a signed binary string into an integer. * - * @param binaryString - * the binary string to parse + * @param binaryString the binary string to parse * @return the integer representation of the binary string */ public static int parseSignedBinary(String binaryString) { @@ -581,8 +543,7 @@ public static int mask(int value, int numBits) { /** * Converts a boolean value to an integer representation. * - * @param boolResult - * the boolean value to convert + * @param boolResult the boolean value to convert * @return 1 if true, or 0 if false */ public static int boolToInt(boolean boolResult) { @@ -594,8 +555,9 @@ public static int boolToInt(boolean boolResult) { } /** - * Transforms the given integer value into an unsigned long. If the value is negative, returns the positive long - * value as if the given value is decoded from an equivalent 32-bit hexadecimal string. + * Transforms the given integer value into an unsigned long. If the value is + * negative, returns the positive long value as if the given value is decoded + * from an equivalent 32-bit hexadecimal string. * * @param value * @return @@ -609,9 +571,12 @@ public static Long getUnsignedLong(int value) { * Checks if a NaN is quiet. Does not test if number is a NaN. * *

- * IEEE 754 NaNs are represented with the exponential field filled with ones and some non-zero number in the - * significand. A bit-wise example of a IEEE floating-point standard single precision NaN: x111 1111 1axx xxxx xxxx - * xxxx xxxx xxxx where x means don't care. If a = 1, it is a quiet NaN, otherwise it is a signalling NaN. + * IEEE 754 NaNs are represented with the exponential field filled with ones and + * some non-zero number in the significand. A bit-wise example of a IEEE + * floating-point standard single precision NaN: + * x111 1111 1axx xxxx xxxx xxxx xxxx xxxx + * where x means don't care. If a = 1, it is a quiet NaN, otherwise it is a + * signalling NaN. * * @param aNanN * @return true if the given NaN is quiet. @@ -624,7 +589,8 @@ public static boolean isQuietNaN(int aNaN) { * Checks if a float is denormalized. * *

- * IEEE 754 denormals are identified by having the exponents bits set to zero (30 to 23). + * IEEE 754 denormals are identified by having the exponents bits set to zero + * (30 to 23). * * @param aFloat * @return true if the given float is denormal @@ -641,7 +607,8 @@ public static boolean isDenormal(int aFloat) { * Checks if a float is zero. * *

- * IEEE 754 zeros are identified by having the all bits except the sign set to zero (30 to 0). + * IEEE 754 zeros are identified by having the all bits except the sign set to + * zero (30 to 0). * * @param aFloat * @return true if the given float represents zero @@ -674,47 +641,46 @@ public static int getSignedInfinity(int floatBits) { * * * @param value - * @param byteOffset - * can have value 0 or 1, where 0 is the least significant short + * @param byteOffset can have value 0 or 1, where 0 is the least significant + * short * @return */ public static int getShort(int value, int byteOffset) { switch (byteOffset) { - case 0: - return value & 0x0000FFFF; - case 2: - return (value & 0xFFFF0000) >>> 16; - default: - throw new RuntimeException("Invalid case: " + byteOffset); + case 0: + return value & 0x0000FFFF; + case 2: + return (value & 0xFFFF0000) >>> 16; + default: + throw new RuntimeException("Invalid case: " + byteOffset); } } /** * Extracts a specific byte from an integer. * - * @param value - * the integer to extract the byte from - * @param byteOffset - * the offset of the byte to extract (0-based) + * @param value the integer to extract the byte from + * @param byteOffset the offset of the byte to extract (0-based) * @return the extracted byte as an integer */ public static int getByte(int value, int byteOffset) { switch (byteOffset) { - case 0: - return value & 0x000000FF; - case 1: - return (value & 0x0000FF00) >>> 8; - case 2: - return (value & 0x00FF0000) >>> 16; - case 3: - return (value & 0xFF000000) >>> 24; - default: - throw new RuntimeException("Invalid case: " + byteOffset); + case 0: + return value & 0x000000FF; + case 1: + return (value & 0x0000FF00) >>> 8; + case 2: + return (value & 0x00FF0000) >>> 16; + case 3: + return (value & 0xFF000000) >>> 24; + default: + throw new RuntimeException("Invalid case: " + byteOffset); } } /** - * Reads an unsigned 16-bit number from a byte array. This method reads two bytes from the array, starting at the + * Reads an unsigned 16-bit number from a byte array. This method reads two + * bytes from the array, starting at the * given offset. * * @param byteArray @@ -731,28 +697,15 @@ public static int readUnsignedShort(byte[] byteArray, int offset, result |= SpecsBits.positionByte(byteArray[offset + i], i, numBytes, isLittleEndian); } return result; - /* - if(isLittleEndian) { - return byteArray[offset] << BITS_IN_A_BYTE*0 | byteArray[offset+1] << BITS_IN_A_BYTE*1; - //return byteArray[offset] << BITS_IN_A_BYTE*0 | byteArray[offset+1] << BITS_IN_A_BYTE*1 | byteArray[offset+2] << BITS_IN_A_BYTE*2; - } else { - return byteArray[offset] << BITS_IN_A_BYTE*1 | byteArray[offset+1] << BITS_IN_A_BYTE*0; - //return byteArray[offset] << BITS_IN_A_BYTE*2 | byteArray[offset+1] << BITS_IN_A_BYTE*1 | byteArray[offset+2] << BITS_IN_A_BYTE*0; - } - * - */ } /** - * Reads an unsigned 32-bit number from a byte array. This method reads four bytes from the array, starting at the - * given offset. + * Reads an unsigned 32-bit number from a byte array. This method reads four + * bytes from the array, starting at the given offset. * - * @param byteArray - * the byte array to read from - * @param offset - * the starting offset in the array - * @param isLittleEndian - * whether the bytes are in little-endian order + * @param byteArray the byte array to read from + * @param offset the starting offset in the array + * @param isLittleEndian whether the bytes are in little-endian order * @return the unsigned 32-bit number as a long */ public static long readUnsignedInteger(byte[] byteArray, int offset, @@ -768,15 +721,15 @@ public static long readUnsignedInteger(byte[] byteArray, int offset, } /** - * Positions a byte inside a bigger unit according to its endianess and the position of the byte. A long is used to - * support unsigned integers. + * Positions a byte inside a bigger unit according to its endianess and the + * position of the byte. A long is used to support unsigned integers. * - * TODO: Test/check this method so see if it can support longs, not just integers + * TODO: Test/check this method so see if it can support longs, not just + * integers * * @param aByte * @param bytePosition - * @param totalBytes - * the bytes of the unit (short = 2, int = 4). + * @param totalBytes the bytes of the unit (short = 2, int = 4). * @param isLittleEndian * @return */ @@ -791,19 +744,13 @@ public static long positionByte(byte aByte, int bytePosition, int totalBytes, bo int shift = SpecsBits.BITS_IN_A_BYTE * multiplier; int shiftedByte = getUnsignedByte(aByte) << shift; - // System.out.println("Byte:"+aByte); - // System.out.println("Unsigned Byte:"+BitUtils.getUnsignedByte(aByte)); - // System.out.println("Shift:"+multiplier); - // System.out.println("Shifted:"+shiftedByte); - return shiftedByte; } /** * Reverses the half-words in the given integer. * - * @param data - * the integer to reverse the half-words of + * @param data the integer to reverse the half-words of * @return the integer with reversed half-words */ public static int reverseHalfWords(int data) { @@ -817,8 +764,7 @@ public static int reverseHalfWords(int data) { /** * Reverses the bytes in the given integer. * - * @param data - * the integer to reverse the bytes of + * @param data the integer to reverse the bytes of * @return the integer with reversed bytes */ public static int reverse(int data) { @@ -826,11 +772,6 @@ public static int reverse(int data) { byte[] bytes = ByteBuffer.allocate(4).putInt(data).array(); byte[] reversedBytes = SpecsBits.reverse(bytes); - // System.out.println("ARRAY BEFORE:" + Arrays.toString(bytes)); - // Someone on StackOverflow indicated this solution - // http://stackoverflow.com/questions/12678781/reversing-an-array-in-java - // Collections.reverse(Arrays.asList(bytes)); - // System.out.println("ARRAY AFTER:" + Arrays.toString(reversedBytes)); // Create reversed int ByteBuffer wrapped = ByteBuffer.wrap(reversedBytes); // big-endian by default @@ -841,8 +782,7 @@ public static int reverse(int data) { /** * Reverses the bytes in the given short. * - * @param data - * the short to reverse the bytes of + * @param data the short to reverse the bytes of * @return the short with reversed bytes */ public static short reverse(short data) { @@ -860,8 +800,7 @@ public static short reverse(short data) { /** * Reverses the order of bytes in the given array. * - * @param bytes - * the array of bytes to reverse + * @param bytes the array of bytes to reverse * @return the array with reversed byte order */ public static byte[] reverse(byte[] bytes) { @@ -876,8 +815,7 @@ public static byte[] reverse(byte[] bytes) { /** * Decodes an unsigned byte value from a string representation. * - * @param unsignedByteValue - * the string representation of the unsigned byte value + * @param unsignedByteValue the string representation of the unsigned byte value * @return the decoded unsigned byte value */ public static byte decodeUnsignedByte(String unsignedByteValue) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsCheck.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsCheck.java index b3c515b9..24643706 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsCheck.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsCheck.java @@ -20,7 +20,8 @@ /** * Utility methods for runtime checks and assertions. *

- * Provides static helper methods for validating arguments, states, and error conditions at runtime. + * Provides static helper methods for validating arguments, states, and error + * conditions at runtime. *

* * @author Joao Bispo @@ -31,7 +32,8 @@ private SpecsCheck() { } /** - * Validates that a given expression is true. Throws an IllegalArgumentException if the expression is false. + * Validates that a given expression is true. Throws an IllegalArgumentException + * if the expression is false. * * @param expression the condition to validate * @param supplier a supplier providing the error message @@ -43,7 +45,8 @@ public static void checkArgument(boolean expression, Supplier supplier) } /** - * Ensures that the given reference is not null. Throws a NullPointerException if the reference is null. + * Ensures that the given reference is not null. Throws a NullPointerException + * if the reference is null. * * @param reference the object to check for nullity * @param supplier a supplier providing the error message @@ -59,8 +62,8 @@ public static T checkNotNull(T reference, Supplier supplier) { } /** - * Validates that the size of the given collection matches the expected size. Throws an IllegalArgumentException if - * the sizes do not match. + * Validates that the size of the given collection matches the expected size. + * Throws an IllegalArgumentException if the sizes do not match. * * @param collection the collection to check * @param expectedSize the expected size of the collection @@ -70,8 +73,8 @@ public static void checkSize(Collection collection, int expectedSize) { } /** - * Validates that the size of the given array matches the expected size. Throws an IllegalArgumentException if the - * sizes do not match. + * Validates that the size of the given array matches the expected size. Throws + * an IllegalArgumentException if the sizes do not match. * * @param objects the array to check * @param expectedSize the expected size of the array @@ -81,12 +84,13 @@ public static void checkSize(Object[] objects, int expectedSize) { } /** - * Validates that the size of a collection or array matches the expected size. Throws an IllegalArgumentException if - * the sizes do not match. + * Validates that the size of a collection or array matches the expected size. + * Throws an IllegalArgumentException if the sizes do not match. * - * @param expectedSize the expected size - * @param actualSize the actual size - * @param collectionContents a supplier providing the contents of the collection or array + * @param expectedSize the expected size + * @param actualSize the actual size + * @param collectionContents a supplier providing the contents of the collection + * or array */ private static void checkSize(int expectedSize, int actualSize, Supplier collectionContents) { if (actualSize != expectedSize) { @@ -96,8 +100,8 @@ private static void checkSize(int expectedSize, int actualSize, Supplier } /** - * Validates that the size of the given collection is within the specified range. Throws an IllegalArgumentException - * if the size is outside the range. + * Validates that the size of the given collection is within the specified + * range. Throws an IllegalArgumentException if the size is outside the range. * * @param collection the collection to check * @param minSize the minimum size @@ -108,25 +112,26 @@ public static void checkSizeRange(Collection collection, int minSize, int max } /** - * Validates that the size of the given array is within the specified range. Throws an IllegalArgumentException if - * the size is outside the range. + * Validates that the size of the given array is within the specified range. + * Throws an IllegalArgumentException if the size is outside the range. * - * @param objects the array to check - * @param minSize the minimum size - * @param maxSize the maximum size + * @param objects the array to check + * @param minSize the minimum size + * @param maxSize the maximum size */ public static void checkSizeRange(Object[] objects, int minSize, int maxSize) { checkSizeRange(minSize, maxSize, objects.length, () -> Arrays.toString(objects)); } /** - * Validates that the size of a collection or array is within the specified range. Throws an IllegalArgumentException - * if the size is outside the range. + * Validates that the size of a collection or array is within the specified + * range. Throws an IllegalArgumentException if the size is outside the range. * - * @param minSize the minimum size - * @param maxSize the maximum size - * @param actualSize the actual size - * @param collectionContents a supplier providing the contents of the collection or array + * @param minSize the minimum size + * @param maxSize the maximum size + * @param actualSize the actual size + * @param collectionContents a supplier providing the contents of the collection + * or array */ private static void checkSizeRange(int minSize, int maxSize, int actualSize, Supplier collectionContents) { if (actualSize < minSize || actualSize > maxSize) { @@ -137,8 +142,8 @@ private static void checkSizeRange(int minSize, int maxSize, int actualSize, Sup } /** - * Validates that the given value is an instance of the specified class. Throws an IllegalArgumentException if the - * value is not an instance of the class. + * Validates that the given value is an instance of the specified class. Throws + * an IllegalArgumentException if the value is not an instance of the class. * * @param value the object to check * @param aClass the class to check against diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsCollections.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsCollections.java index 9b84f77e..73e55e16 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsCollections.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsCollections.java @@ -78,7 +78,8 @@ public static K last(List lines) { } /** - * Returns the last element of the list, or an empty Optional if the list is empty. + * Returns the last element of the list, or an empty Optional if the list is + * empty. * * @param lines * @return @@ -112,18 +113,6 @@ public static Iterable iterable(final Iterator iterator) { return () -> iterator; } - /* - public static List asListSame(List elements) { - List list = FactoryUtils.newArrayList(); - - for (K element : elements) { - list.add(element); - } - - return list; - } - */ - /** * @param a * @return @@ -160,7 +149,6 @@ public static List asListT(Class superClass, Object... elements) { } public static , K> List getKeyList(List providers) { - // public static List asList(List> providers) { List list = new ArrayList<>(); for (T provider : providers) { @@ -187,7 +175,8 @@ public static > List newSorted(Collection } /** - * Removes the tokens from the list from startIndex, inclusive, to endIndex, exclusive. + * Removes the tokens from the list from startIndex, inclusive, to endIndex, + * exclusive. * * @param list * @param startIndex @@ -222,7 +211,8 @@ public static List remove(List list, List indexes) { } /** - * Removes from the list the elements that match the predicate, returns the removed elements. + * Removes from the list the elements that match the predicate, returns the + * removed elements. * * @param list * @param filter @@ -265,8 +255,8 @@ public static U removeLast(List list, Class targetClass) } /** - * Returns the first index of object that is an instance of the given class. Returns -1 if no object is found that - * is instance of the class. + * Returns the first index of object that is an instance of the given class. + * Returns -1 if no object is found that is instance of the class. * * @param aClass * @param types @@ -291,8 +281,8 @@ public static int getFirstIndex(List list, Class aClass) { } /** - * Returns the first object that is an instance of the given class. Returns null if no object is found that is - * instance of the class. + * Returns the first object that is an instance of the given class. Returns null + * if no object is found that is instance of the class. * * @param aClass * @param types @@ -311,24 +301,8 @@ public static T getFirst(List list, Class aClass) { } /** - * Casts an element of a list to the given class. - * - * @param aClass - * @param list - * @param index - * @return - */ - /* - public static T get(Class aClass, List list, int index) { - - Object element = list.get(index); - - return aClass.cast(element); - } - */ - - /** - * Returns true if all the elements in the list are instances of the given class. + * Returns true if all the elements in the list are instances of the given + * class. * * @param inputTypes * @return @@ -344,7 +318,8 @@ public static boolean areOfType(Class aClass, List list) { } /** - * Adds the elements of the provider collection to the receiver collection. Returns the receiver collection. + * Adds the elements of the provider collection to the receiver collection. + * Returns the receiver collection. * * @param receiver * @param provider @@ -356,7 +331,8 @@ public static > T add(T receiver, T provider) { } /** - * Casts a list of one type to another type, and checks if all elements can be cast to the target type. + * Casts a list of one type to another type, and checks if all elements can be + * cast to the target type. * * @param list * @param aClass @@ -384,7 +360,8 @@ public static T[] cast(Object[] array, Class targetClass) { } /** - * Casts a list of one type to another type, without checking if the elements can be cast to the target type. + * Casts a list of one type to another type, without checking if the elements + * can be cast to the target type. * * @param list * @param aClass @@ -393,13 +370,6 @@ public static T[] cast(Object[] array, Class targetClass) { @SuppressWarnings("unchecked") public static List castUnchecked(List list, Class aClass) { return (List) list; - /* - List newList = new ArrayList<>(); - - list.forEach(element -> newList.add(aClass.cast(element))); - - return newList; - */ } /** @@ -507,9 +477,6 @@ public static List concatLists(Collection... collections) { * @return */ public static D[] convert(O[] origin, D[] destination, Function converter) { - - // D[] destination = (D[]) new Object[origin.length]; - for (int i = 0; i < origin.length; i++) { destination[i] = converter.apply(origin[i]); } @@ -518,10 +485,12 @@ public static D[] convert(O[] origin, D[] destination, Function con } /** - * Turns an Optional into a Stream of length zero or one depending upon whether a value is present. + * Turns an Optional into a Stream of length zero or one depending upon + * whether a value is present. * *

- * Source: http://stackoverflow.com/questions/22725537/using-java-8s-optional-with-streamflatmap + * Source: + * http://stackoverflow.com/questions/22725537/using-java-8s-optional-with-streamflatmap */ public static Stream toStream(Optional opt) { if (opt.isPresent()) { @@ -532,7 +501,8 @@ public static Stream toStream(Optional opt) { } /** - * Filters the elements of a Collection according to a map function over the elements of that collection. + * Filters the elements of a Collection according to a map function over the + * elements of that collection. * * @param elements * @param mapFunction @@ -543,7 +513,8 @@ public static List filter(Collection elements, Function mapFu } /** - * Filters the elements of a Stream according to a map function over the elements of that collection. + * Filters the elements of a Stream according to a map function over the + * elements of that collection. * * @param elements * @param mapFunction @@ -566,8 +537,8 @@ public static List map(Collection list, Function mapper) { } /** - * Removes all the elements at the head that are an instance of the given class, returns a new list with those - * elements. + * Removes all the elements at the head that are an instance of the given class, + * returns a new list with those elements. * * @param aClass * @param list @@ -620,8 +591,8 @@ public static ET popSingle(List list, Class aClass) { } /** - * Returns all the elements at the head that are an instance of the given class, returns a new list with those - * elements. + * Returns all the elements at the head that are an instance of the given class, + * returns a new list with those elements. * * @param list * @param aClass @@ -634,7 +605,8 @@ public static List peek(List list, Class aClass) { List newList = new ArrayList<>(); - // Starting on the first element, add elements until it finds an element that is not of the type + // Starting on the first element, add elements until it finds an element that is + // not of the type for (T element : list) { // Stop if element is not of type if (!aClass.isInstance(element)) { @@ -673,7 +645,8 @@ public static boolean instanceOf(T object, Collection> cl } /** - * Creates a list with the given element, unless it is null. In that case, returns an empty list. + * Creates a list with the given element, unless it is null. In that case, + * returns an empty list. * * @param element * @return @@ -687,7 +660,8 @@ public static List ofNullable(T element) { } /** - * Accepts lists that have at most one element, return the element if present, or null otherwise. + * Accepts lists that have at most one element, return the element if present, + * or null otherwise. * * @param selectCond * @return @@ -726,11 +700,6 @@ public static Map newHashMap() { public static Set newHashSet(K... elements) { return new HashSet<>(Arrays.asList(elements)); } - /* - public static T[] toArray(List list) { - return list.toArray(new T[0]); - } - */ /** * Adds to the list if element is present, and does nothing otherwise. @@ -771,10 +740,6 @@ public static Optional findFirstNonEmpty(Stream> stream) { * @return a stream of the elements of the list, in reverse order */ public static Stream reverseStream(List list) { - // int from = 0; - // int to = list.size(); - // - // return IntStream.range(from, to).map(i -> to - i + from - 1).mapToObj(i -> list.get(i)); return reverseIndexStream(list).mapToObj(i -> list.get(i)); } @@ -783,7 +748,6 @@ public static Stream reverseStream(List list) { * @return a stream of indexes to the list, in reverse order */ public static IntStream reverseIndexStream(List list) { - int from = 0; int to = list.size(); @@ -817,7 +781,8 @@ public static > String[] toStringArray(Collection< } /** - * Converts a collection to a set, applying the given mapper to each of the elements. + * Converts a collection to a set, applying the given mapper to each of the + * elements. * * @param collection * @param mapper @@ -843,11 +808,8 @@ public static BitSet copy(BitSet bitSet) { } public static T[] newArray(Class targetClass, int size) { - - // newInstance returns a new array @SuppressWarnings("unchecked") var newArray = (T[]) Array.newInstance(targetClass, size); - return newArray; } @@ -870,7 +832,8 @@ public static List get(List list, Class targetClass) { } /** - * Converts the definition to an optional. If the list contains more than one element, throws an exception. + * Converts the definition to an optional. If the list contains more than one + * element, throws an exception. * * @param definition * @return @@ -940,8 +903,9 @@ public static Set or(Collection... collections) { } /** - * If the key has a mapping different than null, just returns the value, otherwise uses the given Supplier to create - * the first value, associates it in the map, and returns it. + * If the key has a mapping different than null, just returns the value, + * otherwise uses the given Supplier to create the first value, associates it in + * the map, and returns it. * * @param * @param @@ -961,9 +925,4 @@ public static V getOrSet(Map map, K key, Supplier defaultValue) return value; } - // @SuppressWarnings("unchecked") - // public static T[] arrayGenerator(int size, Class aClass) { - // return (T[]) Array.newInstance(aClass, size); - // // return aClass.arrayType(). T[size]; - // } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsEnums.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsEnums.java index 2ea81c75..95632a84 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsEnums.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsEnums.java @@ -44,31 +44,22 @@ public class SpecsEnums { private static final ThreadLocal>, EnumHelper>> ENUM_HELPERS = ThreadLocal .withInitial(() -> new HashMap<>()); - // private static final ThreadLocal>, EnumHelper>> ENUM_HELPERS_CACHE = - // ThreadLocal - // .withInitial(() -> new CachedItems<>(enumClass -> new EnumHelper(enumClass))); - /** - * Transforms a String into a constant of the same name in a specific Enum. Returns null instead of throwing + * Transforms a String into a constant of the same name in a specific Enum. + * Returns null instead of throwing * exceptions. * * - * @param - * The Enum where the constant is - * @param enumType - * the Class object of the enum type from which to return a constant - * @param name - * the name of the constant to return - * @return the constant of enum with the same name, or the first element (ordinal order) if not found, with a + * @param The Enum where the constant is + * @param enumType the Class object of the enum type from which to return a + * constant + * @param name the name of the constant to return + * @return the constant of enum with the same name, or the first element + * (ordinal order) if not found, with a * warning */ public static > T valueOf(Class enumType, String name) { try { - // If enum implements StringProvider, use EnumHelper - // if (StringProvider.class.isAssignableFrom(enumType)) { - // return getHelper(enumType).fromName(name); - // } - return Enum.valueOf(enumType, name); } catch (Exception e) { @@ -101,13 +92,12 @@ public static > List getValues(Class enumType, List - * The Enum where the constant is - * @param enumType - * the Class object of the enum type from which to return a constant - * @param name - * the name of the constant to return - * @return true if the Enum contains a constant with the same name, false otherwise + * @param The Enum where the constant is + * @param enumType the Class object of the enum type from which to return a + * constant + * @param name the name of the constant to return + * @return true if the Enum contains a constant with the same name, false + * otherwise */ public static > boolean containsEnum(Class enumType, String name) { T enumeration = valueOf(enumType, name); @@ -120,11 +110,12 @@ public static > boolean containsEnum(Class enumType, String } /** - * Builds an unmmodifiable table which maps the string representation of the enum to the enum itself. + * Builds an unmmodifiable table which maps the string representation of the + * enum to the enum itself. * *

- * This table can be useful to get the enum correspondent to a particular option in String format which was - * collected from, for example, a config file. + * This table can be useful to get the enum correspondent to a particular option + * in String format which was collected from, for example, a config file. * * @param * @param values @@ -141,13 +132,12 @@ public static > Map buildMap(K[] values) { } /** - * Builds a n unmodifiable of the enum to the enum itself. If the enum implements StringProvider, .getString() is - * used instead of .name(). - * + * Builds a n unmodifiable of the enum to the enum itself. If the enum + * implements StringProvider, .getString() is used instead of .name(). * *

- * This table can be useful to get the enum correspondent to a particular option in String format which was - * collected from, for example, a config file. + * This table can be useful to get the enum correspondent to a particular option + * in String format which was collected from, for example, a config file. * * @param * @param values @@ -224,18 +214,15 @@ public static > Class getClass(K[] values) { } public static List extractValues(List> enumClasses) { - // List values = new ArrayList<>(); - return enumClasses.stream() .map(anEnumClass -> extractValues(anEnumClass)) .flatMap(List::stream) .collect(Collectors.toList()); - - // return values; } /** - * If the class represents an enum, returns a list with the values of that enum. Otherwise, returns null. + * If the class represents an enum, returns a list with the values of that enum. + * Otherwise, returns null. * * @param anEnumClass * @return @@ -259,8 +246,8 @@ public static > List extractValuesV2(Class anE } /** - * If the class represents an enum, returns a list of Strings with the names of the values of that enum. Otherwise, - * returns null. + * If the class represents an enum, returns a list of Strings with the names of + * the values of that enum. Otherwise, returns null. * * @param anEnumClass * @return @@ -278,24 +265,13 @@ public static > List extractNames(Class a } /** - * Extracts an instance of an interface from a class which represents an Enum which implements such interface. + * Extracts an instance of an interface from a class which represents an Enum + * which implements such interface. * * @param enumSetupDefiner */ - // public static > Object getInterfaceFromEnum(Class enumImplementingInterface, public static > Object getInterfaceFromEnum(Class enumImplementingInterface, Class interfaceClass) { - - /* - // Check class - if (!enumImplementingInterface.isEnum()) { - LoggingUtils.getLogger().warning( - "Class '" + enumImplementingInterface.getName() - + "' does not represent an enum."); - return null; - } - */ - // Build set with interfaces of the given class Class[] interfacesArray = enumImplementingInterface.getInterfaces(); List> interfacesList = Arrays.asList(interfacesArray); @@ -315,22 +291,20 @@ public static > Object getInterfaceFromEnum(Class enumImple /** * *

- * The following code can be used to dump the complement collection into a newly allocated array: + * The following code can be used to dump the complement collection into a newly + * allocated array: *

* AnEnum[] y = EnumUtils.getComplement(new AnEnum[0], anEnum1, anEnum2); * * @param - * @param a - * a - the array into which the elements of this set are to be stored, if it is big enough; otherwise, a - * new array of the same runtime type is allocated for this purpose. + * @param a a - the array into which the elements of this set are to be + * stored, if it is big enough; otherwise, a + * new array of the same runtime type is allocated for this + * purpose. * @param values * @return */ - // public static > K[] getComplement(K[] a, K... values) { public static > K[] getComplement(K[] a, List values) { - // EnumSet originalSet = EnumSet.copyOf(Arrays.asList(values)); - // Set complementSet = EnumSet.complementOf(originalSet); - EnumSet complementSet = SpecsEnums.getComplement(values); return complementSet.toArray(a); } @@ -349,8 +323,6 @@ public static > EnumSet getComplement(List values) { * @return */ public static & KeyProvider, T> Map buildMap(Class enumClass) { - - // Map enumMap = FactoryUtils.newHashMap(); Map enumMap = new LinkedHashMap<>(); for (K enumConstant : enumClass.getEnumConstants()) { enumMap.put(enumConstant.getKey(), enumConstant); @@ -379,28 +351,6 @@ public static > T getFirstEnum(Class anEnumClass) { return enums[0]; } - /** - * @param class1 - * @return - */ - /* - public static & ResourceProvider> List getResources(Class enumClass) { - K[] enums = enumClass.getEnumConstants(); - - List resources = FactoryUtils.newArrayList(enums.length); - - for (K anEnum : enums) { - resources.add(anEnum.getResource()); - } - - return resources; - } - */ - - /** - * @param class1 - * @return - */ public static & KeyProvider> List getKeys(Class enumClass) { K[] enums = enumClass.getEnumConstants(); @@ -414,8 +364,8 @@ public static & KeyProvider> List getKeys(Class e } /** - * Returns a string representing the enum options using ',' as delimiter and '[' and ']' and prefix and suffix, - * respectively. + * Returns a string representing the enum options using ',' as delimiter and '[' + * and ']' and prefix and suffix, respectively. * * @param anEnumClass * @return @@ -432,9 +382,6 @@ public static > String getEnumOptions(Class anEnumClass) { public static > T fromName(Class enumType, String name) { return SpecsEnums.valueOf(enumType, name); - // EnumHelper helper = getHelper(enumType); - // return enumType.cast(helper.fromName(name)); - } public static > T fromOrdinal(Class enumClass, int ordinal) { @@ -448,9 +395,6 @@ public static > EnumHelper getHelper(Class enumClass) { if (helper == null) { helper = new EnumHelper<>(enumClass); ENUM_HELPERS.get().put((Class>) enumClass, helper); - // System.out.println("CREATED ENUM HELPER FOR " + enumClass); - } else { - // System.out.println("REUSED ENUM HELPER FOR " + enumClass); } return (EnumHelper) helper; @@ -464,7 +408,8 @@ public static > T[] values(Class enumClass) { * * @param * @param anEnum - * @return the next enum, according to the ordinal order, or the first enum if this one is the last + * @return the next enum, according to the ordinal order, or the first enum if + * this one is the last */ public static > T nextEnum(T anEnum) { @SuppressWarnings("unchecked") diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsFactory.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsFactory.java index 50109b3c..4887fd50 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsFactory.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsFactory.java @@ -31,22 +31,27 @@ import java.util.Set; /** - * @deprecated This class was created when the code base was still using Java 5.0. With Java 7, the Diamond Operator and the - * Collections methods, this class should no longer be used. Consider using Guava classes in com.google.common.collect, such as Maps, - * Lists, etc. + * @deprecated This class was created when the code base was still using Java + * 5.0. With Java 7, the Diamond Operator and the Collections + * methods, this class should no longer be used. + * Consider using Guava classes in com.google.common.collect, such + * as Maps, Lists, etc. * - * Factory methods for common objects, such as the ones in Java Collections. + * Factory methods for common objects, such as the ones in Java + * Collections. * - *

- * The purpose of theses methods is to avoid writing the generic type when creating a new class. + *

+ * The purpose of theses methods is to avoid writing the generic + * type when creating a new class. * - *

- * IMPORTANT: Instead of using this class, consider using Guava classes in com.google.common.collect, such as Maps, - * Lists, etc. + *

+ * IMPORTANT: Instead of using this class, consider using Guava + * classes in com.google.common.collect, such as Maps, Lists, etc. * - *

- * PS.: This class was created when the code base was still using Java 5.0. With Java 7, the Diamond Operator and the - * Collections methods, this class should no longer be used. + *

+ * PS.: This class was created when the code base was still using + * Java 5.0. With Java 7, the Diamond Operator and the Collections + * methods, this class should no longer be used. * * @author Joao Bispo */ @@ -57,7 +62,7 @@ public class SpecsFactory { * Creates a list of the given class type, containing 'elements'. * * @param listClass the class type of the list elements - * @param elements the elements to be added to the list + * @param elements the elements to be added to the list * @return a list containing the given elements */ public static List asList(Class listClass, Object... elements) { @@ -89,7 +94,7 @@ public static List newArrayList() { * Creates a new ArrayList with the specified initial capacity. * * @param initialCapacity the initial capacity of the list - * @param the type of elements in the list + * @param the type of elements in the list * @return a new ArrayList */ public static List newArrayList(int initialCapacity) { @@ -100,7 +105,7 @@ public static List newArrayList(int initialCapacity) { * Creates a new ArrayList containing the elements of the specified collection. * * @param elements the collection whose elements are to be placed into the list - * @param the type of elements in the list + * @param the type of elements in the list * @return a new ArrayList */ public static List newArrayList(Collection elements) { @@ -121,7 +126,7 @@ public static List newLinkedList() { * Creates a new LinkedList containing the elements of the specified collection. * * @param elements the collection whose elements are to be placed into the list - * @param the type of elements in the list + * @param the type of elements in the list * @return a new LinkedList */ public static List newLinkedList(Collection elements) { @@ -170,8 +175,8 @@ public static Map newLinkedHashMap() { * Creates a new EnumMap for the specified key class. * * @param keyClass the class of the keys in the map - * @param the type of keys in the map - * @param the type of values in the map + * @param the type of keys in the map + * @param the type of values in the map * @return a new EnumMap */ public static , V> Map newEnumMap(Class keyClass) { @@ -182,7 +187,7 @@ public static , V> Map newEnumMap(Class keyClass) { * Creates a new HashSet containing the elements of the specified collection. * * @param elements the collection whose elements are to be placed into the set - * @param the type of elements in the set + * @param the type of elements in the set * @return a new HashSet */ public static Set newHashSet(Collection elements) { @@ -203,8 +208,8 @@ public static Set newHashSet() { * Creates a new LinkedHashMap containing the mappings of the specified map. * * @param elements the map whose mappings are to be placed into the new map - * @param the type of keys in the map - * @param the type of values in the map + * @param the type of keys in the map + * @param the type of values in the map * @return a new LinkedHashMap */ public static Map newLinkedHashMap(Map elements) { @@ -222,10 +227,11 @@ public static Set newLinkedHashSet() { } /** - * Creates a new LinkedHashSet containing the elements of the specified collection. + * Creates a new LinkedHashSet containing the elements of the specified + * collection. * * @param elements the collection whose elements are to be placed into the set - * @param the type of elements in the set + * @param the type of elements in the set * @return a new LinkedHashSet */ public static Set newLinkedHashSet(Collection elements) { @@ -266,10 +272,11 @@ public static Map assignMap(Map map) { } /** - * Builds a set with a sequence of integers starting at 'startIndex' and with 'size' integers. + * Builds a set with a sequence of integers starting at 'startIndex' and with + * 'size' integers. * * @param startIndex the starting index of the sequence - * @param size the number of integers in the sequence + * @param size the number of integers in the sequence * @return a set containing the sequence of integers */ public static Set newSetSequence(int startIndex, int size) { @@ -300,14 +307,17 @@ public static List fromIntArray(int[] array) { } /** - * If the given value is null, returns an empty collection. Otherwise, returns an unmodifiable view of the list. + * If the given value is null, returns an empty collection. Otherwise, returns + * an unmodifiable view of the list. * *

- * This method is useful for final fields whose contents do not need to be changed. + * This method is useful for final fields whose contents do not need to be + * changed. * * @param aList the list to be checked - * @param the type of elements in the list - * @return an unmodifiable view of the list, or an empty list if the original list is null or empty + * @param the type of elements in the list + * @return an unmodifiable view of the list, or an empty list if the original + * list is null or empty */ public static List getUnmodifiableList(List aList) { if (aList == null) { @@ -321,14 +331,15 @@ public static List getUnmodifiableList(List aList) { } /** - * Method similar to Collections.addAll, but that accepts 'null' as the source argument. + * Method similar to Collections.addAll, but that accepts 'null' as the source + * argument. * *

* If the source argument is null, the collection sink remains unmodified. * - * @param sink the collection to which elements are to be added + * @param sink the collection to which elements are to be added * @param source the collection whose elements are to be added to the sink - * @param the type of elements in the collections + * @param the type of elements in the collections */ public static void addAll(Collection sink, Collection source) { if (source == null) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsGraphviz.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsGraphviz.java index 8b38c577..2defc9aa 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsGraphviz.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsGraphviz.java @@ -164,10 +164,6 @@ public static String parseLabel(String label) { */ public static String formatId(String label) { return formatId(label, '0', '0'); - - // String newLabel = label.replace('[', '0'); - // newLabel = newLabel.replace(']', '0'); - // return newLabel; } public static String formatId(String label, char leftSquare, char rightSquare) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsIo.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsIo.java index 978925e6..c247a40e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsIo.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsIo.java @@ -76,7 +76,8 @@ /** * Utility methods for input/output operations. *

- * Provides static helper methods for reading, writing, and managing files and resources. + * Provides static helper methods for reading, writing, and managing files and + * resources. *

* * @author Joao Bispo @@ -160,35 +161,32 @@ public static File mkdir(File folder) { } /** - * Given a string representing a filepath to a folder, returns a File object representing the folder. + * Given a string representing a filepath to a folder, returns a File object + * representing the folder. * *

- * If the folder doesn't exist, the method will try to create the folder and necessary sub-folders. If an error - * occurs (ex.: the folder could not be created, the given path does not represent a folder), throws an exception. + * If the folder doesn't exist, the method will try to create the folder and + * necessary sub-folders. If an error occurs (ex.: the folder could not be + * created, the given path does not represent a folder), throws an exception. * - * * *

- * If the given folderpath is an empty string, returns the current working folder. + * If the given folderpath is an empty string, returns the current working + * folder. * *

* If the method returns it is guaranteed that the folder exists. * - * @param folderpath - * String representing a folder. + * @param folderpath String representing a folder. * @return a File object representing a folder, or null if unsuccessful. */ public static File mkdir(String folderpath) { // Check null argument. If null, it would raise and exception and stop // the program when used to create the File object. if (folderpath == null) { - // Logger.getLogger(IoUtils.class.getName()).warning("Input 'folderpath' is null."); throw new RuntimeException("Input 'folderpath' is null"); - // LoggingUtils.msgWarn("Input 'folderpath' is null."); - // return null; } // Check if folderpath is empty - // if (folderpath.isEmpty()) { if (SpecsStrings.isEmpty(folderpath)) { return SpecsIo.getWorkingDir(); } @@ -208,13 +206,7 @@ public static File mkdir(String folderpath) { // Check if is a file. If true, stop final boolean folderExists = folder.isFile(); if (folderExists) { - // folder = folder.getParentFile(); - // Logger.getLogger(IoUtils.class.getName()).log(Level.WARNING, - // "Path '" + folderpath + "' exists, but " + - // "doesn''t represent a folder."); throw new RuntimeException("Path '" + folderpath + "' exists, but " + "doesn't represent a folder"); - // LoggingUtils.msgInfo("Path '" + folderpath + "' exists, but " + "doesn't represent a folder."); - // return null; } // Try to create folder. @@ -236,24 +228,18 @@ public static File mkdir(String folderpath) { } // Couldn't create folder - // Logger.getLogger(IoUtils.class.getName()). - // log(Level.WARNING,"Path '" + folderpath+"' does not exist and " + - // "could not be created."); throw new RuntimeException("Path '" + folderpath + "' does not exist and " + "could not be created"); - // LoggingUtils.msgWarn("Path '" + folderpath + "' does not exist and " + "could not be created."); - // return null; - } /** * Method to create a File object for a file which should exist. * *

- * The method does some common checks (ex.: if the file given by filepath exists, if it is a file). If any of the + * The method does some common checks (ex.: if the file given by filepath + * exists, if it is a file). If any of the * checks fail, throws an exception. * - * @param filepath - * String representing an existing file. + * @param filepath String representing an existing file. * @return a File object representing a file, or null if unsuccessful. */ public static File existingFile(String filepath) { @@ -261,8 +247,6 @@ public static File existingFile(String filepath) { // the program when used to create the File object. if (filepath == null) { throw new RuntimeException("Input 'filepath' is null"); - // LoggingUtils.msgWarn("Input 'filepath' is null."); - // return null; } // Create File object @@ -278,15 +262,10 @@ public static File existingFile(String filepath) { final boolean fileExists = file.exists(); if (fileExists) { throw new RuntimeException("Path '" + filepath + "' exists, but doesn't " + "represent a file"); - // LoggingUtils.msgWarn("Path '" + filepath + "' exists, but doesn't " + "represent a file."); - // return null; } // File doesn't exist, return null. throw new RuntimeException("Path '" + filepath + "' does not exist"); - // LoggingUtils.msgWarn("Path '" + filepath + "' does not exist."); - // return null; - } /** @@ -303,10 +282,10 @@ public static String read(String filename) { * Given a File object, returns a String with the contents of the file. * *

- * If an error occurs (ex.: the File argument does not represent a file) returns null and logs the cause. + * If an error occurs (ex.: the File argument does not represent a file) returns + * null and logs the cause. * - * @param file - * a File object representing a file. + * @param file a File object representing a file. * @return a String with the contents of the file. */ public static String read(File file) { @@ -366,7 +345,8 @@ public static String read(InputStream inputStream) { StringBuilder stringBuilder = new StringBuilder(); // Try to read the contents of the input stream into the StringBuilder - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 + // Using 'finally' style 2 as described in + // http://www.javapractices.com/topic/TopicAction.do?Id=25 try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, SpecsIo.DEFAULT_CHAR_SET))) { @@ -394,17 +374,15 @@ public static String read(InputStream inputStream) { } /** - * Given a File object and a String, writes the contents of the String in the file, overwriting everything that was - * previously in that file. + * Given a File object and a String, writes the contents of the String in the + * file, overwriting everything that was previously in that file. * *

- * If successful, returns true. If an error occurs (ex.: the File argument does not represent a file) returns false, - * logs the cause and nothing is written. + * If successful, returns true. If an error occurs (ex.: the File argument does + * not represent a file) returns false, logs the cause and nothing is written. * - * @param file - * a File object representing a file. - * @param contents - * a String with the content to write + * @param file a File object representing a file. + * @param contents a String with the content to write * @return true if write is successful. False otherwise. */ public static boolean write(File file, String contents) { @@ -424,17 +402,15 @@ public static boolean write(File file, String contents) { } /** - * Given a File object and a String, writes the contents of the String at the end of the file. If successful, - * returns true. + * Given a File object and a String, writes the contents of the String at the + * end of the file. If successful, returns true. * *

- * If an error occurs (ex.: the File argument does not represent a file) returns false, logs the cause and nothing - * is written. + * If an error occurs (ex.: the File argument does not represent a file) returns + * false, logs the cause and nothing is written. * - * @param file - * a File object representing a file. - * @param contents - * a String with the content to write + * @param file a File object representing a file. + * @param contents a String with the content to write * @return true if write is successful. False otherwise. */ public static boolean append(File file, String contents) { @@ -442,7 +418,6 @@ public static boolean append(File file, String contents) { // the program when used to create the File object. if (file == null) { SpecsLogs.warn("Input 'file' is null."); - // Logger.getLogger(IoUtils.class.getName()).warning("Input 'file' is null."); return false; } @@ -458,7 +433,8 @@ public static boolean append(File file, String contents) { * Method shared among write and append. * *

- * Using 'finally' style 2 as described in Java + * Using 'finally' style 2 as described in + * Java * Practices: Finally and Catch. * * @param file @@ -490,11 +466,6 @@ private static boolean writeAppendHelper(File file, String contents, boolean app return false; } - // Adapt contents to system newline - // if (!contents.contains("\r")) { - // contents = contents.replace("\n", System.getProperty("line.separator")); - // } - writer.write(contents, 0, contents.length()); // Inform about the operation @@ -512,11 +483,7 @@ private static boolean writeAppendHelper(File file, String contents, boolean app } catch (IOException ex) { SpecsLogs.warn("Problems when accessing file '" + file.getPath() + "'. Check if folder exists before writing the file.", ex); - // SpecsLogs.warn(ex); - // SpecsLogs.msgInfo("Problems when accessing file '" + file.getPath() - // + "'. Check if folder exists before writing the file."); isSuccess = false; - } return isSuccess; @@ -531,10 +498,8 @@ private static boolean writeAppendHelper(File file, String contents, boolean app * separator: '.'
* result: 'readme' * - * @param filename - * a string - * @param separator - * the extension separator + * @param filename a string + * @param separator the extension separator * @return the name of the file without the extension and the separator */ public static String removeExtension(String filename, String separator) { @@ -556,8 +521,7 @@ public static String removeExtension(String filename, String separator) { * filename: 'readme.txt'
* result: 'readme' * - * @param filename - * a string + * @param filename a string * @return the name of the file without the extension and the separator */ public static String removeExtension(String filename) { @@ -577,17 +541,13 @@ public static String removeExtension(File file) { /** * Note: by default follows symlinks. * - * @param path - * a File representing a folder or a file. - * - * @param extensions - * a set of strings + * @param path a File representing a folder or a file. + * @param extensions a set of strings * - * @return all the files inside the given folder, excluding other folders, that have a certain extension as - * determined by the set. + * @return all the files inside the given folder, excluding other folders, that + * have a certain extension as determined by the set. */ public static List getFilesRecursive(File path, Collection extensions) { - return getFilesRecursive(path, extensions, true); } @@ -596,20 +556,13 @@ public static List getFilesRecursive(File folder, Collection exten } /** - * @param folder - * a File representing a folder or a file. - * - * @param extensions - * a set of strings - * - * @param followSymlinks - * whether to follow symlinks + * @param folder a File representing a folder or a file. + * @param extensions a set of strings + * @param followSymlinks whether to follow symlinks + * @param cutoffFolders a predicate to determine if a folder should be cut off * - * @param cutoffFolders - * - * - * @return all the files inside the given folder, excluding other folders, that have a certain extension as - * determined by the set. + * @return all the files inside the given folder, excluding other folders, that + * have a certain extension as determined by the set. */ public static List getFilesRecursive(File path, Collection extensions, boolean followSymlinks, Predicate cutoffFolders) { @@ -627,17 +580,6 @@ public static List getFilesRecursive(File path, Collection extensi private static void getFilesRecursivePrivate(File path, Collection extensions, boolean followSymlinks, Predicate cutoffFolders, List foundFiles) { - - // List fileList = new ArrayList<>(); - // - // for (String extension : extensions) { - // List files = getFilesRecursive(folder, extension, followSymlinks); - // fileList.addAll(files); - // } - // - // return fileList; - - // if (!path.isDirectory()) { if (!path.exists()) { SpecsLogs.debug(() -> "Path '" + path + "' does not exist."); return; @@ -660,11 +602,6 @@ private static void getFilesRecursivePrivate(File path, Collection exten foundFiles.add(path); return; - // if (SpecsIo.getExtension(path).equals(extension)) { - // return Arrays.asList(path); - // } - // - // return Collections.emptyList(); } if (!path.isDirectory()) { @@ -686,243 +623,50 @@ private static void getFilesRecursivePrivate(File path, Collection exten children = new File[0]; SpecsLogs.debug("Could not list files of path '" + path.getAbsolutePath() + "'"); } - // File[] childrenChecked = children != null ? children : new File[0]; + for (File child : children) { getFilesRecursivePrivate(child, extensions, followSymlinks, cutoffFolders, foundFiles); } - - /* - this.extension = extension; - this.separator = SpecsIo.DEFAULT_EXTENSION_SEPARATOR; - this.followSymlinks = followSymlinks; - } - - @Override - public boolean accept(File dir, String name) { - - String suffix = separator + extension.toLowerCase(); - - if (!followSymlinks) { - - File f = new File(dir, name); - - // Fail if this is a symlink. - if (Files.isSymbolicLink(f.toPath())) { - return false; - } - } - - return name.toLowerCase().endsWith(suffix); - */ - /* - // Process files inside folder - for (File file : path.listFiles()) { - - - - // Process folder - if (file.isDirectory()) { - // If it should be cut-off, stop processing of this folder - if (cutoffFolders.test(file)) { - continue; - } - - // Recursively add files of folder - getFilesRecursivePrivate(file, extensions, followSymlinks, cutoffFolders, foundFiles); - continue; - } - - // - // if (!followSymlinks) { - // - // File f = new File(dir, name); - // - // // Fail if this is a symlink. - // if (Files.isSymbolicLink(f.toPath())) { - // return false; - // } - // } - // - // return name.toLowerCase().endsWith(suffix); - - String extension = SpecsIo.getExtension(file).toLowerCase(); - - if(extensions.contains(o)) - - // Add files that pass the extension and symlink rules - // String suffix = SpecsIo.DEFAULT_EXTENSION_SEPARATOR + extension.toLowerCase(); - } - */ - /* - List fileList = new ArrayList<>(); - - ExtensionFilter filter = new ExtensionFilter(extension, followSymlinks); - File[] files = path.listFiles(filter); - - fileList.addAll(Arrays.asList(files)); - - // directories - files = path.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - - // Ignore directory if is symlink - if (!followSymlinks && Files.isSymbolicLink(file.toPath())) { - continue; - } - - fileList.addAll(getFilesRecursive(file, extension)); - } - } - - return fileList; - */ } /** * Note: by default follows symlinks. * - * @param folder - * a File representing a folder or a file. - * @param extension - * a string - * @return all the files inside the given folder, excluding other folders, that have a certain extension. + * @param folder a File representing a folder or a file. + * @param extension a string + * @return all the files inside the given folder, excluding other folders, that + * have a certain extension. */ public static List getFilesRecursive(File folder, String extension) { return getFilesRecursive(folder, Arrays.asList(extension), true, path -> false); - // return getFilesRecursive(folder, extension, true); - } - - /** - * @param path - * a File representing a folder or a file. - * - * @param extension - * a string - * - * @param followSymlinks - * whether to follow symlinks - * - * @return all the files inside the given folder, excluding other folders, that have a certain extension. - */ - /* - public static List getFilesRecursive(File path, String extension, boolean followSymlinks) { - - // if (!path.isDirectory()) { - if (!path.exists()) { - SpecsLogs.warn("Path '" + path + "' does not exist."); - return null; - } - - if (path.isFile()) { - if (SpecsIo.getExtension(path).equals(extension)) { - return Arrays.asList(path); - } - - return Collections.emptyList(); - } - - List fileList = new ArrayList<>(); - - ExtensionFilter filter = new ExtensionFilter(extension, followSymlinks); - File[] files = path.listFiles(filter); - - fileList.addAll(Arrays.asList(files)); - - // directories - files = path.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - - // Ignore directory if is symlink - if (!followSymlinks && Files.isSymbolicLink(file.toPath())) { - continue; - } - - fileList.addAll(getFilesRecursive(file, extension)); - } - } - - return fileList; } - */ - /** * Note: by default this follows symlinks. * * @param path - * a File representing a path. + * a File representing a path. * * @return all the files inside the given folder, excluding other folders. */ public static List getFilesRecursive(File path) { - // return getFilesRecursive(path, Collections.emptySet(), true, folder -> false); + // return getFilesRecursive(path, Collections.emptySet(), true, folder -> + // false); return getFilesRecursive(path, true); } /** - * - * - * @param path - * a File representing a path. - * - * @param followSymlinks - * whether to follow symlinks (both files and directories) + * @param path a File representing a path. + * @param followSymlinks whether to follow symlinks (both files and directories) * * @return all the files inside the given path, excluding other folders. */ public static List getFilesRecursive(File path, boolean followSymlinks) { return getFilesRecursive(path, Collections.emptySet(), followSymlinks, folder -> false); } - /* - public static List getFilesRecursive(File path, boolean followSymlinks) { - - // Special case: path is a single file - if (path.isFile()) { - return Arrays.asList(path); - } - - List fileList = new ArrayList<>(); - File[] files = path.listFiles(); - - if (files == null) { - // Not a folder - return fileList; - } - - for (File file : files) { - - // Ignore file if is symlink - if (!followSymlinks && Files.isSymbolicLink(file.toPath())) { - continue; - } - - if (file.isFile()) { - fileList.add(file); - } - } - - for (File file : files) { - - if (file.isDirectory()) { - - // Ignore directory if is symlink - if (!followSymlinks && Files.isSymbolicLink(file.toPath())) { - continue; - } - - fileList.addAll(getFilesRecursive(file, followSymlinks)); - } - } - - return fileList; - } - */ /** - * @param folder - * a File representing a folder. + * @param folder a File representing a folder. * @return all the folders inside the given folder, excluding other files. */ public static List getFolders(File folder) { @@ -945,8 +689,7 @@ public static List getFolders(File folder) { /** * Do a depth-first listing of all folders inside the given folder. * - * @param folder - * a File representing a folder. + * @param folder a File representing a folder. * @return all the folders inside the given folder, excluding other files. */ public static List getFoldersRecursive(File folder) { @@ -968,10 +711,10 @@ private static void getFoldersRecursiveHelper(File folder, List folderList } /** - * @param path - * a File representing an existing path. - * @return if path is a folder, returns all the files inside the given folder, excluding other folders. Otherwise, - * returns a list with the given path + * @param path a File representing an existing path. + * @return if path is a folder, returns all the files inside the given folder, + * excluding other folders. Otherwise, returns a list with the given + * path */ public static SpecsList getFiles(File path) { return SpecsList.convert(getFilesPrivate(path)); @@ -1023,7 +766,6 @@ public static List getFilesWithExtension(List files, Collection copyFolder(File source, File destination, boolean verbo * @param overwrite */ public static List copyFolder(File source, File destination, boolean verbose, boolean overwrite) { - // public static void copyFolder(File source, File destination, boolean verbose, boolean overwrite) { if (!source.isDirectory()) { throw new RuntimeException("Source '" + source + "' is not a folder"); } @@ -1094,8 +835,9 @@ public static boolean copy(File source, File destination) { * Copies the specified file to the specified location. * *

- * If the destination is an existing folder, copies the file to a file of the same name on that folder (method - * 'safeFolder' can be used to create the destination folder, before passing it to the function). + * If the destination is an existing folder, copies the file to a file of the + * same name on that folder (method 'safeFolder' can be used to create the + * destination folder, before passing it to the function). * *

* If verbose is true, warns when overwriting files. @@ -1123,7 +865,8 @@ public static boolean copy(File source, File destination, boolean verbose) { SpecsLogs.msgInfo("Copy: overwriting file '" + destination + "'."); } - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 + // Using 'finally' style 2 as described in + // http://www.javapractices.com/topic/TopicAction.do?Id=25 boolean success = true; try (InputStream in = new FileInputStream(source)) { @@ -1152,9 +895,6 @@ public static boolean copy(File source, File destination, boolean verbose) { * @throws IOException */ public static boolean copy(InputStream source, File destination) { - // Preconditions.checkArgument(source != null); - // Preconditions.checkArgument(destination != null); - boolean success = true; File f2 = destination; @@ -1172,24 +912,6 @@ public static boolean copy(InputStream source, File destination) { SpecsLogs.warn("IoException while copying stream to file '" + destination + "'", e); success = false; } - /* - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 - try (OutputStream out = new FileOutputStream(f2); InputStream in = source) { - - // For Overwrite the file. - - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - SpecsLogs.debug(() -> "Copied stream to file '" + destination.getAbsolutePath() + "'."); - - } catch (IOException e) { - SpecsLogs.warn("IoException while copying stream to file '" + destination + "'", e); - success = false; - } - */ return success; } @@ -1197,7 +919,8 @@ public static boolean copy(InputStream source, File destination) { * Helper method which enables recursion by default. * * @param folder - * @return true in case the operation was successful (could delete all files, or the folder does not exit) + * @return true in case the operation was successful (could delete all files, or + * the folder does not exit) */ public static boolean deleteFolderContents(File folder) { return deleteFolderContents(folder, true); @@ -1247,7 +970,8 @@ public static String getResource(ResourceProvider resource) { } /** - * Given the name of a resource, returns a String with the contents of the resource. + * Given the name of a resource, returns a String with the contents of the + * resource. * * @param resourceName * @return @@ -1332,15 +1056,6 @@ public static boolean extractZip(File zipFile, File folder) { } - // public static boolean extractZip(File filename, File folder) { - // try (InputStream stream = new FileInputStream(filename)) { - // return extractZipResource(stream, folder); - // } catch (IOException e) { - // throw new RuntimeException("Could not unzip file '" + filename + "'", e); - // } - // - // } - public static boolean extractZipResource(InputStream resource, File folder) { boolean success = true; if (!folder.isDirectory()) { @@ -1348,8 +1063,8 @@ public static boolean extractZipResource(InputStream resource, File folder) { return false; } - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 - // try (ZipInputStream zis = new ZipInputStream(IoUtils.class.getResourceAsStream(resource))) { + // Using 'finally' style 2 as described in + // http://www.javapractices.com/topic/TopicAction.do?Id=25 try (ZipInputStream zis = new ZipInputStream(resource)) { ZipEntry entry; @@ -1363,9 +1078,6 @@ public static boolean extractZipResource(InputStream resource, File folder) { File outFile = new File(folder, entry.getName()); - // Make sure complete folder structure exists - // IoUtils.safeFolder(outFile.getParent()); - SpecsLogs.msgInfo("Unzipping '" + outFile.getPath() + "'"); unzipFile(zis, outFile); } @@ -1382,7 +1094,8 @@ public static boolean extractZipResource(InputStream resource, File folder) { * Reads the contents of ZipInputStream at the current position to a File. * *

- * Does not close the stream, so that it can be used again for the remaining zipped files. + * Does not close the stream, so that it can be used again for the remaining + * zipped files. * * @param zis * @param outFile @@ -1507,7 +1220,8 @@ public static byte[] readAsBytes(File file) { } public static byte[] readAsBytes(File file, int numBytes) { - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 + // Using 'finally' style 2 as described in + // http://www.javapractices.com/topic/TopicAction.do?Id=25 try (InputStream inStream = new FileInputStream(file)) { byte[] data = new byte[numBytes]; @@ -1522,7 +1236,8 @@ public static byte[] readAsBytes(File file, int numBytes) { } /** - * When we don't know the size of the input stream, read until the stream is empty. + * When we don't know the size of the input stream, read until the stream is + * empty. * *

* Closes the stream after reading. @@ -1534,7 +1249,8 @@ public static byte[] readAsBytes(InputStream inStream) { List bytes = new ArrayList<>(); - // Using 'finally' style 2 as described in http://www.javapractices.com/topic/TopicAction.do?Id=25 + // Using 'finally' style 2 as described in + // http://www.javapractices.com/topic/TopicAction.do?Id=25 try { try { int aByte = -1; @@ -1556,23 +1272,15 @@ public static byte[] readAsBytes(InputStream inStream) { } catch (FileNotFoundException ex) { SpecsLogs.warn("File not found", ex); } catch (IOException ex) { - SpecsLogs.warn("IoExpection", ex); - } - /* - finally { - try { - inStream.close(); - } catch (IOException ex) { - LoggingUtils.msgWarn("Exception while closing stream.", ex); - } + SpecsLogs.warn("IOException", ex); } - */ return null; } /** - * Copies the given list of resources to the execution path. If the files already exist, the method does nothing. + * Copies the given list of resources to the execution path. If the files + * already exist, the method does nothing. * *

* The method assumes that the resource is bundled within the application JAR. @@ -1606,8 +1314,8 @@ public static File resourceCopy(ResourceProvider resource, File destinationFolde } /** - * Copy the given resource to the destination folder using the full path of the resource. Is destination file - * already exists, does nothing. + * Copy the given resource to the destination folder using the full path of the + * resource. If destination file already exists, does nothing. * * @param resource * @param destinationFolder @@ -1617,7 +1325,8 @@ public static File resourceCopy(String resource, File destinationFolder) { } /** - * Copy the given resource to the destination folder. If destination file already exists, overwrites. + * Copy the given resource to the destination folder. If destination file + * already exists, overwrites. * * @param resource * @param destinationFolder @@ -1643,16 +1352,18 @@ public static ResourceCopyData resourceCopyVersioned(ResourceProvider resource, } /** - * Copies the given resource to the destination folder. If the file already exists, uses ResourceProvider version - * method to determine if the file should be overwritten or not. + * Copies the given resource to the destination folder. If the file already + * exists, uses ResourceProvider version method to determine if the file should + * be overwritten or not. * *

- * If the file already exists but no versioning information is available in the system, the file is overwritten. + * If the file already exists but no versioning information is available in the + * system, the file is overwritten. * *

- * The method will use the package of the class indicated in 'context' as the location to store the information - * about versioning. Keep in mind that calls using the same context will refer to the same local copy of the - * resource. + * The method will use the package of the class indicated in 'context' as the + * location to store the information about versioning. Keep in mind that calls + * using the same context will refer to the same local copy of the resource. * * @param resource * @param destinationFolder @@ -1684,7 +1395,8 @@ public static ResourceCopyData resourceCopyVersioned(ResourceProvider resource, String NOT_FOUND = ""; String version = prefs.get(key, NOT_FOUND); - // If current version is the same as the version of the resource just return the existing file + // If current version is the same as the version of the resource just return the + // existing file if (version.equals(resource.getVersion())) { return new ResourceCopyData(destination, false); } @@ -1768,8 +1480,9 @@ public static boolean resourceCopyWithName(String resource, String resourceFinal } /** - * If baseInput path is "C:\inputpath"; If inputFile is "C:\inputpath\aFolder\inputFile.txt"; If outputFolder is - * "C:\anotherFolder"; + * If baseInput path is "C:\inputpath"; + * If inputFile is "C:\inputpath\aFolder\inputFile.txt"; + * If outputFolder is "C:\anotherFolder"; * * Returns the String "C:\anotherFolder\aFolder\" * @@ -1784,7 +1497,6 @@ public static String getExtendedFoldername(File baseInputPath, File inputFile, F String baseInputFileParent = inputFile.getParentFile().getAbsolutePath(); if (!baseInputFileParent.startsWith(baseInputPathname)) { - // LoggingUtils.getLogger().warning( SpecsLogs.warn("Base parent '" + baseInputFileParent + "' does not start with " + "'" + baseInputPathname + "'"); return null; @@ -1798,8 +1510,9 @@ public static String getExtendedFoldername(File baseInputPath, File inputFile, F } /** - * Convert String to InputStream using ByteArrayInputStream class. This class constructor takes the string byte - * array which can be done by calling the getBytes() method. + * Convert String to InputStream using ByteArrayInputStream class. This class + * constructor takes the string byte array which can be done by calling the + * getBytes() method. * * @param text * @return @@ -1830,35 +1543,17 @@ public static InputStream toInputStream(File file) { /** * Helper method that filters files that have a certain extension. * - * @param fileOrFolder - * a File representing an existing file or folder. - * @param extension - * a string + * @param fileOrFolder a File representing an existing file or folder. + * @param extension a string * @return all the files that have a certain extension */ - // public static List getFiles(File fileOrFolder, String extension) { public static SpecsList getFiles(File fileOrFolder, String extension) { - // ExtensionFilter filter = new ExtensionFilter(extension); String suffix = DEFAULT_EXTENSION_SEPARATOR + extension.toLowerCase(); List fileList = getFiles(fileOrFolder).stream() .filter(currentFile -> currentFile.getName().toLowerCase().endsWith(suffix)) .collect(Collectors.toList()); return SpecsList.convert(fileList); - /* - File[] files = folder.listFiles(new ExtensionFilter(extension)); - if (files == null) { - return Collections.emptyList(); - } - - ArrayList returnValue = new ArrayList<>(); - - for (File file : files) { - returnValue.add(file); - } - - return returnValue; - */ } /** @@ -1892,12 +1587,6 @@ public static List getPathsWithPattern(File folder, String pattern, boolea } public static List getPathsWithPattern(File folder, String pattern, boolean recursive, PathFilter filter) { - - // If recursion disabled, use simple version of the function - // if (!recursive) { - // return getFilesWithPattern(folder, pattern); - // } - List files = new ArrayList<>(); // Treat recursion separately @@ -1914,58 +1603,14 @@ public static List getPathsWithPattern(File folder, String pattern, boolea if (filter.isAllowed(currentPatternPath)) { files.add(currentPatternPath); } - - /* - if (currentPatternPath.isDirectory()) { - if (filter.isAllowed(currentPatternPath)) { - files.add(currentPatternPath); - } - - continue; - } - - if (currentPatternPath.isFile()) { - if (filter.isAllowed(currentPatternPath)) { - files.add(currentPatternPath); - } - - continue; - } - - SpecsLogs.warn("Could not hand path, is neither a file or a folder: " + currentPatternPath); - */ } return files; } /** - * Returns true if the folder contains at least one file having the extension "extension". - * - * @param folder - * The folder to find the extension from. - * @param extension - * The extension to find in the folder. - * - * @return true if the folder contains at least one file having the extension "extension". - */ - /* - public static boolean contains(File folder, String extension) { - if (!folder.isDirectory()) { - throw new IllegalArgumentException("The file given in parameter is not a folder"); - } - - File[] files = folder.listFiles(new ExtensionFilter(extension)); - - if (files == null || files.length == 0) { - return false; - } - return true; - } - */ - - /** - * Returns the relative path of the file given in parameter, relative to the working folder. + * Returns the relative path of the file given in parameter, relative to the + * working folder. * * @param file * @return @@ -1981,10 +1626,10 @@ public static String getRelativePath(File file) { * The output path is normalized to use the '/' as path separator. * *

- * If the file does not share a common ancestor with baseFile, returns the absolute path to file. + * If the file does not share a common ancestor with baseFile, returns the + * absolute path to file. * - * @param file - * The file the user needs the relative path of. + * @param file The file the user needs the relative path of. * * @return the relative path of the file given in parameter. */ @@ -1996,8 +1641,8 @@ public static String getRelativePath(File file, File baseFile) { * * @param file * @param baseFile - * @param strict - * if true, returns empty Optional if the file is not a sub-path of baseFile. + * @param strict if true, returns empty Optional if the file is not a sub-path + * of baseFile. * @return */ public static Optional getRelativePath(File file, File baseFile, boolean isStrict) { @@ -2020,7 +1665,8 @@ public static Optional getRelativePath(File file, File baseFile, boolean // Finds the current folder path String mainFolder = null; try { - // Get absolute path first, to resolve paths such as Windows Desktop, then get canonical + // Get absolute path first, to resolve paths such as Windows Desktop, then get + // canonical mainFolder = baseFile.getAbsoluteFile().getCanonicalPath(); File absoluteFile = file.getAbsoluteFile(); file = absoluteFile.getCanonicalFile(); @@ -2141,18 +1787,7 @@ private static void getParentNamesReverse(File file, List names) { * @return */ public static String getExtension(File file) { - // String separator = DEFAULT_SEPARATOR; - String filename = file.getName(); - - return getExtension(filename); - /* - int extIndex = filename.lastIndexOf(separator); - if (extIndex < 0) { - return ""; - } - - return filename.substring(extIndex + 1, filename.length()); - */ + return getExtension(file.getName()); } /** @@ -2186,15 +1821,6 @@ public static String getExtension(String fileName) { */ public static File existingFolder(String folderpath) { return existingFolder(null, folderpath); - /* - File folder = existingFolder(null, folderpath); - - if (folder == null) { - throw new RuntimeException("Folder '" + folderpath + "' not found"); - } - - return folder; - */ } public static File existingFolder(File parentFolder, String foldername) { @@ -2202,8 +1828,6 @@ public static File existingFolder(File parentFolder, String foldername) { if (!folder.isDirectory()) { throw new RuntimeException("Could not open folder '" + folder.getPath() + "'"); - // LoggingUtils.msgWarn("Could not open folder '" + folder.getPath() + "'"); - // return null; } return folder; @@ -2216,41 +1840,8 @@ public static File existingFile(File parent, String filePath) { } /** - * From the given paths, returns a list of existing files. The paths can represent single files or folders. - * - *

- * If a folder is given, looks recursively inside the folder. - * - * @param paths - * @param extensions - * @return - */ - // public static List existingFiles(List paths, boolean recursive, Collection extensions) { - // List existingPaths = new ArrayList<>(); - // for (String arg : paths) { - // File path = new File(arg); - // if (!path.exists()) { - // SpecsLogs.info("Ignoring path '" + arg + "', it does not exist"); - // continue; - // } - // - // existingPaths.add(path); - // } - // - // List files = new ArrayList<>(); - // for (File existingPath : existingPaths) { - // if (existingPath.isDirectory()) { - // files.addAll(SpecsIo.getFiles(existingPath, recursive, extensions)); - // } else { - // files.add(existingPath); - // } - // } - // - // return files; - // } - - /** - * Returns the canonical path of the given file. If a problem happens, throws an exception. + * Returns the canonical path of the given file. If a problem happens, throws an + * exception. * * @param executable * @return @@ -2259,8 +1850,6 @@ public static String getPath(File file) { try { return file.getCanonicalPath(); - // String path = file.getCanonicalPath(); - // return normalizePath(path); } catch (IOException e) { throw new RuntimeException("Could not get canonical file for " + file.getPath()); } @@ -2280,7 +1869,8 @@ public static File getParent(File file) { return parentFile; } - // Try with canonical path, getParent) might not work when using '\' in Linux platforms + // Try with canonical path, getParent) might not work when using '\' in Linux + // platforms parentFile = SpecsIo.getCanonicalFile(file).getParentFile(); if (parentFile != null) { return parentFile; @@ -2324,27 +1914,17 @@ public static File download(String urlString, File outputFolder) { /** * This function downloads the file specified in the URL. * - * @param url - * The URL of the file to be downloaded. + * @param url The URL of the file to be downloaded. * @return true if the file could be downloaded, false otherwise * @throws IOException */ public static File download(URL url, File outputFolder) { URLConnection con; - // UID uid = new UID(); try { con = url.openConnection(); con.connect(); - // String type = con.getContentType(); - // - // if (type == null) { - // LoggingUtils.msgInfo("Could not get the content type of the URL '" + url + "'"); - // return null; - // - // } - // Get filename String path = url.getPath(); String filename = path.substring(path.lastIndexOf('/') + 1, path.length()); @@ -2361,8 +1941,6 @@ public static File download(URL url, File outputFolder) { byte[] buffer = new byte[4 * 1024]; int read; - // String[] split = type.split("/"); - // String filename = Integer.toHexString(uid.hashCode()) + "_" + split[split.length - 1]; // Make sure output folder exists if (!outputFolder.isDirectory()) { outputFolder = SpecsIo.mkdir(outputFolder); @@ -2373,11 +1951,9 @@ public static File download(URL url, File outputFolder) { SpecsLogs.msgInfo("Downloading '" + escapedFilename + "' to '" + outputFolder + "'..."); try (FileOutputStream os = new FileOutputStream(outputFile); InputStream in = con.getInputStream()) { - while ((read = in.read(buffer)) > 0) { os.write(buffer, 0, read); } - } return outputFile; @@ -2389,7 +1965,6 @@ public static File download(URL url, File outputFolder) { SpecsLogs.msgInfo("IOException while reading URL '" + urlString + "':\n - " + e.getMessage()); return null; } - } /** @@ -2413,8 +1988,8 @@ public static String escapeFilename(String filename) { } /** - * Helper method which creates a temporary file in the system temporary folder with extension 'txt'. - * + * Helper method which creates a temporary file in the system temporary folder + * with extension 'txt'. * * @return */ @@ -2423,7 +1998,8 @@ public static File getTempFile() { } /** - * Creates a file with a random name in a temporary folder. This file will be deleted when the JVM exits. + * Creates a file with a random name in a temporary folder. This file will be + * deleted when the JVM exits. * * @param folderName * @return @@ -2441,7 +2017,8 @@ public static File getTempFile(String folderName, String extension) { } /** - * A randomly named folder in the OS temporary folder that is deleted when the virtual machine exits. + * A randomly named folder in the OS temporary folder that is deleted when the + * virtual machine exits. * * @return */ @@ -2458,7 +2035,8 @@ public static File newRandomFolder() { } /** - * Code taken from http://www.kodejava.org/how-do-i-get-operating-system-temporary-directory-folder/ + * Code taken from + * http://www.kodejava.org/how-do-i-get-operating-system-temporary-directory-folder/ * * @return */ @@ -2478,9 +2056,10 @@ public static File getTempFolder(String folderName) { // This can be problematic in regard to read/write permissions // Suffix the name of the user to make the temporary folder unique to the user /** - * FIXME: this is not a good idea, as it can lead to problems when running multiple instances of the same program. + * FIXME: this is not a good idea, as it can lead to problems when running + * multiple instances of the same program. * at the same time, as the temporary folder will be shared by all instances. - * A better solution would be to append a UUID to the folder name. + * A better solution would be to append a UUID to the folder name. */ if (SpecsSystem.isLinux()) { String userName = System.getProperty("user.name"); @@ -2497,14 +2076,14 @@ public static File getTempFolder(String folderName) { } /** - * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. + * List directory contents for a resource folder. Not recursive. This is + * basically a brute-force implementation. * Works for regular files and also JARs. * * @author Greg Briggs - * @param aClass - * Any java class that lives in the same place as the resources you want. - * @param path - * Should end with "/", but not start with one. + * @param aClass Any java class that lives in the same place as the resources + * you want. + * @param path Should end with "/", but not start with one. * @return Just the name of each member item, not the full paths. * @throws URISyntaxException * @throws IOException @@ -2555,14 +2134,15 @@ String[] getResourceListing(Class aClass, String path) throws URISyntaxExcept } /** - * Returns a File object pointing to the given file path. If the returned object is different than null, the file - * exists. + * Returns a File object pointing to the given file path. If the returned object + * is different than null, the file exists. * *

- * The method tries to build a File object using the following order of approaches:
+ * The method tries to build a File object using the following order of + * approaches:
* - If the given file path is absolute, uses only that information;
- * - If the given parent folder is different than null, uses it as base folder. Otherwise, uses the path alone, - * relative to the current working folder; + * - If the given parent folder is different than null, uses it as base folder. + * Otherwise, uses the path alone, relative to the current working folder; * * @param parentFolder * @param filepath @@ -2636,7 +2216,7 @@ public static Optional parseUrl(String urlString) { if (urlString == null) { return Optional.empty(); } - + try { return Optional.of(new URI(urlString).toURL()); } catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) { @@ -2663,22 +2243,12 @@ public static String getUrl(String urlString) { return null; } - /* - public static String getCanonicalPath(File file) { - try { - return file.getCanonicalPath(); - } catch (IOException e) { - throw new RuntimeException("Could not get canonical path for " + file.getPath()); - } - } - */ - /** * Returns the canonical file. * *

- * Calls getAbsoluteFile(), to avoid problems when using paths such as 'Desktop' in Windows, and then transforms to - * a canonical path. + * Calls getAbsoluteFile(), to avoid problems when using paths such as 'Desktop' + * in Windows, and then transforms to a canonical path. * *

* Throws a RuntimeException if it could not obtain the canonical file. @@ -2690,16 +2260,8 @@ public static File getCanonicalFile(File file) { try { return new File(file.getAbsolutePath().trim()).getCanonicalFile(); - - /* - file = file.getAbsoluteFile().getCanonicalFile(); - - // return new File(file.getAbsolutePath().replace('\\', '/')); - return new File(normalizePath(file.getAbsolutePath())); - */ } catch (IOException e) { SpecsLogs.msgInfo("Could not get canonical file for " + file.getPath() + ", returning absolute file"); - // return new File(normalizePath(file.getAbsolutePath())); return file.getAbsoluteFile(); } } @@ -2708,8 +2270,8 @@ public static File getCanonicalFile(File file) { * Converts all '\' to '/' * *

- * This method should only be used when manipulating Files as strings. Otherwise, File objects always revert to the - * system's preferred separator. + * This method should only be used when manipulating Files as strings. + * Otherwise, File objects always revert to the system's preferred separator. * * @param path * @return @@ -2722,11 +2284,6 @@ public static String normalizePath(File path) { return normalizePath(path.getPath()); } - // - // public static CharSequence getNewline() { - // return System.getProperty("line.separator"); - // } - public static char getFolderSeparator() { return SpecsIo.DEFAULT_FOLDER_SEPARATOR; } @@ -2747,7 +2304,6 @@ public static boolean delete(File file) { * @return */ public static String getCanonicalPath(File file) { - // return normalizePath(getCanonicalFile(file).getPath()); return getCanonicalFile(file).getPath(); } @@ -2755,10 +2311,8 @@ public static Optional getJarPath(Class aClass) { String jarfilePath = null; try { - jarfilePath = aClass.getProtectionDomain().getCodeSource().getLocation().toURI() .getPath(); - } catch (URISyntaxException e) { SpecsLogs.msgLib("Problems decoding URI of jarpath\n" + e.getMessage()); return Optional.empty(); @@ -2778,14 +2332,12 @@ public static Optional getJarPath(Class aClass) { } return Optional.of(jarLocFile); - } /** * Deletes the given folder and all its contents. * - * @param folder - * folder to delete + * @param folder folder to delete * @return true if both the folder and its contents could be deleted */ public static boolean deleteFolder(File folder) { @@ -2819,7 +2371,8 @@ public static Map getFileMap(List sources, Set exten } /** - * Maps the canonical path of each file found in the sources folders to its corresponding source folder. + * Maps the canonical path of each file found in the sources folders to its + * corresponding source folder. * * @param sources * @param recursive @@ -2835,8 +2388,8 @@ public static Map getFileMap(List sources, boolean recursive * @param sources * @param recursive * @param extensions - * @param cutoffFolders - * accepts a folder, if returns true, that folder and its sub-folders will be ignored from the search + * @param cutoffFolders accepts a folder, if returns true, that folder and its + * sub-folders will be ignored from the search * @return */ public static Map getFileMap(List sources, boolean recursive, Set extensions, @@ -2847,8 +2400,6 @@ public static Map getFileMap(List sources, boolean recursive for (File source : sources) { // Convert source to absolute path File canonicalSource = SpecsIo.getCanonicalFile(source); - // List filenames = getFiles(Arrays.asList(source), extensions); - // filenames.stream().forEach(filename -> fileMap.put(filename, source)); getFiles(Arrays.asList(canonicalSource), recursive, extensions, cutoffFolders).stream() .forEach(file -> fileMap.put(SpecsIo.getCanonicalPath(file), canonicalSource)); } @@ -2862,27 +2413,13 @@ public static SpecsList getFiles(List sources, boolean recursive, Co public static SpecsList getFiles(List sources, boolean recursive, Collection extensions, Predicate cutoffFolders) { - - // Function> flatMapper = recursive - // ? path -> SpecsIo.getFilesRecursive(path).stream() - // : path -> SpecsIo.getFiles(path).stream(); - List sourceFiles = sources.stream() - // .flatMap(flatMapper) .flatMap(path -> fileMapper(path, recursive, extensions, cutoffFolders)) - // .map(file -> file.getAbsolutePath()) .filter(file -> extensions.contains(SpecsIo.getExtension(file))) .collect(Collectors.toList()); - // System.out.println( - // "All Sources:" + sourceFiles.stream().map(Object::toString).collect(Collectors.joining(", "))); - // - // Sort files to keep order across platforms Collections.sort(sourceFiles); - // - // System.out.println( - // "All Sources after:" + sourceFiles.stream().map(Object::toString).collect(Collectors.joining(", "))); return SpecsList.convert(sourceFiles); } @@ -2894,11 +2431,6 @@ private static Stream fileMapper(File path, boolean recursive, Collection< return Stream.empty(); } - // // Check if it is a folder that should be ignored - // if (source.isDirectory() && cutoffFolders.test(source)) { - // continue; - // } - return recursive ? SpecsIo.getFilesRecursive(path, extensions, true, cutoffFolders).stream() : SpecsIo.getFiles(path).stream(); } @@ -2924,7 +2456,8 @@ public static void copyFolderContents(File sourceFolder, File destinationFolder, } /** - * Compresses the entries into the given zipFile. Uses basePath to calculate the root of entries in the zip. + * Compresses the entries into the given zipFile. Uses basePath to calculate the + * root of entries in the zip. * * @param entries * @param basePath @@ -3004,7 +2537,8 @@ public static boolean isEmptyFolder(File folder) { } /** - * Based on https://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java + * Based on + * https://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java * * @param file * @return @@ -3031,18 +2565,14 @@ public static String getMd5(InputStream is) { throw new RuntimeException("Could not find MD5 algorithm", e); } - // InputStream is = Files.newInputStream(Paths.get(file.getAbsolutePath())); try ( BufferedInputStream bis = new BufferedInputStream(is); DigestInputStream dis = new DigestInputStream(bis, md)) { - while (dis.read() != -1) { - } /* Read decorated stream (dis) to EOF as normal... */ } catch (IOException e) { throw new RuntimeException("Could not calculate MD5", e); - // throw new RuntimeException("Problems while using file '" + file + "'", e); } byte[] digest = md.digest(); @@ -3143,10 +2673,6 @@ public static int read() { } } - // public static String getPathSeparator() { - // return File.pathSeparator; - // } - /** * * @param file @@ -3270,14 +2796,12 @@ public static int getDepth(File file) { } /** - * - * @return the first folder in java.library.path that is writable. Throws exception if no folder that can be written - * is found + * @return the first folder in java.library.path that is writable. Throws + * exception if no folder that can be written is found */ public static File getFirstLibraryFolder() { var libraryFolders = getLibraryFolders(); for (var libraryFolder : libraryFolders) { - // if (libraryFolder.canWrite() && libraryFolder.canRead()) { if (SpecsIo.canWrite(libraryFolder)) { return libraryFolder; } @@ -3309,7 +2833,6 @@ public static boolean canWrite(File folder) { } catch (Exception e) { return false; } - } /** @@ -3337,5 +2860,4 @@ public static String cleanUrl(String urlString) { return url.getProtocol() + "://" + url.getHost() + url.getPath(); } - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsLogs.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsLogs.java index 59c6014c..eefb7c50 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsLogs.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsLogs.java @@ -45,25 +45,10 @@ public class SpecsLogs { private final static ThreadLocal> SPECS_LOGGER = ThreadLocal .withInitial(() -> EnumLogger.newInstance(SpecsLoggerTag.class).addToIgnoreList(SpecsLogs.class)); - // private final static String NEWLINE = System.getProperty("line.separator"); - private final static String SYSTEM_OUT_LOGGER = "System.out"; private final static String SYSTEM_ERR_LOGGER = "System.err"; - // private final static String SEVERE_TAG = "App-Severe"; - // private final static String WARNING_TAG = "App-Warn"; public final static String INFO_TAG = "App-Info"; - // private final static String LIB_TAG = "App-Lib"; - - // private final static String LOGGING_TAG = "CurrentApp"; - // public final static String LOGGING_ANDROID_TAG = "currentApp"; - // private final static String LIB_LOGGING_TAG = "[LIB]"; - // Preserving a reference to original stdout/stderr streams, - // in case they change. - // private final static PrintStream stdout = System.out; - // private final static PrintStream stderr = System.err; - - // private static boolean printStackTrace = true; /** * Helper method to get the root Logger. @@ -81,57 +66,15 @@ public static Logger getRootLogger() { */ public static Logger getLogger() { return SPECS_LOGGER.get().getLogger(null); - // return Logger.getLogger(SpecsLogs.LOGGING_TAG); } public static EnumLogger getSpecsLogger() { return SPECS_LOGGER.get(); - // return Logger.getLogger(SpecsLogs.LOGGING_TAG); } /** - * Helper method to automatically get the Logger correspondent to the class which calls this method. - * - *

- * Thes method uses the "heavy" StackTrace to determine what object called it. This should only be used for logging - * "warnings" which are not called often, or in situation such as constructors, were we do not want to leak the - * object reference before it exists. - * - * @param object - * @return logger specific to the given object - */ - - /* - public static Logger getLoggerDebug() { - // StackTraceElement stackElement = ProcessUtils.getCallerMethod(); - // If called directly, use index 4 - return getLoggerDebug(5); - // StackTraceElement stackElement = ProcessUtils.getCallerMethod(4); - // return Logger.getLogger(stackElement.getClassName()); - } - */ - - /** - * Helper method to automatically get the Logger correspondent to the class which calls this method. - * - *

- * Thes method uses the "heavy" StackTrace to determine what object called it. This should only be used for logging - * "warnings" which are not called often, or in situation such as constructors, were we do not want to leak the - * object reference before it exists. - * - * @param callerMethodIndex - * the index indicating the depth of method calling. This method introduces 3 calls (index 0-2), index 3 - * is this method, index 4 is the caller index - * @return logger specific to the given object - */ - /* - public static Logger getLoggerDebug(int callerMethodIndex) { - final StackTraceElement stackElement = SpecsSystem.getCallerMethod(callerMethodIndex); - return Logger.getLogger(stackElement.toString()); - } - */ - /** - * Redirects the System.out stream to the logger with name defined by LOGGING_TAG. + * Redirects the System.out stream to the logger with name defined by + * LOGGING_TAG. * *

* Anything written to System.out is recorded as a log at info level. @@ -151,7 +94,8 @@ public static void redirectSystemOut() { } /** - * Redirects the System.err stream to the logger with name defined by LOGGING_TAG. + * Redirects the System.err stream to the logger with name defined by + * LOGGING_TAG. * *

* Anything written to System.err is recorded as a log at warning level. @@ -174,7 +118,7 @@ public static void redirectSystemErr() { * Removes current handlers and adds the given Handlers to the root logger. * * @param handlers - * the Handlers we want to set as the root Handlers. + * the Handlers we want to set as the root Handlers. */ public static void setRootHandlers(Handler[] handlers) { final Logger logger = getRootLogger(); @@ -220,17 +164,12 @@ public static void removeHandler(Handler handler) { setRootHandlers(handlerList.toArray(new Handler[handlerList.size()])); } - public static void setHandlers(List handlers) { - - } - /** * Removes current handlers and adds the given Handlers to the root logger. * * @param handlers - * the Handlers we want to set as the root Handlers. + * the Handlers we want to set as the root Handlers. */ - // public static void addHandler(Handler handler) { public static void addHandlers(List handlers) { // Get all handlers final Logger logger = getRootLogger(); @@ -252,38 +191,6 @@ public static void addHandlers(List handlers) { setRootHandlers(newHandlers); } - /** - * builds a Console Handler which uses as formatter, ConsoleFormatter. - * - * @return a Console Handler formatted by ConsoleFormatter. - */ - /* - public static Handler buildConsoleHandler() { - - StreamHandler cHandler = CustomConsoleHandler.newStderr(); - //ConsoleHandler cHandler = new ConsoleHandler(); - cHandler.setFormatter(new ConsoleFormatter()); - - /* - cHandler.setFilter(new Filter() { - - @Override - public boolean isLoggable(LogRecord record) { - if(record.getLevel().intValue() > 700) { - return false; - } - - return true; - } - }); - */ - /* - cHandler.setLevel(Level.ALL); - - return cHandler; - } - */ - /** * builds a Console Handler which uses as formatter, ConsoleFormatter. * @@ -341,17 +248,14 @@ public static Handler buildErrorLogHandler(String logFilename) { try { fileHandler = new FileHandler(logFilename, false); } catch (final SecurityException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } if (fileHandler == null) { return null; } - // StreamHandler cHandler = CustomConsoleHandler.newStderr(); fileHandler.setFormatter(new ConsoleFormatter()); fileHandler.setFilter(record -> { @@ -368,7 +272,8 @@ public static Handler buildErrorLogHandler(String logFilename) { } /** - * Automatically setups the root logger for output to the console. Redirects System.out and System.err to the logger + * Automatically setups the root logger for output to the console. Redirects + * System.out and System.err to the logger * as well. */ public static void setupConsoleOnly() { @@ -413,8 +318,9 @@ public static void setLevel(Level level) { * Writes a message to the logger with name defined by LOGGING_TAG. * *

- * Messages written with this method are recorded as a log at warning level. Use this level to show a message for - * cases that are supposed to never happen if the code is well used. + * Messages written with this method are recorded as a log at warning level. Use + * this level to show a message for cases that are supposed to never happen if + * the code is well used. * * @param msg */ @@ -431,36 +337,6 @@ public static void msgWarn(String msg) { warn(msg); } - /* - public static void msgWarn(Logger logger, String msg) { - - final List elements = Arrays.asList(Thread.currentThread().getStackTrace()); - final int startIndex = 2; - - msgWarn(msg, elements, startIndex, true, logger); - } - */ - - /* - private static void msgWarn(String msg, List elements, int startIndex, - boolean appendCallingClass, Logger logger) { - - msg = "[WARNING]: " + msg; - msg = parseMessage(msg); - msg = buildErrorMessage(msg, elements.subList(startIndex, elements.size())); - - if (appendCallingClass) { - logger = logger == null ? getLoggerDebug() : logger; - logger.warning(msg); - // getLoggerDebug().warning(msg); - } else { - logger = logger == null ? getLogger() : logger; - logger.warning(msg); - // getLogger().warning(msg); - } - } - */ - /** * @deprecated use warn() instead * @param msg @@ -483,10 +359,6 @@ public static void warn(String msg, Throwable ourCause) { .getLogCallLocation(Thread.currentThread().getStackTrace()); String catchLocation = !catchLocationTrace.isEmpty() ? SpecsLogging.getSourceCode(catchLocationTrace.get(0)) : ""; - // String msgSource = "\n\nCatch location:" + catchLocation; - // final List currentElements = Arrays.asList(Thread.currentThread().getStackTrace()); - // final StackTraceElement currentElement = currentElements.get(2); - // final String msgSource = "\n\n[Catch]:\n" + currentElement; String causeString = ourCause.getMessage(); if (causeString == null) { @@ -495,58 +367,11 @@ public static void warn(String msg, Throwable ourCause) { causeString = "[" + ourCause.getClass().getSimpleName() + "] " + causeString; - // final String causeMsg = causeString + msgSource; - - // msg = msg + "\nCause: [" + ourCause.getClass().getSimpleName() + "] " + ourCause.getMessage() + msgSource; msg = msg + catchLocation + "\n\nException message: " + causeString; SPECS_LOGGER.get().log(Level.WARNING, null, msg, LogSourceInfo.getLogSourceInfo(Level.WARNING), ourCause.getStackTrace()); - - // final List elements = Arrays.asList(ourCause.getStackTrace()); - // final int startIndex = 0; - // - // msgWarn(msg, elements, startIndex, false, null); - } - - /* - public static void msgWarn(Throwable cause) { - - msgWarn("Exception", cause); - // final List elements = Arrays.asList(cause.getStackTrace()); - // final int startIndex = 0; - // - // final String msg = cause.getClass().getName() + ": " + cause.getMessage(); - // - // msgWarn(msg, elements, startIndex, false, null); - } - */ - - /* - public static String buildErrorMessage(String originalMsg, Collection elements) { - - final StringBuilder builder = new StringBuilder(); - builder.append(originalMsg); - - // Append the stack trace to the msg - if (SpecsLogs.printStackTrace) { - builder.append("\n\nStack Trace:"); - builder.append("\n--------------"); - - for (final StackTraceElement element : elements) { - builder.append("\n"); - builder.append(element); - } - - builder.append("\n--------------"); - builder.append("\n"); - - } - - return builder.toString(); - } - */ /** * Info-level message. @@ -565,40 +390,17 @@ public static void info(String msg) { SPECS_LOGGER.get().info(msg); } - /** - * Info-level message. - * - *

- * Accepting a Logger, since that should be the common case, keeping a reference to a Logger so that it does not get - * garbage collected. - * - * @param logger - * @param msg - */ - // public static void msgInfo(Logger logger, String msg) { - // msg = parseMessage(msg); - // - // // if(globalLevel) {logger.setLevel(globalLevel);} - // logger.info(msg); - // - // } - /** * Lib-level message. * *

- * This is a logging level between INFO and CONFIG, to be used by libraries to log execution information. + * This is a logging level between INFO and CONFIG, to be used by libraries to + * log execution information. * * @param msg */ public static void msgLib(String msg) { SPECS_LOGGER.get().log(LogLevel.LIB, msg); - // msg = parseMessage(msg); - // msgLib does not need support for printing the stack-trace, since it is to be used - // to log information that does not represent programming errors. - // Although it can be used to log user input errors, they are not to be resolved by looking - // at the source code, hence not using support for stack-trace. - // Logger.getLogger(SpecsLogs.LIB_TAG).log(LogLevel.LIB, msg); } /** @@ -611,40 +413,20 @@ public static void msgLib(String msg) { */ public static void msgSevere(String msg) { SPECS_LOGGER.get().log(Level.SEVERE, msg); - // msg = parseMessage(msg); - // - // getLoggerDebug().severe(msg); } - /** - * Adds a newline to the end of the message, if it does not have one. - * - * @param msg - * @return - */ - /* - private static String parseMessage(String msg) { - if (msg.isEmpty()) { - return msg; - } - // return msg; - // return String.format(msg+"%n"); - return msg + SpecsLogs.NEWLINE; - } - */ - /** * Enables/disables printing of the stack trace for Warning level. * *

- * This method is for compatibility with previous code. Please use LogSourceInfo.setLogSourceInfo instead. + * This method is for compatibility with previous code. Please use + * LogSourceInfo.setLogSourceInfo instead. * * @param bool */ public static void setPrintStackTrace(boolean bool) { LogSourceInfo sourceInfo = bool ? LogSourceInfo.STACK_TRACE : LogSourceInfo.NONE; LogSourceInfo.setLogSourceInfo(Level.WARNING, sourceInfo); - // SpecsLogs.printStackTrace = bool; } public static boolean isSystemPrint(String loggerName) { @@ -659,10 +441,8 @@ public static boolean isSystemPrint(String loggerName) { return false; } - // public static void addLogFile(File file) { public static void addLog(PrintStream stream) { // Create file handler - // SimpleFileHandler handler = SimpleFileHandler.newInstance(file); final SimpleFileHandler handler = new SimpleFileHandler(stream); // Set formatter @@ -676,26 +456,18 @@ public static void debug(Supplier string) { // To avoid resolving the string unnecessarily if (SpecsSystem.isDebug()) { SPECS_LOGGER.get().debug(string.get()); - // Prefix - // String message = "[DEBUG] " + string.get(); - // msgInfo(message); - // debug(string.get()); } } /** - * If this is not a pure string literal, should always prefer overload that receives a lambda, to avoid doing the + * If this is not a pure string literal, should always prefer overload that + * receives a lambda, to avoid doing the * string computation when debug is not enabled. * * @param string */ public static void debug(String string) { debug(() -> string); - // if (SpecsSystem.isDebug()) { - // // Prefix - // string = "[DEBUG] " + string; - // msgInfo(string); - // } } /** @@ -707,5 +479,4 @@ public static void untested(String untestedAction) { SpecsLogs.warn( "Untested:" + untestedAction + ". Please contact the developers in order to add this case as a test."); } - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsMath.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsMath.java index 71cdff33..5a75a8b7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsMath.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsMath.java @@ -19,7 +19,8 @@ /** * Utility methods for mathematical operations. *

- * Provides static helper methods for arithmetic, rounding, and other math-related tasks. + * Provides static helper methods for arithmetic, rounding, and other + * math-related tasks. *

* * @author Joao Bispo @@ -37,9 +38,10 @@ public static double zeroRatio(Collection values) { } /** - * Calculates the ratio of values below a given threshold in a collection of numbers. + * Calculates the ratio of values below a given threshold in a collection of + * numbers. * - * @param values the collection of numbers + * @param values the collection of numbers * @param threshold the threshold value * @return the ratio of values below the threshold */ @@ -78,10 +80,12 @@ public static double arithmeticMean(Collection values) { } /** - * Calculates the arithmetic mean of a collection of numbers, excluding zero values. + * Calculates the arithmetic mean of a collection of numbers, excluding zero + * values. * * @param values the collection of numbers - * @return the arithmetic mean excluding zeros, or null if the collection is empty + * @return the arithmetic mean excluding zeros, or null if the collection is + * empty */ public static Double arithmeticMeanWithoutZeros(Collection values) { if (values.isEmpty()) { @@ -113,8 +117,9 @@ public static Double arithmeticMeanWithoutZeros(Collection values) { /** * Calculates the geometric mean of a collection of numbers. * - * @param values the collection of numbers - * @param withoutZeros if false, performs geometric mean with zero correction; otherwise, ignores zero values + * @param values the collection of numbers + * @param withoutZeros if false, performs geometric mean with zero correction; + * otherwise, ignores zero values * @return the geometric mean */ public static double geometricMean(Collection values, boolean withoutZeros) { @@ -145,8 +150,9 @@ public static double geometricMean(Collection values, boolean withoutZer /** * Calculates the harmonic mean of a collection of numbers. * - * @param values the collection of numbers - * @param useZeroCorrection if true, applies zero correction to the harmonic mean calculation + * @param values the collection of numbers + * @param useZeroCorrection if true, applies zero correction to the harmonic + * mean calculation * @return the harmonic mean */ public static double harmonicMean(Collection values, boolean useZeroCorrection) { @@ -178,7 +184,7 @@ public static double harmonicMean(Collection values, boolean useZeroCorr /** * Finds the maximum value in a list of numbers. * - * @param values the list of numbers + * @param values the list of numbers * @param ignoreZeros if true, ignores zero values in the calculation * @return the maximum value, or null if the list is null or empty */ @@ -215,7 +221,7 @@ public static Number max(List values, boolean ignoreZeros) { /** * Finds the minimum value in a list of numbers. * - * @param values the list of numbers + * @param values the list of numbers * @param ignoreZeros if true, ignores zero values in the calculation * @return the minimum value, or null if the list is null or empty */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsNumbers.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsNumbers.java index 36b5bce9..f677af2d 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsNumbers.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsNumbers.java @@ -19,7 +19,8 @@ /** * Utility methods for number operations. *

- * Provides static helper methods for parsing, formatting, and converting numbers. + * Provides static helper methods for parsing, formatting, and converting + * numbers. *

* * @author Joao Bispo @@ -63,7 +64,7 @@ public static Number zero(Class numberClass) { /** * Adds two numbers of the same type. * - * @param the type of the numbers + * @param the type of the numbers * @param number1 the first number * @param number2 the second number * @return the result of adding the two numbers diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsStrings.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsStrings.java index c82b94a1..ee1d54bc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsStrings.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsStrings.java @@ -47,7 +47,8 @@ import pt.up.fe.specs.util.utilities.StringLines; /** - * Utility methods for parsing of values which, instead of throwing an exception, return a default value if a parsing + * Utility methods for parsing of values which, instead of throwing an + * exception, return a default value if a parsing * error occurs. * * @author Joao Bispo @@ -89,11 +90,12 @@ public static boolean isPrintableChar(char c) { private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** - * Tries to parse a String into a integer. If an exception happens, warns the user and returns a 0. + * Tries to parse a String into a integer. If an exception happens, warns the + * user and returns a 0. * - * @param integer - * a String representing an integer. - * @return the intenger represented by the string, or 0 if it couldn't be parsed. + * @param integer a String representing an integer. + * @return the intenger represented by the string, or 0 if it couldn't be + * parsed. */ public static int parseInt(String integer) { int intResult = 0; @@ -101,21 +103,18 @@ public static int parseInt(String integer) { intResult = Integer.parseInt(integer); } catch (NumberFormatException e) { SpecsLogs.warn("Couldn''t parse '" + integer + "' into an integer. Returning " + intResult + "."); - // Logger.getLogger(ParseUtils.class.getName()).log( - // Level.WARNING, - // "Couldn''t parse '" + integer + "' into an integer. Returning " + intResult - // + "."); } return intResult; } /** - * Tries to parse a String into a integer. If an exception happens, returns null. + * Tries to parse a String into a integer. If an exception happens, returns + * null. * - * @param integer - * a String representing an integer. - * @return the integer represented by the string, or null if it couldn't be parsed. + * @param integer a String representing an integer. + * @return the integer represented by the string, or null if it couldn't be + * parsed. */ public static Integer parseInteger(String integer) { @@ -132,18 +131,14 @@ public static Integer parseInteger(String integer) { /** * Tries to parse a String into a double. If an exception happens, returns null. * - * @param doublefloat - * a String representing a double. - * @return the double represented by the string, or null if it couldn't be parsed. + * @param doublefloat a String representing a double. + * @return the double represented by the string, or null if it couldn't be + * parsed. */ public static Optional valueOfDouble(String doublefloat) { - // Double doubleResult = null; try { - // doubleResult = Integer.parseInt(doublefloat); - // doubleResult = Double.valueOf(doublefloat); return Optional.of(Double.valueOf(doublefloat)); } catch (NumberFormatException e) { - // LoggingUtils.msgLib(e.toString()); return Optional.empty(); } @@ -156,36 +151,24 @@ public static Optional valueOfDouble(String doublefloat) { */ public static short parseShort(String s) { return Short.parseShort(s); - /* - Short value = null; - try { - value = Short.parseShort(argument); - } catch (NumberFormatException ex) { - throw new RuntimeException("Expecting a short immediate: '\" + argument + \"'.", ex); - // LoggingUtils.getLogger(). - // warning("Expecting an integer immediate: '" + argument + "'."); - // warning("Expecting a short immediate: '" + argument + "'."); - } - return value; - */ } /** * Overload that sets 'isStrict' to true. * - * @param afloat - * a String representing a float. - * @return the float represented by the string, or null if it couldn't be parsed. + * @param afloat a String representing a float. + * @return the float represented by the string, or null if it couldn't be + * parsed. */ public static Float parseFloat(String afloat) { return parseFloat(afloat, true); } /** - * Tries to parse a String into a float. If an exception happens or if it lowers precision, returns null. + * Tries to parse a String into a float. If an exception happens or if it lowers + * precision, returns null. * - * @param afloat - * a String representing a float. + * @param afloat a String representing a float. * @param isStrict * @return */ @@ -208,21 +191,22 @@ public static Float parseFloat(String afloat, boolean isStrict) { /** * Overload that sets 'isStrict' to true. * - * @param aDouble - * a String representing a double. - * @return the double represented by the string, or null if it couldn't be parsed. + * @param aDouble a String representing a double. + * @return the double represented by the string, or null if it couldn't be + * parsed. */ public static Double parseDouble(String aDouble) { return parseDouble(aDouble, true); } /** - * Tries to parse a String into a double. If an exception happens or if it lowers precision, returns null. + * Tries to parse a String into a double. If an exception happens or if it + * lowers precision, returns null. * - * @param aDouble - * a String representing a float. + * @param aDouble a String representing a double. * @param strict - * @return the double represented by the string, or null if it couldn't be parsed. + * @return the double represented by the string, or null if it couldn't be + * parsed. */ public static Double parseDouble(String aDouble, boolean isStrict) { Double doubleResult = null; @@ -239,27 +223,6 @@ public static Double parseDouble(String aDouble, boolean isStrict) { return doubleResult; } - /** - * Tries to parse a String into a float. If an exception happens, returns null. - * - * @param aFloat - * a String representing a float. - * @return the float represented by the string, or null if it couldn't be parsed. - */ - /* - public static Float parseFloat(String aFloat) { - Float doubleResult = null; - try { - doubleResult = Float.valueOf(aFloat); - } catch (NumberFormatException e) { - // LoggingUtils.msgLib(e.toString()); - return null; - } - - return doubleResult; - } - */ - /** * Helper method using radix 10 as default. */ @@ -270,8 +233,7 @@ public static Long parseLong(String longNumber) { /** * Tries to parse a String into a long. If an exception happens, returns null. * - * @param longNumber - * a String representing an long + * @param longNumber a String representing a long * @param radix * @return the long represented by the string, or 0L if it couldn't be parsed */ @@ -282,20 +244,16 @@ public static Long parseLong(String longNumber, int radix) { longResult = Long.valueOf(longNumber, radix); } catch (NumberFormatException e) { return null; - // Logger.getLogger(ParseUtils.class.getName()).log( - // Level.WARNING, - // "Couldn''t parse '" + longNumber - // + "' into an long. Returning " + longResult + "."); } return longResult; } /** - * Tries to parse a String into a BigInteger. If an exception happens, returns null. + * Tries to parse a String into a BigInteger. If an exception happens, returns + * null. * - * @param intNumber - * a String representing an integer. + * @param intNumber a String representing an integer. * @return the long represented by the string, or 0L if it couldn't be parsed. */ public static BigInteger parseBigInteger(String intNumber) { @@ -309,11 +267,12 @@ public static BigInteger parseBigInteger(String intNumber) { } /** - * Tries to parse a String into a Boolean. If an exception happens, warns the user and returns null. + * Tries to parse a String into a Boolean. If an exception happens, warns the + * user and returns null. * - * @param booleanString - * a String representing a Boolean. - * @return the Boolean represented by the string, or null if it couldn't be parsed. + * @param booleanString a String representing a Boolean. + * @return the Boolean represented by the string, or null if it couldn't be + * parsed. */ public static Boolean parseBoolean(String booleanString) { booleanString = booleanString.toLowerCase(); @@ -328,16 +287,15 @@ public static Boolean parseBoolean(String booleanString) { } /** - * Removes, from String text, the portion of text after the rightmost occurrence of the specified separator. + * Removes, from String text, the portion of text after the rightmost occurrence + * of the specified separator. * *

* Ex.: removeSuffix("readme.txt", ".")
* Returns "readme". * - * @param text - * a string - * @param separator - * a string + * @param text a string + * @param separator a string * @return a string */ public static String removeSuffix(String text, String separator) { @@ -357,10 +315,9 @@ public static String removeSuffix(String text, String separator) { * Ex.: toHexString(10, 2)
* Returns 0x0A. * - * @param decimalLong - * a long - * @param stringSize - * the final number of digits in the hexadecimal representation + * @param decimalLong a long + * @param stringSize the final number of digits in the hexadecimal + * representation * @return a string */ public static String toHexString(int decimalInt, int stringSize) { @@ -376,10 +333,9 @@ public static String toHexString(int decimalInt, int stringSize) { * Ex.: toHexString(10, 2)
* Returns 0x0A. * - * @param decimalLong - * a long - * @param stringSize - * the final number of digits in the hexadecimal representation + * @param decimalLong a long + * @param stringSize the final number of digits in the hexadecimal + * representation * @return a string */ public static String toHexString(long decimalLong, int stringSize) { @@ -390,9 +346,9 @@ public static String toHexString(long decimalLong, int stringSize) { } /** - * @param string - * a string - * @return the index of the first whitespace found in the given String, or -1 if none is found. + * @param string a string + * @return the index of the first whitespace found in the given String, or -1 if + * none is found. */ public static int indexOfFirstWhitespace(String string) { return indexOf(string, aChar -> Character.isWhitespace(aChar), false); @@ -400,12 +356,6 @@ public static int indexOfFirstWhitespace(String string) { public static int indexOf(String string, Predicate target, boolean reverse) { - // if (reverse) { - // string = new StringBuilder(string).reverse().toString(); - // } - - // IntStream charsStream = string.chars(); - // Test reverse order if (reverse) { for (int i = string.length() - 1; i >= 0; i--) { @@ -429,10 +379,8 @@ public static int indexOf(String string, Predicate target, boolean re /** * Adds spaces to the end of the given string until it has the desired size. * - * @param string - * a string - * @param length - * the size we want the string to be + * @param string a string + * @param length the size we want the string to be * @return the string, with the desired size */ public static String padRight(String string, int length) { @@ -440,12 +388,11 @@ public static String padRight(String string, int length) { } /** - * Adds spaces to the beginning of the given string until it has the desired size. + * Adds spaces to the beginning of the given string until it has the desired + * size. * - * @param string - * a string - * @param length - * length the size we want the string to be + * @param string a string + * @param length length the size we want the string to be * @return the string, with the desired size */ public static String padLeft(String string, int length) { @@ -453,14 +400,12 @@ public static String padLeft(String string, int length) { } /** - * Adds an arbitrary character to the beginning of the given string until it has the desired size. + * Adds an arbitrary character to the beginning of the given string until it has + * the desired size. * - * @param string - * a string - * @param length - * length the size we want the string to be - * @param c - * the character to pad with + * @param string a string + * @param length length the size we want the string to be + * @param c the character to pad with * @return the string, with the desired size */ public static String padLeft(String string, int length, char c) { @@ -488,10 +433,12 @@ public static > List getSortedList(Collection * Reads a Table file and returns a table with the key-value pairs. * *

- * Any line with one or more parameters, as defined by the object LineParser is put in the table. The first - * parameters is used as the key, and the second as the value.
+ * Any line with one or more parameters, as defined by the object LineParser is + * put in the table. The first parameters is used as the key, and the second as + * the value.
* If a line has more than two parameters, they are ignored.
- * If a line has only a single parameters, the second parameters is assumed to be an empty string. + * If a line has only a single parameters, the second parameters is assumed to + * be an empty string. * * @param tableFile * @param lineParser @@ -616,13 +563,6 @@ public static T moduloGet(List list, int index) { } index = modulo(index, list.size()); - /* - index = index % list.size(); - if(index < 0) { - index = index + list.size(); - } - * - */ return list.get(index); } @@ -683,29 +623,15 @@ public static String getRegexGroup(String contents, String regex, int capturingG return getRegexGroup(contents, pattern, capturingGroupIndex); } - // public static String getRegexGroup(String contents, Pattern regex, int capturingGroupIndex) { public static String getRegexGroup(String contents, Pattern pattern, int capturingGroupIndex) { - // ResultsKey[] keys = ResultsKey.values(); - // for (int i = 0; i < strings.length; i++) { - // for (int j = 0; j < regexes.size(); j++) { - // Pattern regex = regexes.get(j); - // int backReferenceIndex = keyIndex.get(j); - String tester = null; try { - // Pattern pattern = Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE); - Matcher regexMatcher = pattern.matcher(contents); if (regexMatcher.find()) { - // tester = regexMatcher.group(1); tester = regexMatcher.group(capturingGroupIndex); - // tester = tester.replaceAll(",", ""); - // data.put(keys[capturingGroupIndex], tester); - // System.out.println("#" + keys[capturingGroupIndex] + ":" + - // tester); } } catch (PatternSyntaxException ex) { // Syntax error in the regular expression @@ -713,8 +639,6 @@ public static String getRegexGroup(String contents, Pattern pattern, int capturi } return tester; - // } - // } } public static List getRegexGroups(String contents, String regex, int capturingGroupIndex) { @@ -740,8 +664,6 @@ public static List getRegexGroups(String contents, Pattern pattern, int } return results; - // } - // } } /** @@ -763,8 +685,8 @@ public static String getAlphaId(int number) { // Portuguese alphabet (23 letters, skipping K, W, Y) final char[] PT_ALPHABET = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', - 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z' + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z' }; final int ALPHABET_SIZE = PT_ALPHABET.length; if (number < 0) { @@ -790,12 +712,10 @@ public static String getAlphaId(int number) { public static String toExcelColumn(int columnNumber) { int dividend = columnNumber; List reversedColumnName = new ArrayList<>(); - // String columnName = ""; while (dividend > 0) { int modulo = (dividend - 1) % 26; reversedColumnName.add((char) (65 + modulo)); - // columnName = ((char) (65 + modulo)) + columnName; dividend = (dividend - modulo) / 26; } @@ -804,29 +724,27 @@ public static String toExcelColumn(int columnNumber) { return reversedColumnName.stream() .map(Object::toString) .collect(Collectors.joining()); - - // return columnName; } public static String toString(TimeUnit timeUnit) { switch (timeUnit) { - case NANOSECONDS: - return "ns"; - case MICROSECONDS: - return "us"; - case MILLISECONDS: - return "ms"; - case SECONDS: - return "s"; - case MINUTES: - return "m"; - case HOURS: - return "h"; - case DAYS: - return "d"; - default: - SpecsLogs.getLogger().warning("Case not defined:" + timeUnit); - return ""; + case NANOSECONDS: + return "ns"; + case MICROSECONDS: + return "us"; + case MILLISECONDS: + return "ms"; + case SECONDS: + return "s"; + case MINUTES: + return "m"; + case HOURS: + return "h"; + case DAYS: + return "d"; + default: + SpecsLogs.getLogger().warning("Case not defined:" + timeUnit); + return ""; } } @@ -856,11 +774,6 @@ public static double convert(double timeValue, TimeUnit currentUnit, TimeUnit de double multiplier = (double) currentNanos / (double) destinationNanos; - // System.out.println("currentNanos:"+currentNanos); - // System.out.println("destNanos:"+destinationNanos); - // System.out.println("Multiplier:"+multiplier); - // System.out.println("TimeValue:"+timeValue); - return timeValue * multiplier; } @@ -888,8 +801,8 @@ public static HashMap invertMap(Map aMap) { } /** - * Adds all elements of elementsMap to destinationMap. If any element is replaced, the key in put in the return - * list. + * Adds all elements of elementsMap to destinationMap. If any element is + * replaced, the key in put in the return list. * * @param destinationMap * @param elementsMap @@ -909,8 +822,9 @@ public static List putAll(Map destinationMap, Map elements } /** - * Checks if a mapping for a key in elementsMap is also present to destinationMap. If a key is present in both maps, - * it is added to the return list. + * Checks if a mapping for a key in elementsMap is also present to + * destinationMap. If a key is present in both maps, it is added to the return + * list. * * @param destinationMap * @param elementsMap @@ -931,11 +845,6 @@ public static List check(Map destinationMap, Map elementsM public static String getExtension(String hdlFilename) { int separatorIndex = hdlFilename.lastIndexOf('.'); if (separatorIndex == -1) { - /* - LoggingUtils.getLogger().warning( - "Could not find extension in filename '" + hdlFilename - + "'."); - */ return null; } @@ -947,7 +856,8 @@ public static String getExtension(String hdlFilename) { * *

* Ex.: element "Sa" and numElements "2" returns "SaSa".
- * If numElements is zero, returns an empty string. If numElements is one, returns the string itself. + * If numElements is zero, returns an empty string. If numElements is one, + * returns the string itself. * * @param element * @param numElements @@ -992,14 +902,11 @@ public static Character charAt(String string, int charIndex) { * * * @param aList - * @param startIndex - * (inclusive) - * @param endIndex - * (exclusive) + * @param startIndex (inclusive) + * @param endIndex (exclusive) */ public static void remove(List aList, int startIndex, int endIndex) { - // for (int i = endIndex; i >= startIndex; i--) { for (int i = endIndex - 1; i >= startIndex; i--) { aList.remove(i); } @@ -1056,7 +963,8 @@ public static String camelCaseSeparate(String aString, String separator) { } /** - * Accepts tag-value pairs and replaces the tags in the given template for the specified values. + * Accepts tag-value pairs and replaces the tags in the given template for the + * specified values. * * @param template * @param defaultTagsAndValues @@ -1134,7 +1042,8 @@ public static Number parseNumber(String number) { } /** - * Tries to parse a number according to a number of classes, in the following order:
+ * Tries to parse a number according to a number of classes, in the following + * order:
* - Integer
* - Long
* - Float
@@ -1193,7 +1102,8 @@ public static String parseTime(double nanos) { } /** - * Transforms a number of nano-seconds into a string, trying to find what should be the best time unit. + * Transforms a number of nano-seconds into a string, trying to find what should + * be the best time unit. * * @param nanos * @return @@ -1223,7 +1133,6 @@ public static String parseTime(long nanos) { double mins = secs / 60.0; - // return doubleFormat.format(mins) + " minutes"; String min = "minute"; int intMins = (int) mins; if (intMins != 1) { @@ -1242,8 +1151,6 @@ public static String parseTime(long nanos) { .add(Integer.toString(intSecs)) .add(sec) .toString(); - - // return intMins + " " + min + " " + (int) (secs - ((int) mins * 60)) + " seconds"; } /** @@ -1324,41 +1231,8 @@ public static Double decodeDouble(String number, Supplier defaultValue) } /** - * Test if two objects (that can be null) are equal. - * - *

- * If both objects are null, returns null. Otherwise, uses the equals of the first non-null object on the other. - * - * @param nargout - * @param nargouts - * @return - */ - /* - public static boolean equals(Object obj1, Object obj2) { - boolean isObj1Null = obj1 == null; - boolean isObj2Null = obj2 == null; - - if (isObj1Null && isObj2Null) { - return true; - } - - Object nonNullObject = null; - Object objectToCompare = null; - if (!isObj1Null) { - nonNullObject = obj1; - objectToCompare = obj2; - } else { - nonNullObject = obj2; - objectToCompare = obj1; - } - - return nonNullObject.equals(objectToCompare); - } - */ - - /** - * Test if the given object implements the given class. If true, casts the object to the class type. Otherwise, - * throws an exception. + * Test if the given object implements the given class. If true, casts the + * object to the class type. Otherwise, throws an exception. * * * @param object @@ -1373,8 +1247,8 @@ public static T cast(Object object, Class aClass) { * Casts an object to a given type. * *

- * If the object could not be cast to the given type and throwException is false, returns null. If throwException is - * true, throws an exception. + * If the object could not be cast to the given type and throwException is + * false, returns null. If throwException is true, throws an exception. * * @param object * @param aClass @@ -1401,7 +1275,8 @@ public static T cast(Object object, Class aClass, boolean throwException) * Casts a list of objects to a List of the given type. * *

- * If any of the objects in the list could not be cast to the given type and throwException is false, returns null. + * If any of the objects in the list could not be cast to the given type and + * throwException is false, returns null. * If throwException is true, throws an exception. * * @param object @@ -1467,8 +1342,8 @@ public static boolean isDigitOrLetter(char aChar) { } /** - * Replaces '.' in the package with '/', and suffixes '/' to the String, if necessary. - * + * Replaces '.' in the package with '/', and suffixes '/' to the String, if + * necessary. * * @param packageName * @return @@ -1486,14 +1361,8 @@ public static String packageNameToResource(String packageName) { public static int parseIntegerRelaxed(String constant) { Preconditions.checkArgument(constant != null); - // Double doubleConstant = ParseUtils.parseDouble(constant); double doubleConstant = Double.parseDouble(constant); - /* - if (doubleConstant == null) { - throw new RuntimeException("Could not parse '" + constant + "' into a number"); - } - */ - // Double has enough precision to accurately represent any 32-bit number. + if (!(doubleConstant >= Integer.MIN_VALUE && doubleConstant <= Integer.MAX_VALUE)) { throw new OverflowException("Number in size is too large"); } @@ -1501,7 +1370,6 @@ public static int parseIntegerRelaxed(String constant) { throw new RuntimeException("Dimension argument must be an integer."); } - // return doubleConstant.intValue(); return (int) doubleConstant; } @@ -1673,7 +1541,8 @@ public static int count(String string, char aChar) { * Counts the number of lines in the given String. * *

- * Taken from here: https://stackoverflow.com/questions/2850203/count-the-number-of-lines-in-a-java-string#2850259 + * Taken from here: + * https://stackoverflow.com/questions/2850203/count-the-number-of-lines-in-a-java-string#2850259 * * @param string * @return @@ -1737,29 +1606,16 @@ public static List splitArgs(String string) { if (!arg.isEmpty()) { currentString = new StringBuilder(); addArgs(args, arg); - // args.add(arg); } continue; } - /* - if (currentChar == '\\') { - // Check if it is escaping a double quote - if (string.length() > (i + 1) && string.charAt(i + 1) == '"') { - i++; - } - - currentString.append("\\\""); - continue; - } - */ - // Arguments that were quoted will loose the quotes. - // Otherwise, when using the resulting list to execute the program, it would add quotes again + // Otherwise, when using the resulting list to execute the program, it would add + // quotes again if (currentChar == '"') { doubleQuoteActive = !doubleQuoteActive; - // currentString.append("\""); continue; } @@ -1768,7 +1624,6 @@ public static List splitArgs(String string) { if (currentString.length() > 0) { addArgs(args, currentString.toString()); - // args.add(currentString.toString()); } return args; @@ -1852,7 +1707,8 @@ public static String toCamelCase(String string) { } /** - * Overload which lets select the used separator and capitalizes the first letter. + * Overload which lets select the used separator and capitalizes the first + * letter. * * @param string * @return @@ -1935,11 +1791,11 @@ public static String normalizeFileContents(String fileContents) { } /** - * Returns an integer from a decimal string such as "123". If the string does not contain just a decimal integer + * Returns an integer from a decimal string such as "123". If the string does + * not contain just a decimal integer * (such as " 123" or "12x") then this returns empty. * - * @param value - * The string to convert to int. Must not be null. + * @param value The string to convert to int. Must not be null. * @return The parsed integer, or empty if the string is not an integer. */ public static Optional tryGetDecimalInteger(String value) { @@ -1958,7 +1814,8 @@ public static Optional tryGetDecimalInteger(String value) { } /** - * Basen on https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java + * Basen on + * https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java * * @param bytes * @return @@ -2006,11 +1863,11 @@ public static String removeWhitespace(String string) { } /** - * Given a string with an open-close parenthesis, returns the closing parenthesis corresponding to the first open - * parenthesis it finds. + * Given a string with an open-close parenthesis, returns the closing + * parenthesis corresponding to the first open parenthesis it finds. * *

- * If no matching closing parenthesis is found, throwns an Exception. + * If no matching closing parenthesis is found, throws an Exception. * * @param string * @return @@ -2046,13 +1903,12 @@ public static String toDecimal(long number) { } /** - * Splits the given String according to a separator, and removes blank String that can be created from the - * splitting. + * Splits the given String according to a separator, and removes blank String + * that can be created from the splitting. * * @param string * @param separator - * @param strip - * if true, strips each splitted String + * @param strip if true, strips each splitted String * @return */ public static List splitNonEmpty(String string, String separator, boolean strip) { @@ -2066,12 +1922,14 @@ public static List splitNonEmpty(String string, String separator, boolea * Parses a list of paths. * *

- * A sequence of paths may be prefixed with a $PREFIX$, the paths after the second $ will be prefixed with PREFIX, - * until a new $PREFIX$ appears. PREFIX can be empty. + * A sequence of paths may be prefixed with a $PREFIX$, the paths after the + * second $ will be prefixed with PREFIX, until a new $PREFIX$ appears. PREFIX + * can be empty. * *

- * Example (; as separator): path1$prefix/$path2;path3$$path4 returns a Map where "" (empty string) is mapped to - * path1 and path4, and "prefix" is mapped to path2 and path3 + * Example (; as separator): path1$prefix/$path2;path3$$path4 returns a Map + * where "" (empty string) is mapped to path1 and path4, and "prefix" is mapped + * to path2 and path3 * * * @param pathList @@ -2086,7 +1944,6 @@ public static MultiMap parsePathList(String pathList, String sep // Separate into prefixes MultiMap prefixPaths = new MultiMap<>(); - // List pathsWithoutPrefix = new ArrayList<>(); String currentString = pathList; @@ -2192,7 +2049,8 @@ public static String nullIfEmpty(String string) { } /** - * Checks if two strings are identical, not considering empty spaces. Returns false if strings do not match. + * Checks if two strings are identical, not considering empty spaces. Returns + * false if strings do not match. */ public static boolean check(String expected, String actual) { @@ -2207,9 +2065,10 @@ public static boolean check(String expected, String actual) { * Normalizes the given string so that it represents a JSON object. * *

- * - If the input is a single string that ends in .json, interprets as an existing file whose contents will be - * returned;
- * - If the string does not start with { or ends with }, introduces those characters; + * - If the input is a single string that ends in .json, interprets as an + * existing file whose contents will be returned;
+ * - If the string does not start with { or ends with }, introduces those + * characters; * * @param trim * @return @@ -2221,9 +2080,9 @@ public static String normalizeJsonObject(String json) { /** * * @param json - * @param baseFolder - * if json represents a relative path to a json file and baseFolder is not null, uses baseFolder as the - * parent of the relative path + * @param baseFolder if json represents a relative path to a json file and + * baseFolder is not null, uses baseFolder as the + * parent of the relative path * @return */ public static String normalizeJsonObject(String json, File baseFolder) { @@ -2268,7 +2127,8 @@ public static char lastChar(String string) { } /** - * Sanitizes a string representing a single name of a path. Currently replaces ' ', '(' and ')' with '_' + * Sanitizes a string representing a single name of a path. Currently replaces ' + * ', '(' and ')' with '_' * * @param path * @return diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsSwing.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsSwing.java index bd6af703..e73f9305 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsSwing.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsSwing.java @@ -41,7 +41,8 @@ /** * Utility methods for Java Swing operations. *

- * Provides static helper methods for dialogs, UI helpers, and event handling in Java Swing applications. + * Provides static helper methods for dialogs, UI helpers, and event handling in + * Java Swing applications. *

* * @author Joao Bispo @@ -127,7 +128,8 @@ public static boolean setSystemLookAndFeel() { } /** - * Gets the system Look and Feel class name, avoiding problematic defaults like Metal and GTK+. + * Gets the system Look and Feel class name, avoiding problematic defaults like + * Metal and GTK+. * * @return the class name of the system Look and Feel */ @@ -170,10 +172,10 @@ public static String getSystemLookAndFeel() { /** * Builds TableModels from Maps, splitting into multiple tables if necessary. * - * @param map the map to convert into TableModels + * @param map the map to convert into TableModels * @param maxElementsPerTable the maximum number of elements per table - * @param rowWise whether the table should be row-wise - * @param valueClass the class of the values in the map + * @param rowWise whether the table should be row-wise + * @param valueClass the class of the values in the map * @return a list of TableModels */ public static , V> List getTables(Map map, @@ -217,8 +219,8 @@ public static , V> List getTables(Ma /** * Builds a single TableModel from a Map. * - * @param map the map to convert into a TableModel - * @param rowWise whether the table should be row-wise + * @param map the map to convert into a TableModel + * @param rowWise whether the table should be row-wise * @param valueClass the class of the values in the map * @return a TableModel */ @@ -259,8 +261,8 @@ public static JFrame showPanel(JPanel panel, String title) { * * @param panel the JPanel to display * @param title the title of the JFrame - * @param x the x-coordinate of the JFrame - * @param y the y-coordinate of the JFrame + * @param x the x-coordinate of the JFrame + * @param y the y-coordinate of the JFrame * @return the JFrame containing the panel */ public static JFrame newWindow(JPanel panel, String title, int x, int y) { @@ -282,8 +284,8 @@ public static JFrame newWindow(JPanel panel, String title, int x, int y) { * * @param panel the JPanel to display * @param title the title of the JFrame - * @param x the x-coordinate of the JFrame - * @param y the y-coordinate of the JFrame + * @param x the x-coordinate of the JFrame + * @param y the y-coordinate of the JFrame * @return the JFrame containing the panel */ public static JFrame showPanel(JPanel panel, String title, int x, int y) { @@ -299,7 +301,8 @@ public static JFrame showPanel(JPanel panel, String title, int x, int y) { } /** - * Checks if the current environment is headless, i.e., no screen is available for displaying Swing components. + * Checks if the current environment is headless, i.e., no screen is available + * for displaying Swing components. * * @return true if the environment is headless, false otherwise */ @@ -317,7 +320,8 @@ public static boolean isHeadless() { } /** - * Opens a folder containing the file and selects it in a default system file manager. + * Opens a folder containing the file and selects it in a default system file + * manager. * * @param file the file to select * @return true if the operation was successful, false otherwise @@ -329,7 +333,7 @@ public static boolean browseFileDirectory(File file) { if (SpecsSystem.isWindows()) { - String[] command = {"explorer.exe", "/select,", file.getAbsoluteFile().getAbsolutePath()}; + String[] command = { "explorer.exe", "/select,", file.getAbsoluteFile().getAbsolutePath() }; try { Runtime.getRuntime().exec(command); } catch (IOException e) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsSystem.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsSystem.java index ae296d08..96089d46 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsSystem.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsSystem.java @@ -94,7 +94,8 @@ private static boolean testIsDebug() { } /** - * Helper method which receives the command and the working directory instead of the builder. + * Helper method which receives the command and the working directory instead of + * the builder. * * @param command * @param workingDir @@ -103,7 +104,7 @@ private static boolean testIsDebug() { * @return */ public static ProcessOutputAsString runProcess(List command, File workingDir, - boolean storeOutput, boolean printOutput) { + boolean storeOutput, boolean printOutput) { ProcessBuilder builder = new ProcessBuilder(command); builder.directory(workingDir); @@ -111,7 +112,7 @@ public static ProcessOutputAsString runProcess(List command, File workin } public static ProcessOutputAsString runProcess(List command, File workingDir, - boolean storeOutput, boolean printOutput, Long timeoutNanos) { + boolean storeOutput, boolean printOutput, Long timeoutNanos) { ProcessBuilder builder = new ProcessBuilder(command); builder.directory(workingDir); @@ -124,7 +125,8 @@ public static ProcessOutputAsString runProcess(List command, File workin } /** - * Helper method which receives the command instead of the builder, and launches the process in the current + * Helper method which receives the command instead of the builder, and launches + * the process in the current * directory. * * @param command @@ -133,33 +135,11 @@ public static ProcessOutputAsString runProcess(List command, File workin * @return */ public static ProcessOutputAsString runProcess(List command, - boolean storeOutput, boolean printOutput) { + boolean storeOutput, boolean printOutput) { return runProcess(command, SpecsIo.getWorkingDir(), storeOutput, printOutput); } - /** - * Launches a process for the given command, that runs on 'workingDir'. - * - * @param command - * @param workingDir - * @param storeOutput - * @param printOutput - * @param builder - * @return - */ - /* - public static ProcessOutput runProcess(List command, String workingDir, - boolean storeOutput, boolean printOutput, ProcessBuilder builder) { - - builder.command(command); - builder.directory(new File(workingDir)); - - // return runProcess(builder, storeOutput, printOutput).get(); - return runProcess(builder, storeOutput, printOutput); - } - */ - /** * Launches the process characterized by 'builder'. * @@ -181,7 +161,8 @@ public static ProcessOutputAsString runProcess(ProcessBuilder builder, boolean s } /** - * Helper method which receives the command instead of the builder, and launches the process in the current + * Helper method which receives the command instead of the builder, and launches + * the process in the current * directory. * * @param command @@ -190,13 +171,14 @@ public static ProcessOutputAsString runProcess(ProcessBuilder builder, boolean s * @return */ public static ProcessOutput runProcess(List command, - Function outputProcessor, Function errorProcessor) { + Function outputProcessor, Function errorProcessor) { return runProcess(command, SpecsIo.getWorkingDir(), outputProcessor, errorProcessor); } /** - * Helper method which receives the command and the working directory instead of the builder. + * Helper method which receives the command and the working directory instead of + * the builder. * * @param command * @param workingDir @@ -205,98 +187,13 @@ public static ProcessOutput runProcess(List command, * @return */ public static ProcessOutput runProcess(List command, File workingDir, - Function outputProcessor, Function errorProcessor) { + Function outputProcessor, Function errorProcessor) { ProcessBuilder builder = new ProcessBuilder(command); builder.directory(workingDir); return runProcess(builder, outputProcessor, errorProcessor); } - /** - * Arguments such as -I - * - * @param command - * @return - */ - /* - // private static List normalizeProcessCommand(List command) { - private static String normalizeProcessArgument(String arg) { - // Trim argument - String trimmedArg = arg.strip(); - SpecsLogs.debug(() -> "Argument: '" + trimmedArg + "'"); - - if (!trimmedArg.startsWith("-I")) { - return trimmedArg; - } - - if (trimmedArg.charAt(2) != '\"') { - return trimmedArg; - } - - SpecsLogs.debug(() -> "Normalizing -I argument: '" + trimmedArg + "'"); - SpecsCheck.checkArgument(trimmedArg.endsWith("\""), - () -> "Expected argument to end with double quote: '" + trimmedArg + "'"); - String normalizedArg = "-I" + trimmedArg.substring(3, trimmedArg.length() - 1); - SpecsLogs.debug(() -> "Normalized: '" + normalizedArg + "'"); - - return normalizedArg; - - // // List normalizedCommand = new ArrayList<>(command.size()); - // - // // for (String arg : command) { - // // Trim argument - // String trimmedArg = arg.strip(); - // - // // Check if it has white space - // if (!trimmedArg.contains(" ")) { - // // SpecsLogs.debug("Did not normalized argument, did not find spaces: '" + trimmedArg + "'"); - // return trimmedArg; - // // normalizedCommand.add(trimmedArg); - // // continue; - // } - // - // // If contain white space, check if already between quotes - // boolean hasStartQuote = trimmedArg.startsWith("\""); - // boolean hasEndQuote = trimmedArg.endsWith("\""); - // if (hasStartQuote && hasEndQuote) { - // // SpecsLogs - // // .debug("Did not normalized argument, has spaces but also already has quotes: '" + trimmedArg + "'"); - // return trimmedArg; - // // normalizedCommand.add(trimmedArg); - // // continue; - // } - // - // // Check if quotes are balanced - // // Leave like that, it can be on purpose - // // E.g., -I"" - // boolean isUnbalanced = hasStartQuote ^ hasEndQuote; - // if (isUnbalanced) { - // // SpecsLogs.debug("Found unbalanced double quotes on argument, leaving it like that: '" + trimmedArg + - // // "'"); - // return trimmedArg; - // } - // // } else { - // SpecsLogs.debug("Found argument that needs double quotes, correcting: '" + trimmedArg + "'"); - // // } - // - // if (!hasStartQuote) { - // trimmedArg = "\"" + trimmedArg; - // } - // - // if (!hasEndQuote) { - // trimmedArg = trimmedArg + "\""; - // } - // - // return trimmedArg; - // // normalizedCommand.add(trimmedArg); - // // } - // - // // return normalizedCommand; - // - - } - */ - /** * Launches the process characterized by 'builder'. * @@ -309,28 +206,29 @@ private static String normalizeProcessArgument(String arg) { * @return */ public static ProcessOutput runProcess(ProcessBuilder builder, - Function outputProcessor, Function errorProcessor) { + Function outputProcessor, Function errorProcessor) { return runProcess(builder, outputProcessor, errorProcessor, null); } public static ProcessOutput runProcess(ProcessBuilder builder, - Function outputProcessor, Function errorProcessor, Long timeoutNanos) { + Function outputProcessor, Function errorProcessor, Long timeoutNanos) { return runProcess(builder, outputProcessor, errorProcessor, null, timeoutNanos); } public static ProcessOutput runProcess(ProcessBuilder builder, - Function outputProcessor, Function errorProcessor, - Consumer input, Long timeoutNanos) { + Function outputProcessor, Function errorProcessor, + Consumer input, Long timeoutNanos) { - // The command in the builder might need processing (e.g., Windows system commands) + // The command in the builder might need processing (e.g., Windows system + // commands) processCommand(builder); SpecsLogs.debug(() -> "Launching Process: " + builder.command().stream().collect(Collectors.joining(" "))); Process process = null; try { - // Experiment: Calling Garbage Collector before starting process in order to reduce memory required to fork - // VM + // Experiment: Calling Garbage Collector before starting process in order to + // reduce memory required to fork VM // http://www.bryanmarty.com/2012/01/14/forking-jvm/ long totalMemBefore = Runtime.getRuntime().totalMemory(); System.gc(); @@ -358,8 +256,6 @@ public static ProcessOutput runProcess(ProcessBuilder builder, stdinThread.shutdown(); } - // outputStream. - // The ExecutorService objects are shutdown, as they will not // receive more tasks. stdoutThread.shutdown(); @@ -369,17 +265,12 @@ public static ProcessOutput runProcess(ProcessBuilder builder, } /** - * Performs several fixes on the builder command (e.g., adapts command for Windows platforms) + * Performs several fixes on the builder command (e.g., adapts command for + * Windows platforms) * * @param builder */ private static void processCommand(ProcessBuilder builder) { - - // For now, do nothing if it is not Windows - // if (!isWindows()) { - // return; - // } - // Do nothing if no command if (builder.command().isEmpty()) { return; @@ -420,7 +311,7 @@ private static void processCommand(ProcessBuilder builder) { } private static ProcessOutput executeProcess(Process process, - Long timeoutNanos, Future outputFuture, Future errorFuture) { + Long timeoutNanos, Future outputFuture, Future errorFuture) { boolean timedOut = false; @@ -463,14 +354,6 @@ private static ProcessOutput executeProcess(Process process, outputException = e; } - // wait for notify (?) - /* try { - process.getInputStream().wait(); - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - }*/ - int returnValue = timedOut ? -1 : process.exitValue(); if (timedOut) { SpecsLogs.info("Process timed out after " + SpecsStrings.parseTime(timeoutNanos)); @@ -482,7 +365,8 @@ private static ProcessOutput executeProcess(Process process, private static void destroyProcess(Process process) { - // TODO: a breakpoint is necessary before process destruction, or else the "insts" + // TODO: a breakpoint is necessary before process destruction, or else the + // "insts" // linestream is closed // Get descendants of the process @@ -524,46 +408,8 @@ public static ThreadFactory getDaemonThreadFactory() { } /** - * Transforms a String List representing a command into a single String separated by spaces. - * - * @param command - * @return - */ - /* - public static String getCommandString(List command) { - return normalizeCommand(command).stream() - // Normalize argument - // .map(SpecsSystem::normalizeProcessArgument) - .collect(Collectors.joining(" ")); - - // StringBuilder builder = new StringBuilder(); - // - // builder.append(command.get(0)); - // for (int i = 1; i < command.size(); i++) { - // builder.append(" "); - // builder.append(command.get(i)); - // } - // - // return builder.toString(); - } - */ - /** - * Normalizes a command to be executed, inserting double quotes where necessary. - * - * @param command - * @return - */ - /* - public static List normalizeCommand(List command) { - return command.stream() - // Normalize argument - .map(SpecsSystem::normalizeProcessArgument) - .collect(Collectors.toList()); - } - */ - - /** - * @return the StackTraceElement of the previous method of the method calling this method + * @return the StackTraceElement of the previous method of the method calling + * this method */ public static StackTraceElement getCallerMethod() { return getCallerMethod(3); @@ -585,7 +431,8 @@ public static StackTraceElement getCallerMethod(int callerMethodIndex) { /** * @param aClass * @param anInterface - * @return true if the given class implements the given interface. False otherwise. + * @return true if the given class implements the given interface. False + * otherwise. */ public static boolean implementsInterface(Class aClass, Class anInterface) { // Build set with interfaces of the given class @@ -598,12 +445,11 @@ public static boolean implementsInterface(Class aClass, Class anInterface) * Method with standard initialization procedures for a Java SE program. * *

- * Setups the logger and the Look&Feel for Swing. Additionally, looks for the file 'suika.properties' on the working + * Setups the logger and the Look&Feel for Swing. Additionally, looks for the + * file 'suika.properties' on the working * folder and applies its options. */ public static void programStandardInit() { - // fixes(); - // Disable security manager for Web Start // System.setSecurityManager(null); // Redirect output to the logger @@ -621,14 +467,9 @@ public static void programStandardInit() { } - // private static void fixes() { - // // To avoid illegal reflective accesses in Java 10 while library is not upgraded - // // https://stackoverflow.com/questions/33255578/old-jaxb-and-jdk8-metaspace-outofmemory-issue - // System.getProperties().setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); - // } - /** - * @return the name of the class of the main thread, or null if could not find the main thread. + * @return the name of the class of the main thread, or null if could not find + * the main thread. */ public static StackTraceElement[] getMainStackTrace() { String mainThread = "main"; @@ -695,7 +536,8 @@ public static void sleep(long millis) { } /** - * Similar to 'runProcess', but returns an int with the exit code, instead of the ProcessOutput. + * Similar to 'runProcess', but returns an int with the exit code, instead of + * the ProcessOutput. * *

* Prints the output, but does not store it to a String. @@ -753,7 +595,8 @@ public static long getUsedMemoryMb(boolean callGc) { } /** - * Taken from here: http://www.inoneo.com/en/blog/9/java/get-the-jvm-peak-memory-usage + * Taken from here: + * http://www.inoneo.com/en/blog/9/java/get-the-jvm-peak-memory-usage */ public static void printPeakMemoryUsage() { // Place this code just before the end of the program @@ -765,7 +608,6 @@ public static void printPeakMemoryUsage() { memoryUsage += String.format("Peak %s memory used: %s\n", pool.getName(), SpecsStrings.parseSize(peak.getUsed())); - // memoryUsage += String.format("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted()); } // we print the result in the console @@ -777,7 +619,8 @@ public static void printPeakMemoryUsage() { } /** - * Do-nothing function, for cases that accept Runnable and we do not want to do anything. + * Do-nothing function, for cases that accept Runnable and we do not want to do + * anything. */ public static void emptyRunnable() { @@ -808,7 +651,8 @@ public static boolean isCommandAvailable(List command, File workingdir) } /** - * Adds a path to the java.library.path property, and flushes the path cache so that subsequent System.load calls + * Adds a path to the java.library.path property, and flushes the path cache so + * that subsequent System.load calls * can find it. * * @param path The path to add @@ -819,7 +663,6 @@ public static void addJavaLibraryPath(String path) { System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparatorChar + path); - // Field sysPathsField; try { Lookup cl = MethodHandles.privateLookupIn(ClassLoader.class, MethodHandles.lookup()); @@ -869,8 +712,8 @@ public static boolean is64Bit() { String realArch = arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") - ? "64" - : "32"; + ? "64" + : "32"; if (realArch.equals("32")) { return false; @@ -879,35 +722,6 @@ public static boolean is64Bit() { return true; } - /** - * Cannot reliably get the return value from a JAR. - * - * This method checks if the last line of output is the error message defined in this class. - * - * @param output - * @return - */ - /* - public static boolean noErrorOccurred(String output) { - - // Get last line, check if error - List lines = LineReader.readLines(output); - boolean exceptionOccurred = lines.get(lines.size() - 1).equals(ProcessUtils.ERROR); - - if (!exceptionOccurred) { - return true; - } else { - return false; - } - } - */ - - /* - public static String getErrorString() { - return "\n" + ERROR; - } - */ - /** * Launches the callable in another thread and waits termination. * @@ -921,24 +735,6 @@ public static T executeOnThreadAndWait(Callable callable) { executor.shutdown(); return get(future); - /* - try { - return future.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - SpecsLogs.msgInfo("Failed to complete execution on thread, returning null"); - return null; - } catch (ExecutionException e) { - // Rethrow cause - Throwable cause = e.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; - } - - throw new RuntimeException(e.getCause()); - // throw new RuntimeException("Error while executing thread", e); - } - */ } public static T get(Future future) { @@ -996,10 +792,12 @@ public static T get(Future future, long timeout, TimeUnit unit) { } /** - * Runs the given supplier in a separate thread, encapsulating the result in a Future. + * Runs the given supplier in a separate thread, encapsulating the result in a + * Future. * *

- * Taken from here: https://stackoverflow.com/questions/5715235/java-set-timeout-on-a-certain-block-of-code + * Taken from here: + * https://stackoverflow.com/questions/5715235/java-set-timeout-on-a-certain-block-of-code * * @param * @param supplier @@ -1019,29 +817,9 @@ public static int executeOnProcessAndWait(Class aClass, String... args) { return executeOnProcessAndWait(aClass, SpecsIo.getWorkingDir(), Arrays.asList(args)); } - // public static int executeOnProcessAndWaitWithExec(Class aClass, String javaExecutable, String... args) { - // return executeOnProcessAndWaitWithExec(aClass, javaExecutable, Arrays.asList(args)); - // } - - /** - * Taken from here: https://stackoverflow.com/questions/636367/executing-a-java-application-in-a-separate-process - * - * @param aClass - * @return - */ - // public static int executeOnProcessAndWaitWithExec(Class aClass, String javaExecutable, List args) { - // return executeOnProcessAndWait(aClass, SpecsIo.getWorkingDir(), args); - // } - - // public static int executeOnProcessAndWait(Class aClass, File workingDir, - // List args) { - // - // return executeOnProcessAndWaitWith(aClass, workingDir, args); - // - // } - /** - * Taken from here: https://stackoverflow.com/questions/636367/executing-a-java-application-in-a-separate-process + * Taken from here: + * https://stackoverflow.com/questions/636367/executing-a-java-application-in-a-separate-process * * @param aClass * @param javaExecutable @@ -1050,80 +828,31 @@ public static int executeOnProcessAndWait(Class aClass, String... args) { * @return */ public static int executeOnProcessAndWait(Class aClass, File workingDir, - List args) { - - // File jarPath = SpecsIo.getJarPath(aClass).orElseThrow( - // () -> new RuntimeException("Could not locate the JAR file for the class '" + aClass + "'")); - // ((URLClassLoader() Thread.currentThread().getContextClassLoader()).getURL(); - // Process.exec("java", "-classpath", urls.join(":"), CLASS_TO_BE_EXECUTED) + List args) { String classpath = System.getProperty("java.class.path"); - // System.out.println("CLASSPATH:" + classpath); - String className = aClass.getCanonicalName(); - // String javaHome = "C:/Program Files/Java/jdk1.8.0_131/jre"; + List command = new ArrayList<>(); command.addAll( Arrays.asList("java", "-cp", classpath, className)); - // command.addAll( - // Arrays.asList("java", "\"-Djava.home=" + javaHome + "\"", "-cp", classpath, className)); - // Arrays.asList("cmd", "/c", "java", "\"-Djava.home=" + javaHome + "\"", "-cp", classpath, className)); - // command.addAll(Arrays.asList("java", "-cp", "\"" + jarPath.getAbsolutePath() + "\"", className)); + command.addAll(args); ProcessBuilder process = new ProcessBuilder(command); process.directory(workingDir); - // Set java home - // System.setProperty("java.home", javaHome); - // System.out.println("JAVA HOME:" + System.getProperty("java.home")); - // System.out.println("JAVA HOME BEFORE:" + System.getenv().get("JAVA_HOME")); - // System.getenv().put("JAVA_HOME", javaHome); - // System.out.println("JAVA HOME AFTER:" + System.getenv().get("JAVA_HOME")); - // process.environment().put("JAVA_HOME", javaHome); - ProcessOutputAsString output = runProcess(process, false, true); return output.getReturnValue(); - // ProcessBuilder builder = new ProcessBuilder("java", "-cp", classpath, className); - // Process process; - // try { - // process = builder.start(); - // process.waitFor(); - // return process.exitValue(); - // } catch (IOException e) { - // SpecsLogs.warn("Exception which executing process:\n", e); - // } catch (InterruptedException e) { - // Thread.currentThread().interrupt(); - // SpecsLogs.msgInfo("Failed to complete execution on process"); - // } - // - // return -1; - } - - // public static ProcessBuilder buildJavaProcess(Class aClass, String javaExecutable, List args) { - // public static ProcessBuilder buildJavaProcess(Class aClass, List args) { - // List command = new ArrayList<>(); - // command.add("java"); - // - // String classpath = System.getProperty("java.class.path"); - // String className = aClass.getCanonicalName(); - // - // command.add("-cp"); - // command.add(classpath); - // command.add(className); - // - // command.addAll(args); - // - // ProcessBuilder process = new ProcessBuilder(command); - // - // return process; - // } + } /** - * Returns a double based on the major (feature) and minor (interim) segments of the runtime version. + * Returns a double based on the major (feature) and minor (interim) segments of + * the runtime version. *

- * Example: if the version string is "16.3.2-internal+11-specsbuild-20220403", the return will be `16.3`. + * Example: if the version string is "16.3.2-internal+11-specsbuild-20220403", + * the return will be `16.3`. */ public static double getJavaVersionNumber() { var version = Runtime.version(); @@ -1137,9 +866,11 @@ public static double getJavaVersionNumber() { } /** - * Returns the components of the version number of the running Java VM as an immutable list. + * Returns the components of the version number of the running Java VM as an + * immutable list. *

- * Example: if the version string is "16.3.2-internal+11-specsbuild-20220403", the return will be `[16, 3, 2]`. + * Example: if the version string is "16.3.2-internal+11-specsbuild-20220403", + * the return will be `[16, 3, 2]`. */ public static List getJavaVersion() { // Get property @@ -1226,32 +957,9 @@ public static boolean isDebug() { return IS_DEBUG.get(); } - /* - // public static boolean hasCopyConstructor(T object) { - public static boolean hasCopyConstructor(Object object) { - // Class aClass = (Class) object.getClass(); - - // Constructor constructorMethod = null; - for (Constructor constructor : object.getClass().getConstructors()) { - Class[] constructorParams = constructor.getParameterTypes(); - - if (constructorParams.length != 1) { - continue; - } - - if (object.getClass().isAssignableFrom(constructorParams[0])) { - return true; - } - } - - return false; - // Create copy constructor: new T(T data) - // constructorMethod = aClass.getConstructor(aClass); - } - */ - /** - * Uses the copy constructor to create a copy of the given object. Throws exception if the class does not have a + * Uses the copy constructor to create a copy of the given object. Throws + * exception if the class does not have a * copy constructor. * * @param object @@ -1342,11 +1050,11 @@ public static T newInstance(Class aClass, Object... arguments) { * @param * @param aClass * @param arguments - * @return the first constructor that is compatible with the given arguments, or null if none is found + * @return the first constructor that is compatible with the given arguments, or + * null if none is found */ public static Constructor getConstructor(Class aClass, Object... arguments) { - constructorTest: - for (var constructor : aClass.getConstructors()) { + constructorTest: for (var constructor : aClass.getConstructors()) { // Verify if arguments are compatible var paramTypes = constructor.getParameterTypes(); @@ -1424,14 +1132,16 @@ public static List> getCommonSuperClasses(List> classes) { } /** - * @return true if the JVM is currently executing in a Linux system, false otherwise + * @return true if the JVM is currently executing in a Linux system, false + * otherwise */ public static boolean isLinux() { return IS_LINUX; } /** - * @return true if the JVM is currently executing in a Windows system, false otherwise + * @return true if the JVM is currently executing in a Windows system, false + * otherwise */ public static boolean isWindows() { return IS_WINDOWS; @@ -1466,8 +1176,7 @@ public static Object invoke(Object object, String method, Object... args) { } Class invokingClass = object instanceof Class ? (Class) object : object.getClass(); - // Class invokingClass = object.getClass(); - // Object invokingObject = object instanceof Class ? null : object; + // If method is static, object will be ignored Object invokingObject = object; @@ -1484,11 +1193,11 @@ public static Object invoke(Object object, String method, Object... args) { } catch (Exception e) { throw new RuntimeException("Error while invoking method '" + method + "'", e); } - // return object.class.getMethod(property, arguments).invoke(object, arguments); } /** - * Similar to findMethod(), but caches results. Be careful, can lead to unintended errors. + * Similar to findMethod(), but caches results. Be careful, can lead to + * unintended errors. * * @param invokingClass * @param methodName @@ -1516,8 +1225,7 @@ private static String getMethodId(Class invokingClass, String methodName, Cla public static Method findMethod(Class invokingClass, String methodName, Class... types) { Method invokingMethod = null; - top: - for (var classMethod : invokingClass.getMethods()) { + top: for (var classMethod : invokingClass.getMethods()) { // Check name if (!classMethod.getName().equals(methodName)) { continue; @@ -1567,7 +1275,8 @@ private static Optional findField(Class invokingClass, String fieldNam } /** - * Invokes the given method as a property. If the method with name 'foo()' could not be found, looks for a .getFoo() + * Invokes the given method as a property. If the method with name 'foo()' could + * not be found, looks for a .getFoo() * method. * * @param object @@ -1575,14 +1284,8 @@ private static Optional findField(Class invokingClass, String fieldNam * @return */ public static Object invokeAsGetter(Object object, String methodName) { - // Special cases - // if (methodName.equals("toString")) { - // return object.toString(); - // } - - // System.out.println("MEthod name: '" + methodName + "'"); Class invokingClass = object instanceof Class ? (Class) object : object.getClass(); - // Class invokingClass = object.getClass(); + SpecsLogs.debug(() -> "invokeAsGetter: processing '" + methodName + "' for class '" + invokingClass + "'"); // Check if getter is a field @@ -1630,22 +1333,6 @@ public static Object invokeAsGetter(Object object, String methodName) { throw new RuntimeException( "Could not resolve property '" + methodName + "' for instance of class '" + invokingClass + "'"); - - // // If null, try camelCase getter - // if (invokingMethod == null) { - // String getterName = "get" + methodName.substring(0, 1).toUpperCase() - // + methodName.substring(1, methodName.length()); - // return invoke(object, getterName); - // } - // - // SpecsCheck.checkNotNull(invokingMethod, - // () -> "Could not find method '" + methodName + "' for object " + object); - // - // try { - // return invokingMethod.invoke(object); - // } catch (Exception e) { - // throw new RuntimeException("Error while invoking method '" + methodName + "'", e); - // } } public static List getStaticFields(Class aClass, Class type) { @@ -1679,7 +1366,8 @@ public static void stop() { } /** - * Reads the implementation version that is in the manifest file. Reads property Implementation-Version. + * Reads the implementation version that is in the manifest file. Reads property + * Implementation-Version. * * @return */ @@ -1726,17 +1414,19 @@ public static Throwable getLastCause(Throwable e) { return e; } - /** * Attempts to locate a PowerShell executable available in the system's PATH. *

- * Tries to find "pwsh" (PowerShell Core) first, and if not found, falls back to "powershell" (Windows PowerShell). - * It does so by attempting to execute each candidate with a command that queries the PowerShell version. + * Tries to find "pwsh" (PowerShell Core) first, and if not found, falls back to + * "powershell" (Windows PowerShell). + * It does so by attempting to execute each candidate with a command that + * queries the PowerShell version. * If a suitable executable is found, its name is returned. *

* * @return the name of the PowerShell executable found ("pwsh" or "powershell") - * @throws IllegalStateException if no PowerShell executable is available on the system PATH + * @throws IllegalStateException if no PowerShell executable is available on the + * system PATH */ private static String findPwsh() { // GitHub Windows runners have pwsh in PATH; if not, fall back to powershell.exe @@ -1744,7 +1434,8 @@ private static String findPwsh() { try { Process p = new ProcessBuilder(exe, "-NoLogo", "-NoProfile", "-Command", "$PSVersionTable.PSVersion") .redirectErrorStream(true).start(); - if (p.waitFor() == 0) return exe; + if (p.waitFor() == 0) + return exe; } catch (Exception ignored) { } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/SpecsXml.java b/SpecsUtils/src/pt/up/fe/specs/util/SpecsXml.java index c638c777..2a25ac27 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/SpecsXml.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/SpecsXml.java @@ -76,12 +76,9 @@ public static Document getXmlRoot(InputStream xmlDocument, InputStream schemaDoc // If schema present, validate document if (schemaDocument != null) { var schemaFactory = SchemaFactory.newDefaultInstance(); - // schemaFactory.setErrorHandler(errorHandler); var schema = schemaFactory.newSchema(new StreamSource(schemaDocument)); var validator = schema.newValidator(); validator.validate(new DOMSource(doc)); - // dbFactory.setSchema(schema); - // dbFactory.setValidating(true); } // optional, but recommended @@ -151,13 +148,6 @@ public static String getAttribute(Element element, String tag, String attribute) } private static String getAttribute(NodeList nList, String tag, String attribute) { - // NodeList nList = doc.getElementsByTagName(section); - /* - if (nList == null) { - LoggingUtils.msgInfo("Could not find section '" + section + "'"); - return null; - } - */ if (nList.getLength() == 0) { SpecsLogs.msgInfo("Could not find section '" + tag + "'"); return null; @@ -235,18 +225,6 @@ public static Optional getNodeMaybe(NodeList nodes, String tag) { return Optional.empty(); } - /* - public static List getNodes(NodeList nodeList, String nodeTag) { - - List nodes = new ArrayList<>(); - for (int i = 0; i < nodeList.getLength(); i++) { - nodes.add(nodeList.item(i)); - } - - return nodes; - } - */ - public static Optional getAttribute(Node node, String attrName) { if (node.getNodeType() == Node.ELEMENT_NODE) { return Optional.of(((Element) node).getAttribute(attrName)); @@ -257,7 +235,8 @@ public static Optional getAttribute(Node node, String attrName) { Node attribute = node.getAttributes().getNamedItem(attrName); if (attribute == null) { return Optional.empty(); - // throw new RuntimeException("No attribute with name '"+attrName+"' in node '"+node+"'); + // throw new RuntimeException("No attribute with name '"+attrName+"' in node + // '"+node+"'); } return Optional.of((attribute.getNodeValue())); @@ -278,20 +257,6 @@ public static List getNodes(Node node, String tag) { return children; } - /* - public static String getValue(Document doc, String... tagChain) { - return getValue(doc.getChildNodes(), tagChain); - } - */ - - /** - * The value of the node found by walking the given tag-chain. - * - * @param doc - * @param tagChain - * @return - */ - public static String getText(NodeList nodes, String... tagChain) { NodeList currentNodes = nodes; @@ -331,12 +296,6 @@ public static List getElementChildren(Element element, String tag) { if (tag.equals("*") || tag.equals(childElement.getTagName())) { children.add(childElement); } - - // if (!currentNode.getNodeName().equals(tag)) { - // continue; - // } - // - // children.add(((Element) currentNode).); } return children; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/ArithmeticResult32.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/ArithmeticResult32.java index b45090c8..111ff37e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/ArithmeticResult32.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/ArithmeticResult32.java @@ -20,8 +20,8 @@ public class ArithmeticResult32 { public ArithmeticResult32(int result, int carryOut) { - this.result = result; - this.carryOut = carryOut; + this.result = result; + this.carryOut = carryOut; } public final int result; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/DelaySlotBranchCorrector.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/DelaySlotBranchCorrector.java index 8174c51f..167ba69b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/DelaySlotBranchCorrector.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/DelaySlotBranchCorrector.java @@ -13,34 +13,36 @@ package pt.up.fe.specs.util.asm.processor; /** - * Indicates instructions where the control flow may change in architectures with delay slots. + * Indicates instructions where the control flow may change in architectures + * with delay slots. * * @author Joao Bispo */ public class DelaySlotBranchCorrector { public DelaySlotBranchCorrector() { - this.currentDelaySlot = 0; + this.currentDelaySlot = 0; } public void giveInstruction(boolean isJump, int delaySlots) { - this.wasJump = this.isJump; - this.isJump = isJump(isJump, delaySlots); + this.wasJump = this.isJump; + this.isJump = isJump(isJump, delaySlots); } /** * @return true if the control-flow can change after the given instruction */ public boolean isJumpPoint() { - return this.isJump; + return this.isJump; } /** * - * @return true if the control-flow could have changed between the given instruction and the one before. + * @return true if the control-flow could have changed between the given + * instruction and the one before. */ public boolean wasJumpPoint() { - return this.wasJump; + return this.wasJump; } /** @@ -50,36 +52,35 @@ public boolean wasJumpPoint() { * @return true if the current instruction is a jump */ private boolean isJump(boolean isJump, int delaySlots) { - // If we are currently in a delay slot that is not the last, - // just decrement. - if (this.currentDelaySlot > 1) { - this.currentDelaySlot--; - return false; - } + // If we are currently in a delay slot that is not the last, just decrement. + if (this.currentDelaySlot > 1) { + this.currentDelaySlot--; + return false; + } - // This is the last delay slot. This instruction will jump. - if (this.currentDelaySlot == 1) { - this.currentDelaySlot--; - return true; - } + // This is the last delay slot. This instruction will jump. + if (this.currentDelaySlot == 1) { + this.currentDelaySlot--; + return true; + } - // Check if it is a jump instruction - if (isJump) { - return processJump(delaySlots); - } + // Check if it is a jump instruction + if (isJump) { + return processJump(delaySlots); + } - // It is not a jump instruction - return false; + // It is not a jump instruction + return false; } private boolean processJump(int delaySlots) { - // Check if it has delay slots - if (delaySlots > 0) { - this.currentDelaySlot = delaySlots; - return false; - } + // Check if it has delay slots + if (delaySlots > 0) { + this.currentDelaySlot = delaySlots; + return false; + } - return true; + return true; } private int currentDelaySlot; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/JumpDetector.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/JumpDetector.java index 937ef62e..2267b367 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/JumpDetector.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/JumpDetector.java @@ -28,16 +28,19 @@ public interface JumpDetector { public void giveInstruction(Object instruction); /** - * Detects if there was a jump between the given instruction and the instruction before the given instruction. + * Detects if there was a jump between the given instruction and the instruction + * before the given instruction. * *

- * Even if a branch is not taken (i.e. the given instruction is the instruction in the next address of the - * instruction given before), it counts as a jump. + * Even if a branch is not taken (i.e. the given instruction is the instruction + * in the next address of the instruction given before), it counts as a jump. * *

- * If the method returns true, this means that the given instruction is the start of a BasicBlock. + * If the method returns true, this means that the given instruction is the + * start of a BasicBlock. * - * @return true, if the given instruction is the first instruction after a jump. false otherwise + * @return true, if the given instruction is the first instruction after a jump. + * false otherwise * */ public boolean wasJumpPoint(); @@ -50,28 +53,31 @@ public interface JumpDetector { /** * - * @return true if the last given instruction is a jump and the jump is conditional, false if it is a jump but + * @return true if the last given instruction is a jump and the jump is + * conditional, false if it is a jump but * unconditional. Null if there was no jump. */ public Boolean isConditionalJump(); /** * - * @return true if there was a jump and the jump was conditional, false if it was not. Null if there was no jump. + * @return true if there was a jump and the jump was conditional, false if it + * was not. Null if there was no jump. */ public Boolean wasConditionalJump(); /** * - * @return true if there was a jump and the jump direction was forward, false if it was not. Null if there was no - * jump. + * @return true if there was a jump and the jump direction was forward, false if + * it was not. Null if there was no jump. */ public Boolean wasForwardJump(); /** * - * @return true if there was a conditional jump and the jump was taken. false if it was not. Null if there was no - * jump, or if the jump was not conditional. + * @return true if there was a conditional jump and the jump was taken. false if + * it was not. Null if there was no jump, or if the jump was not + * conditional. */ public Boolean wasBranchTaken(); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterId.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterId.java index 10cd6d2a..c219570a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterId.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterId.java @@ -13,21 +13,13 @@ package pt.up.fe.specs.util.asm.processor; -// import java.io.Serializable; - /** * Identifies registers in the DTool simulator. * * @author Joao Bispo */ -// public interface RegisterId extends Serializable { public interface RegisterId { - /** - * @return the register number used in the DTool simulator corresponding to this particular register. - */ - // int getRegisterNumber(); - /** * * @return the name of the register. diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterTable.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterTable.java index 8c8d658a..5c7d6ba9 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterTable.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterTable.java @@ -30,73 +30,68 @@ public class RegisterTable { public RegisterTable() { - this.registerValues = new HashMap<>(); + this.registerValues = new HashMap<>(); } public Integer put(RegisterId regId, Integer registerValue) { - if (registerValue == null) { - SpecsLogs.getLogger(). - warning("Null input not accepted."); - return null; - } - return this.registerValues.put(regId.getName(), registerValue); + if (registerValue == null) { + SpecsLogs.getLogger().warning("Null input not accepted."); + return null; + } + return this.registerValues.put(regId.getName(), registerValue); } public Integer get(String registerName) { - // Check if it has key - if (this.registerValues.containsKey(registerName)) { - return this.registerValues.get(registerName); - } - - // Check if it is just a single bit of the register - Integer value = getFlagValue(registerName); - if (value != null) { - return value; - } - - SpecsLogs.getLogger(). - warning("Could not find register '" + registerName + "' in table."); - return null; + // Check if it has key + if (this.registerValues.containsKey(registerName)) { + return this.registerValues.get(registerName); + } + + // Check if it is just a single bit of the register + Integer value = getFlagValue(registerName); + if (value != null) { + return value; + } + + SpecsLogs.getLogger().warning("Could not find register '" + registerName + "' in table."); + return null; } private Integer getFlagValue(String registerName) { - if (registerName == null) { - SpecsLogs.getLogger(). - warning("Register name '" + registerName + "' does not represent a valid flag."); - return null; - } - Integer bitPosition = RegisterUtils.decodeFlagBit(registerName); - if (bitPosition == null) { - SpecsLogs.getLogger(). - warning("Could not recognize key: " + registerName); - return null; - } - - String regName = RegisterUtils.decodeFlagName(registerName); - Integer value = this.registerValues.get(regName); - if (value == null) { - SpecsLogs.getLogger(). - warning("Register '" + regName + "' not found."); - return null; - } - - return SpecsBits.getBit(bitPosition, value); + if (registerName == null) { + SpecsLogs.getLogger().warning("Register name '" + registerName + "' does not represent a valid flag."); + return null; + } + Integer bitPosition = RegisterUtils.decodeFlagBit(registerName); + if (bitPosition == null) { + SpecsLogs.getLogger().warning("Could not recognize key: " + registerName); + return null; + } + + String regName = RegisterUtils.decodeFlagName(registerName); + Integer value = this.registerValues.get(regName); + if (value == null) { + SpecsLogs.getLogger().warning("Register '" + regName + "' not found."); + return null; + } + + return SpecsBits.getBit(bitPosition, value); } @Override public String toString() { - StringBuilder builder = new StringBuilder(); - - List keys = new ArrayList<>(this.registerValues.keySet()); - Collections.sort(keys); - for (String key : keys) { - builder.append(key); - builder.append(": "); - builder.append(this.registerValues.get(key)); - builder.append("\n"); - } - - return builder.toString(); + StringBuilder builder = new StringBuilder(); + + List keys = new ArrayList<>(this.registerValues.keySet()); + Collections.sort(keys); + for (String key : keys) { + builder.append(key); + builder.append(": "); + builder.append(this.registerValues.get(key)); + builder.append("\n"); + } + + return builder.toString(); } private final Map registerValues; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterUtils.java index 86cfe6d8..6c800fbd 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/asm/processor/RegisterUtils.java @@ -24,8 +24,7 @@ public class RegisterUtils { public static String buildRegisterBit(RegisterId regId, int bitPosition) { - // return regId.getName() + REGISTER_BIT_OPEN + bitPosition + REGISTER_BIT_CLOSE; - return regId.getName() + RegisterUtils.REGISTER_BIT_START + bitPosition; + return regId.getName() + RegisterUtils.REGISTER_BIT_START + bitPosition; } /** @@ -37,44 +36,34 @@ public static String buildRegisterBit(RegisterId regId, int bitPosition) { * @return */ public static Integer decodeFlagBit(String registerFlagName) { - // int beginIndex = registerFlagName.indexOf(REGISTER_BIT_OPEN); - int beginIndex = registerFlagName.lastIndexOf(RegisterUtils.REGISTER_BIT_START); - // int endIndex = registerFlagName.indexOf(REGISTER_BIT_CLOSE); + int beginIndex = registerFlagName.lastIndexOf(RegisterUtils.REGISTER_BIT_START); - // if(beginIndex == -1 || endIndex == -1) { - if (beginIndex == -1) { - SpecsLogs.getLogger(). - warning("Flag '" + registerFlagName + "' does not represent " - + "a valid flag."); - return null; - } + if (beginIndex == -1) { + SpecsLogs.getLogger().warning("Flag '" + registerFlagName + "' does not represent " + + "a valid flag."); + return null; + } - // String bitNumber = registerFlagName.substring(beginIndex+1, endIndex); - String bitNumber = registerFlagName.substring(beginIndex + 1); - return SpecsStrings.parseInteger(bitNumber); + String bitNumber = registerFlagName.substring(beginIndex + 1); + return SpecsStrings.parseInteger(bitNumber); } /** - *

* Example: if given the string MSR[29], returns MSR. * * @param registerFlagName * @return */ public static String decodeFlagName(String registerFlagName) { - // int beginIndex = registerFlagName.indexOf(REGISTER_BIT_OPEN); - int beginIndex = registerFlagName.lastIndexOf(RegisterUtils.REGISTER_BIT_START); - if (beginIndex == -1) { - SpecsLogs.getLogger(). - warning("Flag '" + registerFlagName + "' does not represent " - + "a valid flag."); - return null; - } + int beginIndex = registerFlagName.lastIndexOf(RegisterUtils.REGISTER_BIT_START); + if (beginIndex == -1) { + SpecsLogs.getLogger().warning("Flag '" + registerFlagName + "' does not represent " + + "a valid flag."); + return null; + } - return registerFlagName.substring(0, beginIndex); + return registerFlagName.substring(0, beginIndex); } private static final String REGISTER_BIT_START = "_"; - // private static final String REGISTER_BIT_OPEN = "["; - // private static final String REGISTER_BIT_CLOSE = "]"; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiConsumerClassMap.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiConsumerClassMap.java index 3baeeed8..edc50549 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiConsumerClassMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiConsumerClassMap.java @@ -22,7 +22,8 @@ import pt.up.fe.specs.util.utilities.ClassMapper; /** - * Maps a class to a BiConsumer that receives an instance of that class being used as key and other object. + * Maps a class to a BiConsumer that receives an instance of that class being + * used as key and other object. * * @author JoaoBispo * @@ -32,19 +33,15 @@ public class BiConsumerClassMap { private final Map, BiConsumer> map; - // private final boolean supportInterfaces; private final boolean ignoreNotFound; private final ClassMapper classMapper; - // private static final boolean DEFAULT_SUPPORT_INTERFACES = true; - public BiConsumerClassMap() { this(false, new ClassMapper()); } private BiConsumerClassMap(boolean ignoreNotFound, ClassMapper classMapper) { this.map = new HashMap<>(); - // this.supportInterfaces = supportInterfaces; this.ignoreNotFound = ignoreNotFound; this.classMapper = classMapper; } @@ -62,7 +59,8 @@ public static BiConsumerClassMap newInstance(boolean ignoreNotFound * Associates the specified value with the specified key. * *

- * The key is always a class of a type that is a subtype of the type in the value. + * The key is always a class of a type that is a subtype of the type in the + * value. *

* Example:
* - put(Subclass.class, usesSuperClass), ok
@@ -74,14 +72,6 @@ public static BiConsumerClassMap newInstance(boolean ignoreNotFound */ public void put(Class aClass, BiConsumer value) { - - // if (!this.supportInterfaces) { - // if (aClass.isInterface()) { - // SpecsLogs.warn("Support for interfaces is disabled, map is unchanged"); - // return; - // } - // } - this.map.put(aClass, value); this.classMapper.add(aClass); } @@ -100,30 +90,6 @@ private BiConsumer get(Class key) { SpecsCheck.checkNotNull(function, () -> "There should be a mapping for " + mappedClass.get() + ", verify"); return (BiConsumer) function; - - // Class currentKey = key; - // - // while (currentKey != null) { - // // Test key - // BiConsumer result = this.map.get(currentKey); - // if (result != null) { - // return (BiConsumer) result; - // } - // - // if (this.supportInterfaces) { - // for (Class interf : currentKey.getInterfaces()) { - // result = this.map.get(interf); - // if (result != null) { - // return (BiConsumer) result; - // } - // } - // } - // - // currentKey = currentKey.getSuperclass(); - // } - // - // return null; - // } @SuppressWarnings("unchecked") @@ -132,8 +98,8 @@ private BiConsumer get(TK key) { } /** - * Calls the BiConsumer.accept associated with class of the value t, or throws an Exception if no BiConsumer could - * be found in the map. + * Calls the BiConsumer.accept associated with class of the value t, or throws + * an Exception if no BiConsumer could be found in the map. * * @param t * @param u diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiFunctionClassMap.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiFunctionClassMap.java index 145c7bc3..10e138f9 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiFunctionClassMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/BiFunctionClassMap.java @@ -22,7 +22,8 @@ import pt.up.fe.specs.util.utilities.ClassMapper; /** - * Maps a class to a BiFunction that receives an instance of that class being used as key and other object. + * Maps a class to a BiFunction that receives an instance of that class being + * used as key and other object. * * @author JoaoBispo * @@ -32,7 +33,6 @@ public class BiFunctionClassMap { private final Map, BiFunction> map; - // private final boolean supportInterfaces; private final ClassMapper classMapper; public BiFunctionClassMap() { @@ -45,7 +45,8 @@ public BiFunctionClassMap() { * Associates the specified value with the specified key. * *

- * The key is always a class of a type that is a subtype of the type in the value. + * The key is always a class of a type that is a subtype of the type in the + * value. *

* Example:
* - put(Subclass.class, usesSuperClass), ok
@@ -57,14 +58,6 @@ public BiFunctionClassMap() { */ public void put(Class aClass, BiFunction value) { - - // if (!this.supportInterfaces) { - // if (aClass.isInterface()) { - // SpecsLogs.warn("Support for interfaces is disabled, map is unchanged"); - // return; - // } - // } - this.map.put(aClass, value); classMapper.add(aClass); } @@ -83,30 +76,6 @@ private BiFunction get(Class key) { SpecsCheck.checkNotNull(function, () -> "There should be a mapping for " + mappedClass.get() + ", verify"); return (BiFunction) function; - - // Class currentKey = key; - // - // while (currentKey != null) { - // // Test key - // BiFunction result = this.map.get(currentKey); - // if (result != null) { - // return (BiFunction) result; - // } - // - // if (this.supportInterfaces) { - // for (Class interf : currentKey.getInterfaces()) { - // result = this.map.get(interf); - // if (result != null) { - // return (BiFunction) result; - // } - // } - // } - // - // currentKey = currentKey.getSuperclass(); - // } - // - // return null; - } @SuppressWarnings("unchecked") @@ -115,8 +84,8 @@ private BiFunction get(TK key) { } /** - * Calls the BiFunction.accept associated with class of the value t, or throws an Exception if no BiFunction could - * be found in the map. + * Calls the BiFunction.accept associated with class of the value t, or throws + * an Exception if no BiFunction could be found in the map. * * @param t * @param u diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassMap.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassMap.java index 8c9cee88..61ba53b2 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassMap.java @@ -28,8 +28,9 @@ * *

* Use this class if you want to:
- * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a value mapped to class Number will be - * returned if the key is the class Integer and there is no explicit mapping for the class Integer).
+ * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a + * value mapped to class Number will be returned if the key is the class Integer + * and there is no explicit mapping for the class Integer).
* * @author JoaoBispo * @@ -39,7 +40,7 @@ public class ClassMap { private final Map, V> map; - // private final boolean supportInterfaces; + // Can be null private final V defaultValue; @@ -57,7 +58,6 @@ private ClassMap(Map, V> map, V defaultValue, ClassMapper classMapper) { this.map = map; - // this.supportInterfaces = supportInterfaces; this.defaultValue = defaultValue; this.classMapper = classMapper; } @@ -70,7 +70,8 @@ public ClassMap copy() { * Associates the specified value with the specified key. * *

- * The key is always a class of a type that is a subtype of the type in the value. + * The key is always a class of a type that is a subtype of the type in the + * value. *

* Example:
* - put(Subclass.class, usesSuperClass), ok
@@ -82,50 +83,10 @@ public ClassMap copy() { */ public V put(Class aClass, V value) { - - // if (!this.supportInterfaces) { - // if (aClass.isInterface()) { - // SpecsLogs.warn("Support for interfaces is disabled, map is unchanged"); - // return null; - // } - // } - classMapper.add(aClass); return this.map.put(aClass, value); } - /** - * - * @param key - * @return the class that will be used to access the map, based on the given key - */ - /* - public Optional> getEquivalentKey(Class key) { - Class currentKey = key; - - while (currentKey != null) { - // Test key - V result = this.map.get(currentKey); - if (result != null) { - return Optional.of(currentKey); - } - - if (this.supportInterfaces) { - for (Class interf : currentKey.getInterfaces()) { - result = this.map.get(interf); - if (result != null) { - return Optional.of(interf); - } - } - } - - currentKey = currentKey.getSuperclass(); - } - - return Optional.empty(); - } - */ - public Optional tryGet(Class key) { // Map given class to a class supported by this instance var mappedClass = classMapper.map(key); @@ -136,30 +97,6 @@ public Optional tryGet(Class key) { return Optional.of(result); } - /* - Class currentKey = key; - - while (currentKey != null) { - // Test key - V result = this.map.get(currentKey); - if (result != null) { - return Optional.of(result); - } - - if (this.supportInterfaces) { - // System.out.println("INTERFACES OF " + currentKey + ": " + - // Arrays.toString(currentKey.getInterfaces())); - for (Class interf : currentKey.getInterfaces()) { - result = this.map.get(interf); - if (result != null) { - return Optional.of(result); - } - } - } - - currentKey = currentKey.getSuperclass(); - } - */ // Return default value if present if (this.defaultValue != null) { return Optional.of(this.defaultValue); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassSet.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassSet.java index e8cde7cc..c3d6bc7b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassSet.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/ClassSet.java @@ -22,8 +22,9 @@ * *

* Use this class if you want to:
- * 1) Use classes as elements of a set and want the set to respect the hierarchy (e.g., contains will return true for an - * Integer instance if the class Number is in the set)
+ * 1) Use classes as elements of a set and want the set to respect the hierarchy + * (e.g., contains will return true for an Integer instance if the class Number + * is in the set)
* * @author JoaoBispo * @@ -73,12 +74,12 @@ public boolean add(Class e) { } /** - * Returns true if this set contains the specified element. More formally, returns true if and - * only if this set contains an element e such that + * Returns true if this set contains the specified element. More + * formally, returns true if and only if this set contains an element + * e such that * (o==null ? e==null : o.equals(e)). * - * @param o - * element whose presence in this set is to be tested + * @param o element whose presence in this set is to be tested * @return true if this set contains the specified element */ public boolean contains(Class aClass) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/FunctionClassMap.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/FunctionClassMap.java index 3dcee696..7550ac35 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/FunctionClassMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/FunctionClassMap.java @@ -24,14 +24,17 @@ import pt.up.fe.specs.util.utilities.ClassMapper; /** - * Maps a class T or subtype of T to a Function that accepts one argument T and produces a result R. + * Maps a class T or subtype of T to a Function that accepts one argument T and + * produces a result R. * *

* Use this class if you want to:
- * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a value mapped to class Number will be - * returned if the key is the class Integer and there is no explicit mapping for the class Integer).
- * 2) When adding a value, you want to have access to the methods of the subtype of the key (e.g., if T is Number, you - * can do .put(Integer.class, integer -> integer.compareTo()) ). + * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a + * value mapped to class Number will be returned if the key is the class Integer + * and there is no explicit mapping for the class Integer).
+ * 2) When adding a value, you want to have access to the methods of the subtype + * of the key (e.g., if T is Number, you can do .put(Integer.class, integer -> + * integer.compareTo()) ). * * @author JoaoBispo * @@ -41,7 +44,7 @@ public class FunctionClassMap { private final Map, Function> map; - // private final boolean supportInterfaces; + // Can be null private R defaultValue; // Can be null @@ -63,15 +66,11 @@ public FunctionClassMap(Function defaultFunction) { @SuppressWarnings("unchecked") public FunctionClassMap(FunctionClassMap functionClassMap) { - // this(functionClassMap.map, functionClassMap.supportInterfaces, functionClassMap.defaultValue, - // functionClassMap.defaultFunction); - this.map = new HashMap<>(); for (var keyPair : functionClassMap.map.entrySet()) { this.map.put((Class) keyPair.getKey(), (Function) keyPair.getValue()); } - // this.supportInterfaces = functionClassMap.supportInterfaces; this.defaultValue = functionClassMap.defaultValue; this.defaultFunction = functionClassMap.defaultFunction; this.classMapper = new ClassMapper(functionClassMap.classMapper); @@ -84,7 +83,6 @@ private FunctionClassMap(Map, Function FunctionClassMap(Map, Function - * The key is always a class of a type that is a subtype of the type in the value. + * The key is always a class of a type that is a subtype of the type in the + * value. *

* Example:
* - put(Subclass.class, usesSuperClass), ok
@@ -107,17 +106,8 @@ private FunctionClassMap(Map, Function void put(Class aClass, Function value) { - - // if (!this.supportInterfaces) { - // if (aClass.isInterface()) { - // SpecsLogs.warn("Support for interfaces is disabled, map is unchanged"); - // return; - // } - // } - this.map.put(aClass, value); this.classMapper.add(aClass); - } @SuppressWarnings("unchecked") @@ -134,31 +124,6 @@ private Optional> get(Class key) { SpecsCheck.checkNotNull(function, () -> "There should be a mapping for " + mappedClass.get() + ", verify"); return Optional.of((Function) function); - - /* - Class currentKey = key; - - while (currentKey != null) { - // Test key - Function result = this.map.get(currentKey); - if (result != null) { - return Optional.of((Function) result); - } - - if (this.supportInterfaces) { - for (Class interf : currentKey.getInterfaces()) { - result = this.map.get(interf); - if (result != null) { - return Optional.of((Function) result); - } - } - } - - currentKey = currentKey.getSuperclass(); - } - - return Optional.empty(); - */ } @SuppressWarnings("unchecked") @@ -168,7 +133,8 @@ private Optional> get(TK key) { } /** - * Calls the Function.apply associated with class of the value t, or Optional.empty if no mapping could be found. + * Calls the Function.apply associated with class of the value t, or + * Optional.empty if no mapping could be found. * * @param t */ @@ -185,8 +151,8 @@ public Optional applyTry(T t) { } /** - * Calls the Function.apply associated with class of the value t, or throws an Exception if no mapping could be - * found. + * Calls the Function.apply associated with class of the value t, or throws an + * Exception if no mapping could be found. * * @param t */ @@ -206,14 +172,6 @@ public R apply(T t) { throw new NotImplementedException("Function not defined for class '" + t.getClass() + "'"); - /* - if (function == null) { - throw new NotImplementedException("BiConsumer not defined for class '" - + t.getClass() + "'"); - } - - return function.apply(t); - */ } private Optional defaultValue(T t) { @@ -239,13 +197,11 @@ private Optional defaultValue(T t) { public void setDefaultValue(R defaultValue) { this.defaultFunction = null; this.defaultValue = defaultValue; - // return new FunctionClassMap<>(this.map, defaultValue, null, this.classMapper); } public void setDefaultFunction(Function defaultFunction) { this.defaultFunction = defaultFunction; this.defaultValue = null; - // return new FunctionClassMap<>(this.map, null, defaultFunction, this.classMapper); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/classmap/MultiFunction.java b/SpecsUtils/src/pt/up/fe/specs/util/classmap/MultiFunction.java index bcc33cf2..889bf141 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/classmap/MultiFunction.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/classmap/MultiFunction.java @@ -25,14 +25,17 @@ import pt.up.fe.specs.util.utilities.ClassMapper; /** - * Maps a class T or subtype of T to a Function that accepts one argument T and produces a result R. + * Maps a class T or subtype of T to a Function that accepts one argument T and + * produces a result R. * *

* Use this class if you want to:
- * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a value mapped to class Number will be - * returned if the key is the class Integer and there is no explicit mapping for the class Integer).
- * 2) When adding a value, you want to have access to the methods of the subtype of the key (e.g., if T is Number, you - * can do .put(Integer.class, integer -> integer.compareTo()) ). + * 1) Use classes as keys and want the map to respect the hierarchy (e.g., a + * value mapped to class Number will be returned if the key is the class Integer + * and there is no explicit mapping for the class Integer).
+ * 2) When adding a value, you want to have access to the methods of the subtype + * of the key (e.g., if T is Number, you can do + * put(Integer.class, integer -> integer.compareTo()) ). * * @author JoaoBispo * @@ -42,7 +45,7 @@ public class MultiFunction { private final Map, BiFunction, ? extends T, ? extends R>> map; - // private final boolean supportInterfaces; + // Can be null private final R defaultValue; private final ClassMapper classMapper; @@ -54,10 +57,6 @@ public MultiFunction() { this(new HashMap<>(), null, null, new ClassMapper()); } - // public MultiFunction(ER defaultValue) { - // this(new HashMap<>(), true, defaultValue, null); - // } - public MultiFunction(Function defaultFunction) { this((bi, in) -> defaultFunction.apply(in)); } @@ -76,7 +75,6 @@ private > MultiFunction( "Both defaults cannot be different than null at the same time"); this.map = map; - // this.supportInterfaces = supportInterfaces; this.defaultValue = defaultValue; this.defaultFunction = (BiFunction, T, R>) defaultFunction; this.classMapper = classMapper; @@ -86,7 +84,8 @@ private > MultiFunction( * Associates the specified value with the specified key. * *

- * The key is always a class of a type that is a subtype of the type in the value. + * The key is always a class of a type that is a subtype of the type in the + * value. *

* Example:
* - put(Subclass.class, usesSuperClass), ok
@@ -98,14 +97,6 @@ private > MultiFunction( */ public , ET extends T, K extends ET> void put(Class aClass, BiFunction value) { - - // if (!this.supportInterfaces) { - // if (aClass.isInterface()) { - // SpecsLogs.warn("Support for interfaces is disabled, map is unchanged"); - // return; - // } - // } - this.map.put(aClass, value); this.classMapper.add(aClass); } @@ -114,7 +105,6 @@ public void put(Class aClass, Function value) { BiFunction, ET, R> biFunction = (bi, in) -> value.apply(in); - // BiFunction, ET, R> biFunction = convert(value); put(aClass, biFunction); } @@ -132,30 +122,6 @@ private Optional, T, R>> get(Class SpecsCheck.checkNotNull(function, () -> "There should be a mapping for " + mappedClass.get() + ", verify"); return Optional.of((BiFunction, T, R>) function); - /* - Class currentKey = key; - - while (currentKey != null) { - // Test key - BiFunction, ? extends T, ? extends R> result = this.map.get(currentKey); - if (result != null) { - return Optional.of((BiFunction, T, R>) result); - } - - if (this.supportInterfaces) { - for (Class interf : currentKey.getInterfaces()) { - result = this.map.get(interf); - if (result != null) { - return Optional.of((BiFunction, T, R>) result); - } - } - } - - currentKey = currentKey.getSuperclass(); - } - - return Optional.empty(); - */ } @SuppressWarnings("unchecked") @@ -164,8 +130,8 @@ private Optional, T, R>> get(TK ke } /** - * Calls the Function.apply associated with class of the value t, or throws an Exception if no mapping could be - * found. + * Calls the Function.apply associated with class of the value t, or throws an + * Exception if no mapping could be found. * * @param t */ @@ -185,14 +151,6 @@ public R apply(T t) { throw new NotImplementedException("Function not defined for class '" + t.getClass() + "'"); - /* - if (function == null) { - throw new NotImplementedException("BiConsumer not defined for class '" - + t.getClass() + "'"); - } - - return function.apply(t); - */ } private Optional defaultValue(T t) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMap.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMap.java index 4c50a72f..782e97b4 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMap.java @@ -65,7 +65,8 @@ public Set keys() { * Adds 1 to the count of this element. * * @param element - * @return the current number of added elements. If it is the first time we are adding an element, returns 1 + * @return the current number of added elements. If it is the first time we are + * adding an element, returns 1 */ public Integer add(T element) { return add(element, 1); @@ -88,8 +89,7 @@ public Integer add(T element, int incrementValue) { if (value == null) { value = 0; } - - // int incrementValue = 1; + ; value += incrementValue; this.accMap.put(element, value); @@ -132,8 +132,6 @@ public boolean remove(T element, int incrementValue) { return false; } - // int incrementValue = 1; - value -= incrementValue; this.accMap.put(element, value); this.accumulator -= incrementValue; @@ -146,12 +144,6 @@ public boolean remove(T element, int incrementValue) { return true; } - /** - * private void updateTable(T element, Integer value) { - * - * } - */ - /** * * @param element @@ -163,7 +155,6 @@ public int getCount(T element) { return 0; } - // return accMap.get(element); return count; } @@ -184,17 +175,7 @@ public double getRatio(T element) { * @param histogram * @return */ - // public int getSum() { public long getSum() { - /* - int accumulator = 0; - for(T key : accMap.keySet()) { - accumulator += accMap.get(key); - } - - return accumulator; - * - */ return this.accumulator; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMapL.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMapL.java index 315a33eb..3bf99629 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMapL.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/AccumulatorMapL.java @@ -56,7 +56,8 @@ public AccumulatorMapL getUnmodifiableMap() { * Adds 1 to the count of this element. * * @param element - * @return the current number of added elements. If it is the first time we are adding an element, returns 1 + * @return the current number of added elements. If it is the first time we are + * adding an element, returns 1 */ public Long add(T element) { return add(element, 1); @@ -80,8 +81,6 @@ public Long add(T element, long incrementValue) { value = 0l; } - // int incrementValue = 1; - value += incrementValue; this.accMap.put(element, value); this.accumulator += incrementValue; @@ -105,8 +104,6 @@ public boolean remove(T element, int incrementValue) { return false; } - // int incrementValue = 1; - value -= incrementValue; this.accMap.put(element, value); this.accumulator -= incrementValue; @@ -125,14 +122,14 @@ public long getCount(T element) { return 0l; } - // return accMap.get(element); return count; } /** * * @param element - * @return the ratio of the given element in relation to the other elements of the table. + * @return the ratio of the given element in relation to the other elements of + * the table. */ public double getRatio(T element) { Long count = getCount(element); @@ -146,17 +143,7 @@ public double getRatio(T element) { * @param histogram * @return */ - // public int getSum() { public long getSum() { - /* - int accumulator = 0; - for(T key : accMap.keySet()) { - accumulator += accMap.get(key); - } - - return accumulator; - * - */ return this.accumulator; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/Attributes.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/Attributes.java index 4f4bcef8..11f055c9 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/Attributes.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/Attributes.java @@ -1,6 +1,5 @@ package pt.up.fe.specs.util.collections; - import pt.up.fe.specs.util.SpecsCollections; import java.util.*; @@ -23,13 +22,13 @@ default boolean hasAttribute(String attribute) { return getAttributes().contains(attribute); } - /** * @param attribute - * @returns the value of an attribute, or throws exception if attribute is not available. - *

- * To see all the attributes iterate the list provided by - * {@link Attributes#getAttributes()} + * @returns the value of an attribute, or throws exception if attribute is not + * available. + *

+ * To see all the attributes iterate the list provided by + * {@link Attributes#getAttributes()} */ Object getObject(String attribute); @@ -38,11 +37,11 @@ default boolean hasAttribute(String attribute) { * * @param attribute * @param value - * @returns the previous value assigned to the given attribute, or null if value was assigned before + * @returns the previous value assigned to the given attribute, or null if value + * was assigned before */ Object putObject(String attribute, Object value); - /** * Convenience method which casts the attribute to the given class. * @@ -56,7 +55,8 @@ default T getObject(String attribute, Class attributeClass) { } /** - * Attempts to retrieve and convert the value of the corresponding attribute into a list. + * Attempts to retrieve and convert the value of the corresponding attribute + * into a list. *

* Currently, supports values which are arrays or a Collection. * @@ -77,7 +77,6 @@ default List getObjectAsList(String attribute) { throw new RuntimeException("Could not convert object of class '" + value.getClass() + "' in a list"); } - /** * Convenience method which casts the elements of the list to the given class. * @@ -92,8 +91,8 @@ default List getObjectAsList(String attribute, Class elementClass) { /** * @param attribute - * @return the value of the attribute wrapped around an Optional, or Optional.empty() if there is no value for the - * given attribute + * @return the value of the attribute wrapped around an Optional, or + * Optional.empty() if there is no value for the given attribute */ default Optional getOptionalObject(String attribute) { if (!hasAttribute(attribute)) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/BiMap.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/BiMap.java index 9967479f..c6c19824 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/BiMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/BiMap.java @@ -28,89 +28,56 @@ public class BiMap { private int maxX; public BiMap() { - this.bimap = new HashMap<>(); - this.maxY = 0; - this.maxX = 0; + this.bimap = new HashMap<>(); + this.maxY = 0; + this.maxX = 0; } public void put(int x, int y, T value) { - Map yMap = this.bimap.get(x); - if (yMap == null) { - yMap = new HashMap<>(); - this.bimap.put(x, yMap); - } + Map yMap = this.bimap.get(x); + if (yMap == null) { + yMap = new HashMap<>(); + this.bimap.put(x, yMap); + } - yMap.put(y, value); + yMap.put(y, value); - this.maxX = Math.max(this.maxX, x + 1); - this.maxY = Math.max(this.maxY, y + 1); + this.maxX = Math.max(this.maxX, x + 1); + this.maxY = Math.max(this.maxY, y + 1); } public T get(int x, int y) { - Map yMap = this.bimap.get(x); - if (yMap == null) { - return null; - } + Map yMap = this.bimap.get(x); + if (yMap == null) { + return null; + } - return yMap.get(y); + return yMap.get(y); } public String getBoolString(int x, int y) { - T value = get(x, y); - if (value == null) { - return "-"; - } + T value = get(x, y); + if (value == null) { + return "-"; + } - return "x"; + return "x"; } - /* - public void put(int x, int y, T value) { - // Y is the first list - List xList = null; - if(y < bimap.size()) { - xList = bimap.get(y); - } - - if(xList == null) { - xList = new ArrayList(); - bimap.add(y, xList); - } - - xList.add(value); - } - - public T get(int x, int y) { - // Y is the first list - List xList = null; - if(y < bimap.size()) { - xList = bimap.get(y); - } - - if(xList == null) { - return null; - } - - if(x >= xList.size()) { - return null; - } - return xList.get(x); - } - */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); - - for (int y = 0; y < this.maxY; y++) { - if (this.maxX > 0) { - builder.append(getBoolString(0, y)); - } - for (int x = 1; x < this.maxX; x++) { - builder.append(getBoolString(x, y)); - } - builder.append("\n"); - } - return builder.toString(); + StringBuilder builder = new StringBuilder(); + + for (int y = 0; y < this.maxY; y++) { + if (this.maxX > 0) { + builder.append(getBoolString(0, y)); + } + for (int x = 1; x < this.maxX; x++) { + builder.append(getBoolString(x, y)); + } + builder.append("\n"); + } + return builder.toString(); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/HashSetString.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/HashSetString.java index cf69d00a..4608ee07 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/HashSetString.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/HashSetString.java @@ -18,9 +18,6 @@ public class HashSetString extends HashSet { - /** - * - */ private static final long serialVersionUID = 1L; public HashSetString() { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/MultiMap.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/MultiMap.java index bad654d2..fac099a7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/MultiMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/MultiMap.java @@ -35,16 +35,8 @@ public interface MultiMapProvider { Map> newInstance(); } - // --------------------------------------------------------------------- attributes - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - - ---------- static - - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - ----------- dynamic - private final Map> map; - // ----------------------------------------------------------------- public_Methods - // ---------- - - - - - - - - - - - - - - - - - - - - - - - ----------- constructor - public MultiMap() { this.map = new HashMap<>(); } @@ -57,26 +49,13 @@ public MultiMap(MultiMapProvider mapProvider) { this.map = mapProvider.newInstance(); } - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - - ---------- static - - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - ----------- dynamic - /** * Returns the values associated to the parameter key. * - * @param key - * The key the user wants the values of. + * @param key The key the user wants the values of. * @return the values associated to the parameter key. */ public List get(K key) { - // List values = this.map.get(key); - // if (values == null) { - // values = new ArrayList<>(); - // this.map.put(key, values); - // } - // - // return values; - //// return Collections.unmodifiableList(this.map.getOrDefault(key, Collections.emptyList())); return this.map.getOrDefault(key, Collections.emptyList()); } @@ -98,19 +77,12 @@ private List getPrivate(K key) { /** * Adds the given value to the key. - * - * @param key - * the key the user wants to attribute a value to. - * @param value - * the value the user wants to attribute to the key. + * + * @param key the key the user wants to attribute a value to. + * @param value the value the user wants to attribute to the key. */ public void put(K key, V value) { List values = getPrivate(key); - // List values = this.map.get(key); - // if (values == null) { - // values = new ArrayList<>(); - // this.map.put(key, values); - // } values.add(value); } @@ -122,10 +94,9 @@ public void add(K key, V value) { /** * Replaces the current value mapped to the given key with the given values * - * @param key - * the key the user wants to attribute a values to. - * @param values - * a List containing all the values the user wants to attribute to the key. + * @param key the key the user wants to attribute a values to. + * @param values a List containing all the values the user wants to attribute to + * the key. */ public void put(K key, List values) { this.map.put(key, new ArrayList<>(values)); @@ -153,32 +124,6 @@ public void addAll(K key, List values) { @Override public String toString() { return map.toString(); - /* - StringBuilder builder = new StringBuilder(); - - boolean isFirst = true; - for (K key : this.map.keySet()) { - if (isFirst) { - isFirst = false; - } else { - builder.append("; "); - } - - List values = this.map.get(key); - builder.append(key).append(": "); - if (values.isEmpty()) { - builder.append("(empty)"); - } else { - builder.append(values.get(0)); - } - - for (int i = 1; i < values.size(); i++) { - builder.append(", ").append(values.get(i)); - } - } - - return builder.toString(); - */ } public Map> getMap() { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopeNode.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopeNode.java index d89f7dc0..c6d35727 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopeNode.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopeNode.java @@ -37,62 +37,62 @@ class ScopeNode { * */ public ScopeNode() { - this.childScopes = new LinkedHashMap<>(); - this.symbols = new LinkedHashMap<>(); + this.childScopes = new LinkedHashMap<>(); + this.symbols = new LinkedHashMap<>(); } /** * @return the symbols */ public Map getSymbols() { - return this.symbols; + return this.symbols; } public List getScopes() { - return new ArrayList<>(this.childScopes.keySet()); + return new ArrayList<>(this.childScopes.keySet()); } public V getSymbol(String... key) { - return getSymbol(Arrays.asList(key)); + return getSymbol(Arrays.asList(key)); } public V getSymbol(List key) { - if (key.isEmpty()) { - return null; - } + if (key.isEmpty()) { + return null; + } - if (key.size() == 1) { - return this.symbols.get(key.get(0)); + if (key.size() == 1) { + return this.symbols.get(key.get(0)); - } + } - ScopeNode scopeChild = this.childScopes.get(key.get(0)); - if (scopeChild == null) { - return null; - } + ScopeNode scopeChild = this.childScopes.get(key.get(0)); + if (scopeChild == null) { + return null; + } - return scopeChild.getSymbol(key.subList(1, key.size())); + return scopeChild.getSymbol(key.subList(1, key.size())); } public void addSymbol(String name, V symbol) { - V previousSymbol = this.symbols.put(name, symbol); - if (previousSymbol != null) { - SpecsLogs.msgLib("Replacing symbol with name '" + name + "'. Previous content: '" + previousSymbol - + "'. Current content: '" + symbol + "'"); - } + V previousSymbol = this.symbols.put(name, symbol); + if (previousSymbol != null) { + SpecsLogs.msgLib("Replacing symbol with name '" + name + "'. Previous content: '" + previousSymbol + + "'. Current content: '" + symbol + "'"); + } } public void addSymbol(List scope, String name, V symbol) { - if (name == null) { - throw new RuntimeException("'null' is not allowed as a name"); - } - - if (scope == null) { - scope = Collections.emptyList(); - } - List key = new ArrayList<>(scope); - key.add(name); - addSymbol(key, symbol); + if (name == null) { + throw new RuntimeException("'null' is not allowed as a name"); + } + + if (scope == null) { + scope = Collections.emptyList(); + } + List key = new ArrayList<>(scope); + key.add(name); + addSymbol(key, symbol); } /** @@ -100,82 +100,83 @@ public void addSymbol(List scope, String name, V symbol) { * @param symbol */ public void addSymbol(List key, V symbol) { - if (key.isEmpty()) { - SpecsLogs.warn("Empty key, symbol '" + symbol + "' not inserted."); - return; - } - - if (key.size() == 1) { - addSymbol(key.get(0), symbol); - return; - } - - String scopeName = key.get(0); - ScopeNode childScope = this.childScopes.get(scopeName); - if (childScope == null) { - childScope = new ScopeNode<>(); - this.childScopes.put(scopeName, childScope); - } - - childScope.addSymbol(key.subList(1, key.size()), symbol); + if (key.isEmpty()) { + SpecsLogs.warn("Empty key, symbol '" + symbol + "' not inserted."); + return; + } + + if (key.size() == 1) { + addSymbol(key.get(0), symbol); + return; + } + + String scopeName = key.get(0); + ScopeNode childScope = this.childScopes.get(scopeName); + if (childScope == null) { + childScope = new ScopeNode<>(); + this.childScopes.put(scopeName, childScope); + } + + childScope.addSymbol(key.subList(1, key.size()), symbol); } /** * @return */ public List> getKeys() { - return getKeys(new ArrayList<>()); + return getKeys(new ArrayList<>()); } private List> getKeys(List currentScope) { - List> keys = new ArrayList<>(); - - // Add current node keys - for (String key : this.symbols.keySet()) { - List newKey = new ArrayList<>(currentScope); - newKey.add(key); - keys.add(newKey); - } - - // Add node keys from scopes - for (String scope : this.childScopes.keySet()) { - List newScope = new ArrayList<>(currentScope); - newScope.add(scope); - keys.addAll(this.childScopes.get(scope).getKeys(newScope)); - } - - return keys; + List> keys = new ArrayList<>(); + + // Add current node keys + for (String key : this.symbols.keySet()) { + List newKey = new ArrayList<>(currentScope); + newKey.add(key); + keys.add(newKey); + } + + // Add node keys from scopes + for (String scope : this.childScopes.keySet()) { + List newScope = new ArrayList<>(currentScope); + newScope.add(scope); + keys.addAll(this.childScopes.get(scope).getKeys(newScope)); + } + + return keys; } public ScopeNode getScopeNode(List scope) { - if (scope.isEmpty()) { - SpecsLogs.warn("Scope is empty."); - return null; - } - - String scopeName = scope.get(0); - ScopeNode childScope = this.childScopes.get(scopeName); - if (childScope == null) { - return null; - } - - if (scope.size() == 1) { - return childScope; - } - - return childScope.getScopeNode(scope.subList(1, scope.size())); + if (scope.isEmpty()) { + SpecsLogs.warn("Scope is empty."); + return null; + } + + String scopeName = scope.get(0); + ScopeNode childScope = this.childScopes.get(scopeName); + if (childScope == null) { + return null; + } + + if (scope.size() == 1) { + return childScope; + } + + return childScope.getScopeNode(scope.subList(1, scope.size())); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override public String toString() { - // return "Symbols:\n"+symbols + "\nChildScopes:\n" + childScopes; - return this.symbols + "\n" + this.childScopes; + return this.symbols + "\n" + this.childScopes; } public ScopeNode getScope(String scope) { - return this.childScopes.get(scope); + return this.childScopes.get(scope); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopedMap.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopedMap.java index 52536922..eadbe4d5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopedMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/ScopedMap.java @@ -38,13 +38,13 @@ public class ScopedMap { * */ public ScopedMap() { - this.rootNode = new ScopeNode<>(); + this.rootNode = new ScopeNode<>(); - this.firstScope = null; + this.firstScope = null; } public static ScopedMap newInstance() { - return new ScopedMap<>(); + return new ScopedMap<>(); } /** @@ -54,41 +54,43 @@ public static ScopedMap newInstance() { * @return */ public ScopedMap getSymbolMap(String... scope) { - return getSymbolMap(Arrays.asList(scope)); + return getSymbolMap(Arrays.asList(scope)); } /** - * Builds a new SymbolMap with the variables of the specified scope, but without preserving the original scope. + * Builds a new SymbolMap with the variables of the specified scope, but without + * preserving the original scope. * *

- * For instance, if a scope 'x' is asked, the scopes in the returned SymbolMap will start after 'x'. + * For instance, if a scope 'x' is asked, the scopes in the returned SymbolMap + * will start after 'x'. * * @param scope * @return */ public ScopedMap getSymbolMap(List scope) { - ScopedMap scopedVariables = new ScopedMap<>(); + ScopedMap scopedVariables = new ScopedMap<>(); - ScopeNode scopeNode = getScopeNode(scope); - if (scopeNode == null) { - return scopedVariables; - } + ScopeNode scopeNode = getScopeNode(scope); + if (scopeNode == null) { + return scopedVariables; + } - scopedVariables.addSymbols(scopeNode); - return scopedVariables; + scopedVariables.addSymbols(scopeNode); + return scopedVariables; } /** * @param scopeNode */ private void addSymbols(ScopeNode scopeNode) { - for (List key : scopeNode.getKeys()) { - V symbol = scopeNode.getSymbol(key); - List keyScope = key.subList(0, key.size() - 1); - String name = key.get(key.size() - 1); + for (List key : scopeNode.getKeys()) { + V symbol = scopeNode.getSymbol(key); + List keyScope = key.subList(0, key.size() - 1); + String name = key.get(key.size() - 1); - addSymbol(keyScope, name, symbol); - } + addSymbol(keyScope, name, symbol); + } } /** @@ -97,7 +99,7 @@ private void addSymbols(ScopeNode scopeNode) { * @return */ public List> getKeys() { - return this.rootNode.getKeys(); + return this.rootNode.getKeys(); } /** @@ -107,20 +109,22 @@ public List> getKeys() { * @return */ public V getSymbol(String... key) { - return this.rootNode.getSymbol(key); + return this.rootNode.getSymbol(key); } /** - * Returns the symbol mapped to the given key. If a symbol cannot be found, returns null. + * Returns the symbol mapped to the given key. If a symbol cannot be found, + * returns null. * *

- * A key is composed by a scope, in the form of a list of Strings, plus a String with the name of the symbol. + * A key is composed by a scope, in the form of a list of Strings, plus a String + * with the name of the symbol. * * @param key * @return */ public V getSymbol(List key) { - return this.rootNode.getSymbol(key); + return this.rootNode.getSymbol(key); } /** @@ -131,9 +135,9 @@ public V getSymbol(List key) { * @return */ public V getSymbol(List scope, String variableName) { - List key = new ArrayList<>(scope); - key.add(variableName); - return getSymbol(key); + List key = new ArrayList<>(scope); + key.add(variableName); + return getSymbol(key); } /** @@ -145,25 +149,26 @@ public V getSymbol(List scope, String variableName) { * @param symbol */ public void addSymbol(List scope, String name, V symbol) { - this.rootNode.addSymbol(scope, name, symbol); + this.rootNode.addSymbol(scope, name, symbol); - // Set default scope - if (this.firstScope != null) { - this.firstScope = new ArrayList<>(scope); - } + // Set default scope + if (this.firstScope != null) { + this.firstScope = new ArrayList<>(scope); + } } /** * Adds a symbol mapped to the given key. * *

- * A key is composed by a scope, in the form of a list of Strings, plus a String with the name of the symbol. + * A key is composed by a scope, in the form of a list of Strings, plus a String + * with the name of the symbol. * * @param key * @param symbol */ public void addSymbol(List key, V symbol) { - this.rootNode.addSymbol(key, symbol); + this.rootNode.addSymbol(key, symbol); } /** @@ -173,7 +178,7 @@ public void addSymbol(List key, V symbol) { * @param symbol */ public void addSymbol(String key, V symbol) { - this.rootNode.addSymbol(Arrays.asList(key), symbol); + this.rootNode.addSymbol(Arrays.asList(key), symbol); } /** @@ -183,57 +188,59 @@ public void addSymbol(String key, V symbol) { * @param key */ public void addSymbol(V symbol, String... key) { - this.rootNode.addSymbol(Arrays.asList(key), symbol); + this.rootNode.addSymbol(Arrays.asList(key), symbol); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override public String toString() { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - // builder.append("\nSymbols:\n"); - builder.append(this.rootNode.toString()); + builder.append(this.rootNode.toString()); - return builder.toString(); + return builder.toString(); } /** - * Adds all the symbols in the given map to the current map, preserving the original scope. + * Adds all the symbols in the given map to the current map, preserving the + * original scope. * * @param map */ public void addSymbols(ScopedMap map) { - for (List key : map.getKeys()) { - V symbol = map.getSymbol(key); - if (symbol == null) { - SpecsLogs.warn("Null symbol for key '" + key + "'. Table:\n" + map.rootNode); - } - - this.rootNode.addSymbol(key, symbol); - } + for (List key : map.getKeys()) { + V symbol = map.getSymbol(key); + if (symbol == null) { + SpecsLogs.warn("Null symbol for key '" + key + "'. Table:\n" + map.rootNode); + } + + this.rootNode.addSymbol(key, symbol); + } } /** - * Adds all the symbols in the given map to the current map, mapping them to the given scope. + * Adds all the symbols in the given map to the current map, mapping them to the + * given scope. * * @param scope * @param inputVectorsTypes */ public void addSymbols(List scope, ScopedMap symbolMap) { - Map symbols = symbolMap.getSymbols(null); + Map symbols = symbolMap.getSymbols(null); - // Add each symbol to the given scope - for (String symbolName : symbols.keySet()) { - V symbol = symbols.get(symbolName); - addSymbol(scope, symbolName, symbol); - } + // Add each symbol to the given scope + for (String symbolName : symbols.keySet()) { + V symbol = symbols.get(symbolName); + addSymbol(scope, symbolName, symbol); + } } - // TODO: Make private - public ScopeNode getScopeNode(List scope) { - return this.rootNode.getScopeNode(scope); + private ScopeNode getScopeNode(List scope) { + return this.rootNode.getScopeNode(scope); } /** @@ -243,20 +250,20 @@ public ScopeNode getScopeNode(List scope) { * @return */ public Map getSymbols(List scope) { - if (scope == null) { - return this.rootNode.getSymbols(); - } + if (scope == null) { + return this.rootNode.getSymbols(); + } - if (scope.isEmpty()) { - return this.rootNode.getSymbols(); - } + if (scope.isEmpty()) { + return this.rootNode.getSymbols(); + } - ScopeNode scopeNode = getScopeNode(scope); - if (scopeNode == null) { - return new HashMap<>(); - } + ScopeNode scopeNode = getScopeNode(scope); + if (scopeNode == null) { + return new HashMap<>(); + } - return scopeNode.getSymbols(); + return scopeNode.getSymbols(); } /** @@ -265,12 +272,12 @@ public Map getSymbols(List scope) { * @return a collection with all the symbols in the map */ public List getSymbols() { - List symbols = new ArrayList<>(); - for (List key : getKeys()) { - symbols.add(getSymbol(key)); - } + List symbols = new ArrayList<>(); + for (List key : getKeys()) { + symbols.add(getSymbol(key)); + } - return symbols; + return symbols; } /** @@ -281,13 +288,13 @@ public List getSymbols() { * @return */ public boolean containsSymbol(List scope, String symbolName) { - Map varTable = getSymbols(scope); - V variable = varTable.get(symbolName); - if (variable != null) { - return true; - } + Map varTable = getSymbols(scope); + V variable = varTable.get(symbolName); + if (variable != null) { + return true; + } - return false; + return false; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsArray.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsArray.java index 47c0e517..444c7bed 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsArray.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsArray.java @@ -18,7 +18,8 @@ public class SpecsArray { /** * * @param object - * @return the length of the object if it is an array, or -1 if the object is not an array + * @return the length of the object if it is an array, or -1 if the object is + * not an array */ public static int getLength(Object object) { var objectClass = object.getClass(); @@ -81,20 +82,4 @@ public static T last(T[] array) { return array[array.length - 1]; } - /* - public static T[] concant(T[] array, ET newValue) { - @SuppressWarnings("unchecked") - var newArray = (T[]) new Object[array.length + 1]; - - // Copy values from array - for (int i = 0; i < array.length; i++) { - newArray[i] = array[i]; - } - - // New element - newArray[array.length] = newValue; - - return newArray; - } - */ } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsList.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsList.java index 256b7965..1cb7769a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsList.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/SpecsList.java @@ -98,18 +98,6 @@ public SpecsList concat(Collection list) { return SpecsCollections.concat(this.list, list); } - // public SpecsList map(Function mapper) { - // List mappedList = list.stream() - // .map(mapper) - // .collect(Collectors.toList()); - // - // return SpecsList.convert(mappedList); - // } - - // public void addTo(Collection receivingCollection) { - // receivingCollection.addAll(this); - // } - public SpecsList andAdd(T e) { list.add(e); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelConsumer.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelConsumer.java index 6d770165..c2f5f34a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelConsumer.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelConsumer.java @@ -17,7 +17,8 @@ import java.util.concurrent.TimeUnit; /** - * Can only be created by a ConcurrentChannel object, and represents a consumer end of that channel. + * Can only be created by a ConcurrentChannel object, and represents a consumer + * end of that channel. * * @author Joao Bispo */ @@ -30,7 +31,8 @@ public class ChannelConsumer { } /** - * Retrieves and removes the head of this queue, or returns null if this queue is empty. + * Retrieves and removes the head of this queue, or returns null if this queue + * is empty. * * @return the head of this queue, or null if this queue is empty */ @@ -39,27 +41,25 @@ public T poll() { } /** - * Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element - * to become available. + * Retrieves and removes the head of this queue, waiting up to the specified + * wait time if necessary for an element to become available. * - * @param timeout - * how long to wait before giving up, in units of unit - * @param unit - * a TimeUnit determining how to interpret the timeout parameter - * @return the head of this queue, or null if the specified waiting time elapses before an element is available - * @throws InterruptedException - * if interrupted while waiting + * @param timeout how long to wait before giving up, in units of unit + * @param unit a TimeUnit determining how to interpret the timeout parameter + * @return the head of this queue, or null if the specified waiting time elapses + * before an element is available + * @throws InterruptedException if interrupted while waiting */ public T poll(long timeout, TimeUnit unit) throws InterruptedException { return this.channel.poll(timeout, unit); } /** - * Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. + * Retrieves and removes the head of this queue, waiting if necessary until an + * element becomes available. * * @return the head of this queue - * @throws InterruptedException - * if interrupted while waiting + * @throws InterruptedException if interrupted while waiting */ public T take() throws InterruptedException { return this.channel.take(); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelProducer.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelProducer.java index 637363a2..8bf576f5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelProducer.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ChannelProducer.java @@ -19,7 +19,8 @@ import pt.up.fe.specs.util.SpecsLogs; /** - * Can only be created by a ConcurrentChannel objects, and represents a producer end of that channel. + * Can only be created by a ConcurrentChannel objects, and represents a producer + * end of that channel. * * @author Joao Bispo */ @@ -32,13 +33,14 @@ public class ChannelProducer { } /** - * Inserts the specified element into this queue if it is possible to do so immediately without violating capacity - * restrictions, returning true upon success and false if no space is currently available. When using a - * capacity-restricted queue, this method is generally preferable to BlockingQueue.add, which can fail to insert an - * element only by throwing an exception. + * Inserts the specified element into this queue if it is possible to do so + * immediately without violating capacity restrictions, returning true upon + * success and false if no space is currently available. When using a + * capacity-restricted queue, this method is generally preferable to + * BlockingQueue.add, which can fail to insert an element only by throwing an + * exception. * - * @param e - * the element to add + * @param e the element to add * * @return true if the element was added to this queue, else false */ @@ -47,16 +49,14 @@ public boolean offer(T e) { } /** - * inserts the specified element into this queue, waiting up to the specified wait time if necessary for space to - * become available. + * inserts the specified element into this queue, waiting up to the specified + * wait time if necessary for space to become available. * - * @param e - * the element to add - * @param timeout - * how long to wait before giving up, in units of unit - * @param unit - * a TimeUnit determining how to interpret the timeout parameter - * @return true if successful, or false if the specified waiting time elapses before space is available + * @param e the element to add + * @param timeout how long to wait before giving up, in units of unit + * @param unit a TimeUnit determining how to interpret the timeout parameter + * @return true if successful, or false if the specified waiting time elapses + * before space is available * @throws InterruptedException */ public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { @@ -64,7 +64,8 @@ public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedExcepti } /** - * Inserts the specified element into this queue, waiting if necessary for space to become available. + * Inserts the specified element into this queue, waiting if necessary for space + * to become available. * * @param e */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ConcurrentChannel.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ConcurrentChannel.java index ba10120f..05ae15a8 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ConcurrentChannel.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/concurrentchannel/ConcurrentChannel.java @@ -17,7 +17,8 @@ import java.util.concurrent.BlockingQueue; /** - * Wrapper for a bounded Blocking Queue, which can only be accessed by ChannelProducer and ChannelConsumer objects. + * Wrapper for a bounded Blocking Queue, which can only be accessed by + * ChannelProducer and ChannelConsumer objects. * * @author Joao Bispo */ @@ -28,8 +29,7 @@ public class ConcurrentChannel { /** * Creates a bounded blocking queue with the specified capacity. * - * @param capacity - * the capacity of this Concurrent Channel. + * @param capacity the capacity of this Concurrent Channel. */ public ConcurrentChannel(int capacity) { this.channel = new ArrayBlockingQueue<>(capacity); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/ArrayPushingQueue.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/ArrayPushingQueue.java index 0740170f..61740fc1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/ArrayPushingQueue.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/ArrayPushingQueue.java @@ -56,13 +56,11 @@ public ArrayPushingQueue(int capacity) { * Inserts an element at the head of the queue, pushing all other elements one * position forward. If the queue is full, the last element is dropped. * - * @param element - * an element to insert in the queue + * @param element an element to insert in the queue */ @Override public void insertElement(T element) { // Insert element at the head - // queue.addFirst(element); this.queue.add(0, element); // If size exceed capacity, remove last element @@ -75,8 +73,7 @@ public void insertElement(T element) { /** * Returns the element at the specified position in this queue. * - * @param index - * index of the element to return + * @param index index of the element to return * @return the element at the specified position in this queue */ @Override @@ -133,7 +130,6 @@ public String toString() { builder.append("]"); return builder.toString(); - } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/LinkedPushingQueue.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/LinkedPushingQueue.java index b0956f6d..1574a645 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/LinkedPushingQueue.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/LinkedPushingQueue.java @@ -47,8 +47,7 @@ public LinkedPushingQueue(int capacity) { * Inserts an element at the head of the queue, pushing all other elements one * position forward. If the queue is full, the last element is dropped. * - * @param element - * an element to insert in the queue + * @param element an element to insert in the queue */ @Override public void insertElement(T element) { @@ -67,8 +66,7 @@ public void insertElement(T element) { /** * Returns the element at the specified position in this queue. * - * @param index - * index of the element to return + * @param index index of the element to return * @return the element at the specified position in this queue */ @Override @@ -125,7 +123,6 @@ public String toString() { builder.append("]"); return builder.toString(); - } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/MixedPushingQueue.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/MixedPushingQueue.java index 7258c628..2e515616 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/MixedPushingQueue.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/MixedPushingQueue.java @@ -23,46 +23,46 @@ public class MixedPushingQueue implements PushingQueue { private final PushingQueue queue; public MixedPushingQueue(int capacity) { - if (capacity < MixedPushingQueue.LINKED_THRESHOLD) { - this.queue = new ArrayPushingQueue<>(capacity); - } else { - this.queue = new LinkedPushingQueue<>(capacity); - } + if (capacity < MixedPushingQueue.LINKED_THRESHOLD) { + this.queue = new ArrayPushingQueue<>(capacity); + } else { + this.queue = new LinkedPushingQueue<>(capacity); + } } @Override public void insertElement(T element) { - this.queue.insertElement(element); + this.queue.insertElement(element); } @Override public T getElement(int index) { - return this.queue.getElement(index); + return this.queue.getElement(index); } @Override public int size() { - return this.queue.size(); + return this.queue.size(); } @Override public int currentSize() { - return this.queue.currentSize(); + return this.queue.currentSize(); } @Override public Iterator iterator() { - return this.queue.iterator(); + return this.queue.iterator(); } @Override public Stream stream() { - return this.queue.stream(); + return this.queue.stream(); } @Override public String toString() { - return toString(element -> element.toString()); + return toString(element -> element.toString()); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/PushingQueue.java b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/PushingQueue.java index bbb0bb55..16666470 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/PushingQueue.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/collections/pushingqueue/PushingQueue.java @@ -22,8 +22,9 @@ * "Pushing Queue" of fixed size. * *

- * Elements can only be added at the head of the queue. Every time an element is added, every other elements gets - * "pushed" (its index increments by one). If an element is added when the queue is full, the last element in the queue + * Elements can only be added at the head of the queue. Every time an element is + * added, every other elements gets "pushed" (its index increments by one). If + * an element is added when the queue is full, the last element in the queue * gets dropped. * * TODO: remove capacity, replace with size @@ -33,19 +34,17 @@ public interface PushingQueue { /** - * Inserts an element at the head of the queue, pushing all other elements one position forward. If the queue is - * full, the last element is dropped. + * Inserts an element at the head of the queue, pushing all other elements one + * position forward. If the queue is full, the last element is dropped. * - * @param element - * an element to insert in the queue + * @param element an element to insert in the queue */ void insertElement(T element); /** * Returns the element at the specified position in this queue. * - * @param index - * index of the element to return + * @param index index of the element to return * @return the element at the specified position in this queue */ T getElement(int index); @@ -68,8 +67,8 @@ public interface PushingQueue { Stream stream(); default String toString(Function mapper) { - return stream() - .map(element -> mapper.apply(element)) - .collect(Collectors.joining(", ", "[", "]")); + return stream() + .map(element -> mapper.apply(element)) + .collect(Collectors.joining(", ", "[", "]")); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/csv/BufferedCsvWriter.java b/SpecsUtils/src/pt/up/fe/specs/util/csv/BufferedCsvWriter.java index 62172e96..b7c28cc0 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/csv/BufferedCsvWriter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/csv/BufferedCsvWriter.java @@ -29,7 +29,6 @@ public BufferedCsvWriter(File bufferFile, List header) { super(header); this.bufferFile = bufferFile; - // this.outputFile = new File(outputFile.getParent(), outputFile.getName() + ".buffer"); this.headerWritten = false; this.lineCounter = 0; // Delete buffer @@ -38,29 +37,12 @@ public BufferedCsvWriter(File bufferFile, List header) { @Override public BufferedCsvWriter addLine(List line) { - // When adding a line, write directly to the file - // super.addLine(line); - // Write header if (!this.headerWritten) { this.headerWritten = true; // Increment line counter lineCounter++; - /* - StringBuilder builder = new StringBuilder(); - - // Separator - builder.append("sep=").append(this.delimiter).append("\n"); - - // Header - builder.append(this.header.get(0)); - for (int i = 1; i < this.header.size(); i++) { - builder.append(this.delimiter).append(this.header.get(i)); - } - builder.append(this.newline); - - IoUtils.append(this.bufferFile, builder.toString()); - */ + SpecsIo.append(this.bufferFile, buildHeader()); } @@ -69,17 +51,6 @@ public BufferedCsvWriter addLine(List line) { // Write line SpecsIo.append(this.bufferFile, buildLine(line, lineCounter)); - /* - StringBuilder builder = new StringBuilder(); - - builder.append(line.get(0)); - for (int i = 1; i < line.size(); i++) { - builder.append(this.delimiter).append(line.get(i)); - } - builder.append(this.newline); - - IoUtils.append(this.bufferFile, builder.toString()); - */ return this; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/csv/CsvWriter.java b/SpecsUtils/src/pt/up/fe/specs/util/csv/CsvWriter.java index 1ab49e35..70251a3b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/csv/CsvWriter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/csv/CsvWriter.java @@ -60,7 +60,6 @@ public CsvWriter(String... header) { public CsvWriter(List header) { this.delimiter = CsvWriter.DEFAULT_DELIMITER; - // newline = System.lineSeparator(); this.newline = System.getProperty("line.separator"); this.header = header; this.lines = new ArrayList<>(); @@ -180,17 +179,6 @@ protected String buildLine(List line, int lineNumber) { csv.append(newline); return csv.toString(); - /* - StringBuilder csvLine = new StringBuilder(); - - csvLine.append(line.get(0)); - for (int i = 1; i < line.size(); i++) { - csvLine.append(this.delimiter).append(line.get(i)); - } - csvLine.append(this.newline); - - return csvLine.toString(); - */ } public String buildCsv() { @@ -202,18 +190,6 @@ public String buildCsv() { StringBuilder builder = new StringBuilder(); builder.append(buildHeader()); - /* - // Separator - builder.append("sep=").append(this.delimiter).append("\n"); - - // Header - builder.append(this.header.get(0)); - for (int i = 1; i < this.header.size(); i++) { - builder.append(this.delimiter).append(this.header.get(i)); - } - - builder.append(this.newline); - */ // First line is the header int lineCounter = 2; @@ -222,13 +198,6 @@ public String buildCsv() { for (List line : this.lines) { builder.append(buildLine(line, lineCounter)); lineCounter++; - /* - builder.append(line.get(0)); - for (int i = 1; i < line.size(); i++) { - builder.append(this.delimiter).append(line.get(i)); - } - builder.append(this.newline); - */ } return builder.toString(); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/enums/EnumHelper.java b/SpecsUtils/src/pt/up/fe/specs/util/enums/EnumHelper.java index 9e8a13de..d436eaf7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/enums/EnumHelper.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/enums/EnumHelper.java @@ -100,8 +100,8 @@ public T[] values() { } /** - * The names used to map Strings to Enums. Might not be the same as the Enum name, if the Enum implements - * StringProvider. + * The names used to map Strings to Enums. Might not be the same as the Enum + * name, if the Enum implements StringProvider. * * @return */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/ActionsMap.java b/SpecsUtils/src/pt/up/fe/specs/util/events/ActionsMap.java index 6313007d..a096216a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/ActionsMap.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/ActionsMap.java @@ -27,24 +27,22 @@ */ public class ActionsMap { - // private final Map, EventAction> actionsMap; private final Map actionsMap; public ActionsMap() { - this.actionsMap = new HashMap<>(); + this.actionsMap = new HashMap<>(); } - // public EventAction putAction(Enum eventId, EventAction action) { public EventAction putAction(EventId eventId, EventAction action) { - EventAction previousAction = this.actionsMap.put(eventId, action); + EventAction previousAction = this.actionsMap.put(eventId, action); - if (previousAction != null) { - SpecsLogs.warn("Event '" + eventId + "' already in table. Replacing action '" - + previousAction + "' with action '" + action + "'"); - } + if (previousAction != null) { + SpecsLogs.warn("Event '" + eventId + "' already in table. Replacing action '" + + previousAction + "' with action '" + action + "'"); + } - return previousAction; + return previousAction; } /** @@ -53,20 +51,20 @@ public EventAction putAction(EventId eventId, EventAction action) { * @param event */ public void performAction(Event event) { - // Get action - EventAction action = this.actionsMap.get(event.getId()); + // Get action + EventAction action = this.actionsMap.get(event.getId()); - if (action == null) { - SpecsLogs.warn("Could not find an action for event '" + event.getId() + "'"); - return; - } + if (action == null) { + SpecsLogs.warn("Could not find an action for event '" + event.getId() + "'"); + return; + } - // Execute action - action.performAction(event); + // Execute action + action.performAction(event); } public Set getSupportedEvents() { - return this.actionsMap.keySet(); + return this.actionsMap.keySet(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/Event.java b/SpecsUtils/src/pt/up/fe/specs/util/events/Event.java index f48a9c24..0ccea4e2 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/Event.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/Event.java @@ -21,13 +21,7 @@ * @param */ public interface Event { - // public interface Event, E> { - // public interface Event> { - - // Class getDataClass(); - // Enum getId(); EventId getId(); Object getData(); - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/EventAction.java b/SpecsUtils/src/pt/up/fe/specs/util/events/EventAction.java index 5061f761..bad585ee 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/EventAction.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/EventAction.java @@ -19,26 +19,6 @@ * @author Joao Bispo * */ -// public abstract class EventAction { public interface EventAction { - /* - * keleton class that performs an action related to a single event. - * - *

- * Useful for creating anonymous classes that respond to single events. - * - protected final Enum eventId; - - public EventAction(Event event) { - this.event = event; - } - - public Event getEvent() { - return event; - } - - public abstract void performAction(Event event); - */ - void performAction(Event event); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/EventController.java b/SpecsUtils/src/pt/up/fe/specs/util/events/EventController.java index 0045347f..5233f52a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/EventController.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/EventController.java @@ -24,25 +24,24 @@ public class EventController implements EventNotifier, EventRegister { - // Map, Collection> registeredListeners; private final Map> registeredListeners; // To count and keep track of listeners private final AccumulatorMap listenersCount; public EventController() { - this.registeredListeners = new HashMap<>(); - this.listenersCount = new AccumulatorMap<>(); + this.registeredListeners = new HashMap<>(); + this.listenersCount = new AccumulatorMap<>(); } /** * Registers receiver to all its supported events. * - * @param reciver + * @param receiver * @param eventIds */ @Override - public void registerReceiver(EventReceiver reciver) { - registerListener(reciver, reciver.getSupportedEvents()); + public void registerReceiver(EventReceiver receiver) { + registerListener(receiver, receiver.getSupportedEvents()); } /** @@ -53,33 +52,33 @@ public void registerReceiver(EventReceiver reciver) { */ @Override public void unregisterReceiver(EventReceiver receiver) { - unregisterReceiver(receiver, receiver.getSupportedEvents()); + unregisterReceiver(receiver, receiver.getSupportedEvents()); } private void unregisterReceiver(EventReceiver receiver, Collection supportedEvents) { - for (EventId event : supportedEvents) { - unregisterListener(receiver, event); - } + for (EventId event : supportedEvents) { + unregisterListener(receiver, event); + } } private void unregisterListener(EventReceiver receiver, EventId eventId) { - // Check if event is already on table - Collection receivers = this.registeredListeners.get(eventId); - if (receivers == null) { - SpecsLogs.warn("No receivers mapped to EventId '" + eventId + "'"); - return; - } - - // Check if receiver is not present - if (!receivers.contains(receiver)) { - SpecsLogs.msgInfo("Event '" + eventId + "' was not registered for receiver '" + receiver + "'"); - return; - } - - // Remove receiver - receivers.remove(receiver); - // Decrease count - this.listenersCount.remove(receiver); + // Check if event is already on table + Collection receivers = this.registeredListeners.get(eventId); + if (receivers == null) { + SpecsLogs.warn("No receivers mapped to EventId '" + eventId + "'"); + return; + } + + // Check if receiver is not present + if (!receivers.contains(receiver)) { + SpecsLogs.msgInfo("Event '" + eventId + "' was not registered for receiver '" + receiver + "'"); + return; + } + + // Remove receiver + receivers.remove(receiver); + // Decrease count + this.listenersCount.remove(receiver); } @@ -89,9 +88,8 @@ private void unregisterListener(EventReceiver receiver, EventId eventId) { * @param listener * @param eventIds */ - // public void registerListener(EventReceiver listener, Enum... eventIds) { public void registerListener(EventReceiver listener, EventId... eventIds) { - registerListener(listener, Arrays.asList(eventIds)); + registerListener(listener, Arrays.asList(eventIds)); } /** @@ -101,13 +99,13 @@ public void registerListener(EventReceiver listener, EventId... eventIds) { * @param event */ public void registerListener(EventReceiver listener, Collection eventIds) { - if (eventIds == null) { - return; - } + if (eventIds == null) { + return; + } - for (EventId event : eventIds) { - registerListener(listener, event); - } + for (EventId event : eventIds) { + registerListener(listener, event); + } } /** @@ -116,40 +114,38 @@ public void registerListener(EventReceiver listener, Collection eventId * @param listener * @param eventId */ - // public void registerListener(EventReceiver listener, Enum eventId) { public void registerListener(EventReceiver listener, EventId eventId) { - // Check if event is already on table - Collection listeners = this.registeredListeners.get(eventId); - if (listeners == null) { - listeners = new LinkedHashSet<>(); - this.registeredListeners.put(eventId, listeners); - } - - // Check if listener is already registered - if (listeners.contains(listener)) { - SpecsLogs.msgInfo("Event '" + eventId + "' already registers for listener '" + listener + "'"); - return; - } - - // Register listener - listeners.add(listener); - // Add count - this.listenersCount.add(listener); + // Check if event is already on table + Collection listeners = this.registeredListeners.get(eventId); + if (listeners == null) { + listeners = new LinkedHashSet<>(); + this.registeredListeners.put(eventId, listeners); + } + + // Check if listener is already registered + if (listeners.contains(listener)) { + SpecsLogs.msgInfo("Event '" + eventId + "' already registers for listener '" + listener + "'"); + return; + } + + // Register listener + listeners.add(listener); + // Add count + this.listenersCount.add(listener); } @Override public void notifyEvent(Event event) { - Collection listeners = this.registeredListeners.get(event.getId()); + Collection listeners = this.registeredListeners.get(event.getId()); - if (listeners == null) { - // LoggingUtils.msgInfo("No listeners registered to event " + event.getId()); - return; - } + if (listeners == null) { + return; + } - for (EventReceiver listener : listeners) { - listener.acceptEvent(event); - } + for (EventReceiver listener : listeners) { + listener.acceptEvent(event); + } } @@ -157,7 +153,7 @@ public void notifyEvent(Event event) { * @return true if there is at least one listeners registered */ public boolean hasListeners() { - return !this.listenersCount.getAccMap().keySet().isEmpty(); + return !this.listenersCount.getAccMap().keySet().isEmpty(); } /** @@ -165,7 +161,7 @@ public boolean hasListeners() { * @return the listeners currently registered to the controller */ public Collection getListeners() { - return this.listenersCount.getAccMap().keySet(); + return this.listenersCount.getAccMap().keySet(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/EventReceiverTemplate.java b/SpecsUtils/src/pt/up/fe/specs/util/events/EventReceiverTemplate.java index bc0a6fe4..a7ccf150 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/EventReceiverTemplate.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/EventReceiverTemplate.java @@ -28,19 +28,19 @@ public abstract class EventReceiverTemplate implements EventReceiver { @Override public void acceptEvent(Event event) { - if (getActionsMap() == null) { - return; - } + if (getActionsMap() == null) { + return; + } - getActionsMap().performAction(event); + getActionsMap().performAction(event); } @Override public Collection getSupportedEvents() { - if (getActionsMap() == null) { - return Collections.emptyList(); - } + if (getActionsMap() == null) { + return Collections.emptyList(); + } - return getActionsMap().getSupportedEvents(); + return getActionsMap().getSupportedEvents(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/EventUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/events/EventUtils.java index b1148fd6..586148df 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/EventUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/EventUtils.java @@ -25,13 +25,13 @@ public class EventUtils { * @return */ public static Collection getEventIds(EventId... eventIds) { - Collection eventList = new ArrayList<>(); + Collection eventList = new ArrayList<>(); - for (EventId eventId : eventIds) { - eventList.add(eventId); - } + for (EventId eventId : eventIds) { + eventList.add(eventId); + } - return eventList; + return eventList; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/events/SimpleEvent.java b/SpecsUtils/src/pt/up/fe/specs/util/events/SimpleEvent.java index 68c69776..a3b9ebff 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/events/SimpleEvent.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/events/SimpleEvent.java @@ -19,18 +19,18 @@ public class SimpleEvent implements Event { private final Object data; public SimpleEvent(EventId eventId, Object data) { - this.eventId = eventId; - this.data = data; + this.eventId = eventId; + this.data = data; } @Override public EventId getId() { - return this.eventId; + return this.eventId; } @Override public Object getData() { - return this.data; + return this.data; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/CaseNotDefinedException.java b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/CaseNotDefinedException.java index d15e4d9d..3e7d68ec 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/CaseNotDefinedException.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/CaseNotDefinedException.java @@ -17,10 +17,6 @@ public class CaseNotDefinedException extends UnsupportedOperationException { private static final long serialVersionUID = 1L; - // public CaseNotDefinedException(Object origin) { - // this(origin.getClass()); - // } - public CaseNotDefinedException(Class undefinedCase) { super(getDefaultMessageClass(undefinedCase.getName())); } @@ -33,10 +29,6 @@ public CaseNotDefinedException(Object object) { super(getDefaultMessageObject(object)); } - // public CaseNotDefinedException(String message) { - // super("Case not defined: " + message); - // } - private static String getDefaultMessageClass(String originClass) { return "Case not defined for class '" + originClass + "'"; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/NotImplementedException.java b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/NotImplementedException.java index 08110b44..f1384cd1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/NotImplementedException.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/NotImplementedException.java @@ -34,12 +34,12 @@ public NotImplementedException(String message) { } /** - * @deprecated Replaced with {@link NotImplementedException#NotImplementedException(Class)} + * @deprecated Replaced with + * {@link NotImplementedException#NotImplementedException(Class)} */ @Deprecated public NotImplementedException() { super(getDefaultMessage(new Exception().getStackTrace()[1].getClassName())); - // super(getMessagePrivate(2)); } private static String getDefaultMessage(String originClass) { @@ -50,8 +50,4 @@ private static String getDefaultMessage(Enum anEnum) { return "Not yet implemented for enum '" + anEnum.name() + "'"; } - // private static String getMessagePrivate(int level) { - // // TODO: Check if getting the correct stack trace position - // return "Not yet implemented in class '" + new Exception().getStackTrace()[level].getClassName() + "'"; - // } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/OverflowException.java b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/OverflowException.java index b9d7b09f..bc1776ae 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/OverflowException.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/OverflowException.java @@ -17,6 +17,6 @@ public class OverflowException extends RuntimeException { private static final long serialVersionUID = 1L; public OverflowException(String message) { - super(message); + super(message); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/WrongClassException.java b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/WrongClassException.java index db3c6d7c..5ea51165 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/exceptions/WrongClassException.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/exceptions/WrongClassException.java @@ -18,12 +18,12 @@ public class WrongClassException extends UnsupportedOperationException { private static final long serialVersionUID = 1L; public WrongClassException(Object testedInstance, Class expectedClass) { - this(testedInstance.getClass(), expectedClass); + this(testedInstance.getClass(), expectedClass); } public WrongClassException(Class foundClass, Class expectedClass) { - super("Expected class '" + expectedClass.getSimpleName() + "', found " - + foundClass.getSimpleName()); + super("Expected class '" + expectedClass.getSimpleName() + "', found " + + foundClass.getSimpleName()); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphSerializable.java b/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphSerializable.java index 19a8c2b8..3420da1b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphSerializable.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphSerializable.java @@ -32,54 +32,54 @@ public class GraphSerializable { public final List connInfos; public GraphSerializable(List operationIds, List nodeInfos, List inputIds, - List outputIds, List connInfos) { - this.operationIds = operationIds; - this.nodeInfos = nodeInfos; - this.inputIds = inputIds; - this.outputIds = outputIds; - this.connInfos = connInfos; + List outputIds, List connInfos) { + this.operationIds = operationIds; + this.nodeInfos = nodeInfos; + this.inputIds = inputIds; + this.outputIds = outputIds; + this.connInfos = connInfos; } public static , N, C> GraphSerializable toSerializable( - Graph graph) { - List operationIds = new ArrayList<>(); - List nodeInfos = new ArrayList<>(); + Graph graph) { + List operationIds = new ArrayList<>(); + List nodeInfos = new ArrayList<>(); - for (T node : graph.getNodeList()) { - operationIds.add(node.getId()); - nodeInfos.add(node.getNodeInfo()); - } + for (T node : graph.getNodeList()) { + operationIds.add(node.getId()); + nodeInfos.add(node.getNodeInfo()); + } - List inputIds = new ArrayList<>(); - List outputIds = new ArrayList<>(); - List connInfos = new ArrayList<>(); + List inputIds = new ArrayList<>(); + List outputIds = new ArrayList<>(); + List connInfos = new ArrayList<>(); - for (T node : graph.getNodeList()) { + for (T node : graph.getNodeList()) { - // Add children connections - for (int i = 0; i < node.getChildren().size(); i++) { - inputIds.add(node.getId()); - outputIds.add(node.getChildren().get(i).getId()); - connInfos.add(node.getChildrenConnections().get(i)); - } + // Add children connections + for (int i = 0; i < node.getChildren().size(); i++) { + inputIds.add(node.getId()); + outputIds.add(node.getChildren().get(i).getId()); + connInfos.add(node.getChildrenConnections().get(i)); + } - } + } - return new GraphSerializable<>(operationIds, nodeInfos, inputIds, outputIds, - connInfos); + return new GraphSerializable<>(operationIds, nodeInfos, inputIds, outputIds, + connInfos); } public static , N, C> void fromSerializable( - GraphSerializable graph, Graph newGraph) { + GraphSerializable graph, Graph newGraph) { - for (int i = 0; i < graph.operationIds.size(); i++) { - newGraph.addNode(graph.operationIds.get(i), graph.nodeInfos.get(i)); - } + for (int i = 0; i < graph.operationIds.size(); i++) { + newGraph.addNode(graph.operationIds.get(i), graph.nodeInfos.get(i)); + } - for (int i = 0; i < graph.connInfos.size(); i++) { - newGraph.addConnection(graph.inputIds.get(i), graph.outputIds.get(i), - graph.connInfos.get(i)); - } + for (int i = 0; i < graph.connInfos.size(); i++) { + newGraph.addConnection(graph.inputIds.get(i), graph.outputIds.get(i), + graph.connInfos.get(i)); + } } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphToDotty.java b/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphToDotty.java index dc9c9d8d..b50f37a4 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphToDotty.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/graphs/GraphToDotty.java @@ -24,40 +24,34 @@ */ public class GraphToDotty { - /* - public static , N, C> String getDotty(GraphV2 graph) { - return getDotty(graph); - } - */ - public static , N, C> String getDotty(Graph graph) { - // Build Declarations and Connections - List declarations = new ArrayList<>(); - List connections = new ArrayList<>(); - for (GN graphNode : graph.getNodeList()) { - declarations.add(getDeclaration(graphNode)); - - for (int i = 0; i < graphNode.getChildrenConnections().size(); i++) { - String connection = getConnection(graphNode, i); - connections.add(connection); - } - } - - return SpecsGraphviz.generateGraph(declarations, connections); + // Build Declarations and Connections + List declarations = new ArrayList<>(); + List connections = new ArrayList<>(); + for (GN graphNode : graph.getNodeList()) { + declarations.add(getDeclaration(graphNode)); + + for (int i = 0; i < graphNode.getChildrenConnections().size(); i++) { + String connection = getConnection(graphNode, i); + connections.add(connection); + } + } + + return SpecsGraphviz.generateGraph(declarations, connections); } public static , N, C> String getDeclaration(GN node) { - N nodeInfo = node.getNodeInfo(); - return SpecsGraphviz.declaration(node.getId(), nodeInfo.toString(), - "box", "white"); + N nodeInfo = node.getNodeInfo(); + return SpecsGraphviz.declaration(node.getId(), nodeInfo.toString(), + "box", "white"); } public static , N, C> String getConnection(GN node, int index) { - String inputId = node.getId(); - String outputId = node.getChildren().get(index).getId(); + String inputId = node.getId(); + String outputId = node.getChildren().get(index).getId(); - String label = node.getChildrenConnections().get(index).toString(); + String label = node.getChildrenConnections().get(index).toString(); - return SpecsGraphviz.connection(inputId, outputId, label); + return SpecsGraphviz.connection(inputId, outputId, label); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/io/InputFiles.java b/SpecsUtils/src/pt/up/fe/specs/util/io/InputFiles.java index 03349e97..7ad8e560 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/io/InputFiles.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/io/InputFiles.java @@ -27,59 +27,54 @@ public class InputFiles { public InputFiles(boolean isSingleFile, File inputPath, List inputFiles) { - this.isSingleFile = isSingleFile; - this.inputPath = inputPath; - this.inputFiles = inputFiles; + this.isSingleFile = isSingleFile; + this.inputPath = inputPath; + this.inputFiles = inputFiles; } /** * Collects the file or files of the input path. * - * @param inputPath - * can be the path to a single file or to a folder + * @param inputPath can be the path to a single file or to a folder * @return */ public static InputFiles newInstance(String inputPath) { - File inputPathFile = new File(inputPath); - if (!inputPathFile.exists()) { - SpecsLogs.warn("Input path '" + inputPathFile + "' does not exist."); - return null; - } + File inputPathFile = new File(inputPath); + if (!inputPathFile.exists()) { + SpecsLogs.warn("Input path '" + inputPathFile + "' does not exist."); + return null; + } - // Determine if it is a file or a folder - boolean isSingleFile = false; - if (inputPathFile.isFile()) { - isSingleFile = true; - } + // Determine if it is a file or a folder + boolean isSingleFile = false; + if (inputPathFile.isFile()) { + isSingleFile = true; + } - List inputFiles = InputFiles.getFiles(inputPath, isSingleFile); + List inputFiles = InputFiles.getFiles(inputPath, isSingleFile); - return new InputFiles(isSingleFile, inputPathFile, inputFiles); + return new InputFiles(isSingleFile, inputPathFile, inputFiles); } private static List getFiles(String inputPath, boolean isSingleFile) { - // Is File mode - if (isSingleFile) { - File inputFile = SpecsIo.existingFile(inputPath); - if (inputFile == null) { - throw new RuntimeException("Could not open file '" + inputPath + "'"); - // LoggingUtils.msgWarn("Could not open file."); - // return Collections.emptyList(); - } - List files = new ArrayList<>(); - files.add(inputFile); - return files; - } + // Is File mode + if (isSingleFile) { + File inputFile = SpecsIo.existingFile(inputPath); + if (inputFile == null) { + throw new RuntimeException("Could not open file '" + inputPath + "'"); + } + List files = new ArrayList<>(); + files.add(inputFile); + return files; + } - // Is Folder mode - File inputFolder = SpecsIo.mkdir(inputPath); - if (inputFolder == null) { - throw new RuntimeException("Could not open folder '" + inputPath + "'"); - // LoggingUtils.msgWarn("Could not open folder."); - // return Collections.emptyList(); - } + // Is Folder mode + File inputFolder = SpecsIo.mkdir(inputPath); + if (inputFolder == null) { + throw new RuntimeException("Could not open folder '" + inputPath + "'"); + } - return SpecsIo.getFilesRecursive(inputFolder); + return SpecsIo.getFilesRecursive(inputFolder); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/io/ResourceCollection.java b/SpecsUtils/src/pt/up/fe/specs/util/io/ResourceCollection.java index 972335ab..6cd20f15 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/io/ResourceCollection.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/io/ResourceCollection.java @@ -25,13 +25,11 @@ public class ResourceCollection { /** * - * @param id - * identifier for this collection of resources - * @param isIdUnique - * true if this collection of resources have a unique mapping to this id, false if the resources can - * change over time for this id - * @param resources - * a collection of resources + * @param id identifier for this collection of resources + * @param isIdUnique true if this collection of resources have a unique mapping + * to this id, false if the resources can change over time for + * this id + * @param resources a collection of resources */ public ResourceCollection(String id, boolean isIdUnique, Collection resources) { this.id = id; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/io/SimpleFile.java b/SpecsUtils/src/pt/up/fe/specs/util/io/SimpleFile.java index bc18e62d..94e491fa 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/io/SimpleFile.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/io/SimpleFile.java @@ -41,30 +41,19 @@ public interface SimpleFile { * @return */ static SimpleFile newInstance(String filename, String contents) { - return new SimpleFile() { + return new SimpleFile() { - @Override - public String getContents() { - return contents; - } + @Override + public String getContents() { + return contents; + } - @Override - public String getFilename() { - return filename; - } + @Override + public String getFilename() { + return filename; + } - }; + }; } - /** - * Helper constructor that receives a file. - * - * @param file - * @return - */ - /* - static LoadedFile newInstance(File file) { - return newInstance(file.getName(), IoUtils.read(file)); - } - */ } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jar/JarParametersUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/jar/JarParametersUtils.java index a82f13d2..ae052894 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jar/JarParametersUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jar/JarParametersUtils.java @@ -14,50 +14,44 @@ package pt.up.fe.specs.util.jar; /** - * The purpose of this class is to provide to the user some methods helping to manage the parameters while running an - * application (.jar, .exe...). + * The purpose of this class is to provide to the user some methods helping to + * manage the parameters while running an application (.jar, .exe...). * * @author remi * */ public class JarParametersUtils { - // --------------------------------------------------------------------- attributes - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - - ---------- static - /** The values the arguments can have for requiring help. */ private static final String[] HELP_ARG = { "-help", "-h", ".?", "/?", "?" }; - // ----------------------------------------------------------------- public_Methods - // ---------- - - - - - - - - - - - - - - - - - - - - - - - - - - ---------- static - /** - * Returns true if the argument represents an help requirement (value "-help", "-h", "/?"...). Returns false + * Returns true if the argument represents an help requirement (value "-help", + * "-h", "/?"...). Returns false * otherwise. * - * @param help - * The string the user wants to know if it is an help requirement. - * @return true if the argument represents an help requirement (value "-help", "-h", "/?"...). Returns false + * @param help The string the user wants to know if it is an help requirement. + * @return true if the argument represents an help requirement (value "-help", + * "-h", "/?"...). Returns false * otherwise. */ public static boolean isHelpRequirement(String help) { - for (String help_arg : JarParametersUtils.HELP_ARG) { - if (help.equals(help_arg)) { - return true; - } - } - return false; + for (String help_arg : JarParametersUtils.HELP_ARG) { + if (help.equals(help_arg)) { + return true; + } + } + return false; } /** * Returns the String "for any help > 'className' -help". * - * @param jarName - * The name the .jar file the help is required in. + * @param jarName The name the .jar file the help is required in. * @return the String "for any help > 'jarName' -help". */ public static String askForHelp(String jarName) { - return "for any help > " + jarName + " " + JarParametersUtils.HELP_ARG[0]; + return "for any help > " + jarName + " " + JarParametersUtils.HELP_ARG[0]; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/FileSet.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/FileSet.java index 00adf8fd..abbe9d1a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/FileSet.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/FileSet.java @@ -31,33 +31,35 @@ public class FileSet { private String outputName; public FileSet(File sourceFolder, List sourceFiles, String outputName) { - this.sourceFilenames = sourceFiles; - this.sourceFolder = sourceFolder; - this.outputName = outputName; + this.sourceFilenames = sourceFiles; + this.sourceFolder = sourceFolder; + this.outputName = outputName; } public List getSourceFilenames() { - return this.sourceFilenames; + return this.sourceFilenames; } public File getSourceFolder() { - return this.sourceFolder; + return this.sourceFolder; } public String outputName() { - return this.outputName; + return this.outputName; } public void setOutputName(String outputName) { - this.outputName = outputName; + this.outputName = outputName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override public String toString() { - return "SOURCEFOLDER:" + this.sourceFolder; + return "SOURCEFOLDER:" + this.sourceFolder; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/InputMode.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/InputMode.java index b9333d52..46d62922 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/InputMode.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/InputMode.java @@ -20,17 +20,18 @@ /** * Distinguishes between two situations about the given source folder: * - * 1) files: Each .c file inside the source folder is a program; 3) folders: Each folder inside the source folder is a - * program; 1) singleFile: the source folder is interpreted as a single file, which corresponds to a program; 2) + * 1) files: Each .c file inside the source folder is a program; 3) folders: + * Each folder inside the source folder is a program; 1) singleFile: the source + * folder is interpreted as a single file, which corresponds to a program; 2) * singleFolder: The files inside the source folder is a program; * - * * @author Joao Bispo */ public enum InputMode { files, /** - * The given path represents a folder that contains several folders, and each folder is a project. + * The given path represents a folder that contains several folders, and each + * folder is a project. */ folders, singleFile, @@ -42,31 +43,28 @@ public enum InputMode { * @return */ public List getPrograms(File sourcePath, Collection extensions, Integer folderLevel) { - switch (this) { - case folders: - return JobUtils.getSourcesFoldersMode(sourcePath, extensions, folderLevel); - case files: - return JobUtils.getSourcesFilesMode(sourcePath, extensions); - case singleFile: - return JobUtils.getSourcesSingleFileMode(sourcePath, extensions); - case singleFolder: - return JobUtils.getSourcesSingleFolderMode(sourcePath, extensions); - default: - throw new RuntimeException("Case not supported:" + this); - } + switch (this) { + case folders: + return JobUtils.getSourcesFoldersMode(sourcePath, extensions, folderLevel); + case files: + return JobUtils.getSourcesFilesMode(sourcePath, extensions); + case singleFile: + return JobUtils.getSourcesSingleFileMode(sourcePath, extensions); + case singleFolder: + return JobUtils.getSourcesSingleFolderMode(sourcePath, extensions); + default: + throw new RuntimeException("Case not supported:" + this); + } } /** - * Returns true if the path mode represents a folder. False, if it represents a file. + * Returns true if the path mode represents a folder. False, if it represents a + * file. * * @return */ public boolean isFolder() { - if (this == singleFile) { - return false; - } - - return true; + return (this != singleFile); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/Job.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/Job.java index 01cb4ea9..74cc87f4 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/Job.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/Job.java @@ -29,22 +29,12 @@ public class Job { /** * INSTANCE VARIABLES */ - // private final List executions; - // private final List executions; private final Execution execution; - // private final List commandArgs; - // String workingFoldername; - boolean interrupted; - // private Job(List executions) { private Job(Execution execution) { - this.execution = execution; - // this.executions = executions; - // this.commandArgs = commandArgs; - // this.workingFoldername = workingFoldername; - - this.interrupted = false; + this.execution = execution; + this.interrupted = false; } /** @@ -54,26 +44,23 @@ private Job(Execution execution) { */ public int run() { - // for (ProcessExecution execution : executions) { - // for (Execution execution : executions) { - int result = this.execution.run(); + int result = this.execution.run(); - if (result != 0) { - SpecsLogs.msgInfo("Execution returned with error value '" + result + "'"); - return -1; - } + if (result != 0) { + SpecsLogs.msgInfo("Execution returned with error value '" + result + "'"); + return -1; + } - if (this.execution.isInterrupted()) { - this.interrupted = true; - return 0; - } - // } + if (this.execution.isInterrupted()) { + this.interrupted = true; + return 0; + } - return 0; + return 0; } public boolean isInterrupted() { - return this.interrupted; + return this.interrupted; } /** @@ -82,17 +69,12 @@ public boolean isInterrupted() { * @return */ public static Job singleProgram(List commandArgs, String workingDir) { - ProcessExecution exec = new ProcessExecution(commandArgs, workingDir); - // List executions = Arrays.asList(exec); - // List executions = FactoryUtils.newArrayList(); - // executions.add(exec); - - // return new Job(executions); - return new Job(exec); + ProcessExecution exec = new ProcessExecution(commandArgs, workingDir); + return new Job(exec); } public static Job singleJavaCall(Runnable runnable) { - return singleJavaCall(runnable, null); + return singleJavaCall(runnable, null); } /** @@ -101,78 +83,36 @@ public static Job singleJavaCall(Runnable runnable) { * @return */ public static Job singleJavaCall(Runnable runnable, String description) { - JavaExecution exec = new JavaExecution(runnable); - - exec.setDescription(description); + JavaExecution exec = new JavaExecution(runnable); - // List executions = FactoryUtils.newArrayList(); - // executions.add(exec); + exec.setDescription(description); - // return new Job(executions); - return new Job(exec); + return new Job(exec); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override public String toString() { - return this.execution.toString(); - /* - if (executions.size() == 1) { - return executions.get(0).toString(); - } - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < executions.size(); i++) { - builder.append("Execution " + (i + 1) + ": "); - builder.append(executions.get(i)); - builder.append("\n"); - } - - // return "Executions:" + executions; - return builder.toString(); - */ + return this.execution.toString(); } public String getCommandString() { - /* - if (executions.isEmpty()) { - return ""; - } - - if (executions.size() > 1) { - LoggingUtils - .msgInfo("Job has more than one execution, returning the command of just the first execution.\n" - + toString()); - } - - // ProcessExecution execution = executions.get(0); - Execution execution = executions.get(0); - */ - if (!(this.execution instanceof ProcessExecution)) { - SpecsLogs - .msgInfo("First job is not of class 'ProcessExecution', returning empty string"); - return ""; - } - - ProcessExecution pExecution = (ProcessExecution) this.execution; - // return execution.getCommandString(); - return pExecution.getCommandString(); + if (!(this.execution instanceof ProcessExecution)) { + SpecsLogs + .msgInfo("First job is not of class 'ProcessExecution', returning empty string"); + return ""; + } + + ProcessExecution pExecution = (ProcessExecution) this.execution; + return pExecution.getCommandString(); } public String getDescription() { - /* - if (executions.size() > 1) { - LoggingUtils - .msgInfo("Job has more than one execution, returning the command of just the first execution.\n" - + toString()); - } - - - return executions.get(0).getDescription(); - */ - return this.execution.getDescription(); + return this.execution.getDescription(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobBuilder.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobBuilder.java index 737d0140..d1c49a13 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobBuilder.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobBuilder.java @@ -23,7 +23,8 @@ public interface JobBuilder { /** - * Builds Jobs according to the given ProgramSources, returns null if any problem happens. + * Builds Jobs according to the given ProgramSources, returns null if any + * problem happens. * * @param outputFolder * @param programs diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobProgress.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobProgress.java index 9e397845..eabf54bb 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobProgress.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobProgress.java @@ -27,41 +27,35 @@ public class JobProgress { /** * INSTANCE VARIABLES */ - // private String jobFilename; private final List jobs; private final int numJobs; private int counter; - // private final static Logger logger = Logger.getLogger(JobProgress.class.getName()); - - // public JobProgress(int numJobs) { public JobProgress(List jobs) { - // this.numJobs = numJobs; - this.jobs = jobs; - this.numJobs = jobs.size(); - this.counter = 0; + this.jobs = jobs; + this.numJobs = jobs.size(); + this.counter = 0; } public void initialMessage() { - SpecsLogs.msgInfo("Found " + this.numJobs + " jobs."); + SpecsLogs.msgInfo("Found " + this.numJobs + " jobs."); } public void nextMessage() { - if (this.counter >= this.numJobs) { - SpecsLogs.warn("Already showed the total number of steps."); - } + if (this.counter >= this.numJobs) { + SpecsLogs.warn("Already showed the total number of steps."); + } - this.counter++; + this.counter++; - String message = "Job " + this.counter + " of " + this.numJobs; + String message = "Job " + this.counter + " of " + this.numJobs; - String description = this.jobs.get(this.counter - 1).getDescription(); - if (description != null) { - message = message + " (" + description + ")."; - } + String description = this.jobs.get(this.counter - 1).getDescription(); + if (description != null) { + message = message + " (" + description + ")."; + } - SpecsLogs.msgInfo(message); - // LoggingUtils.msgInfo("Job " + counter + " of " + numJobs + " (" + description + ")."); + SpecsLogs.msgInfo(message); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobUtils.java index 3335d781..f507473d 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/JobUtils.java @@ -30,7 +30,8 @@ public class JobUtils { /** - * The given path represents a folder that contains several folders, and each folder is a project. + * The given path represents a folder that contains several folders, and each + * folder is a project. * * @param sourceFolder * @param extensions @@ -38,74 +39,52 @@ public class JobUtils { * @return */ public static List getSourcesFoldersMode(File sourceFolder, - Collection extensions, int folderLevel) { - - // System.out.println("SOURCE FOLDER:"+sourceFolder); - - int currentLevel = folderLevel; - List currentFolderList = Arrays.asList(sourceFolder); - while (currentLevel > 0) { - currentLevel--; - - List newFolderList = new ArrayList<>(); - for (File folder : currentFolderList) { - newFolderList.addAll(SpecsIo.getFolders(folder)); - } - - currentFolderList = newFolderList; - // System.out.println("LEVEL "+(folderLevel-currentLevel)+":"+currentFolderList); - } - // System.out.println("FOLDERS:\n"); - // Create filesets - List programSources = new ArrayList<>(); - for (File folder : currentFolderList) { - // System.out.println(folder); - FileSet source = singleFolderProgramSource(folder, extensions); - String outputName = createOutputName(folder, folderLevel); - // System.out.println("OUTPUT NAME:" + outputName); - source.setOutputName(outputName); - - programSources.add(source); - } - /* - // Get existing - - // Get folders - File[] contents = sourceFolder.listFiles(); - for (File folder : contents) { - if (!folder.isDirectory()) { - LoggingUtils.msgInfo("Ignoring file '" + folder.getPath() - + "' in source folders path."); - continue; - } - - FileSet source = singleFolderProgramSource(folder, extensions); - programSources.add(source); - - } - */ - - return programSources; + Collection extensions, int folderLevel) { + + int currentLevel = folderLevel; + List currentFolderList = Arrays.asList(sourceFolder); + while (currentLevel > 0) { + currentLevel--; + + List newFolderList = new ArrayList<>(); + for (File folder : currentFolderList) { + newFolderList.addAll(SpecsIo.getFolders(folder)); + } + + currentFolderList = newFolderList; + } + + // Create filesets + List programSources = new ArrayList<>(); + for (File folder : currentFolderList) { + FileSet source = singleFolderProgramSource(folder, extensions); + String outputName = createOutputName(folder, folderLevel); + source.setOutputName(outputName); + + programSources.add(source); + } + + return programSources; } private static String createOutputName(File folder, int folderLevel) { - // StringBuilder builder = new StringBuilder(); - String currentName = folder.getName(); + String currentName = folder.getName(); - File currentFolder = folder; - for (int i = 1; i < folderLevel; i++) { - File parent = currentFolder.getParentFile(); + File currentFolder = folder; + for (int i = 1; i < folderLevel; i++) { + File parent = currentFolder.getParentFile(); - currentName = parent.getName() + "_" + currentName; - currentFolder = parent; - } + currentName = parent.getName() + "_" + currentName; + currentFolder = parent; + } - return currentName; + return currentName; } /** - * The given path represents a folder that contains several files, each file is a project. + * The given path represents a folder that contains several files, each file is + * a project. * * @param jobOptions * @param targetOptions @@ -113,19 +92,19 @@ private static String createOutputName(File folder, int folderLevel) { */ public static List getSourcesFilesMode(File sourceFolder, Collection extensions) { - // Get extensions - String sourceFoldername = sourceFolder.getPath(); - // Get sources - List files = SpecsIo.getFilesRecursive(sourceFolder, new HashSet<>(extensions)); + // Get extensions + String sourceFoldername = sourceFolder.getPath(); + // Get sources + List files = SpecsIo.getFilesRecursive(sourceFolder, new HashSet<>(extensions)); - // Each file is a program - List programSources = new ArrayList<>(); - for (File file : files) { - FileSet newProgramSource = singleFileProgramSource(file, sourceFoldername); - programSources.add(newProgramSource); - } + // Each file is a program + List programSources = new ArrayList<>(); + for (File file : files) { + FileSet newProgramSource = singleFileProgramSource(file, sourceFoldername); + programSources.add(newProgramSource); + } - return programSources; + return programSources; } /** @@ -136,26 +115,25 @@ public static List getSourcesFilesMode(File sourceFolder, Collection getSourcesSingleFileMode(File sourceFile, - Collection extensions) { + Collection extensions) { - // The file is a program - List programSources = new ArrayList<>(); - String sourceFoldername = sourceFile.getParent(); + // The file is a program + List programSources = new ArrayList<>(); + String sourceFoldername = sourceFile.getParent(); - programSources.add(singleFileProgramSource(sourceFile, sourceFoldername)); + programSources.add(singleFileProgramSource(sourceFile, sourceFoldername)); - return programSources; + return programSources; } public static List getSourcesSingleFolderMode(File sourceFolder, - Collection extensions) { + Collection extensions) { - List programSources = new ArrayList<>(); - // String parentFoldername = sourceFolder.getParent(); + List programSources = new ArrayList<>(); - programSources.add(singleFolderProgramSource(sourceFolder, extensions)); + programSources.add(singleFolderProgramSource(sourceFolder, extensions)); - return programSources; + return programSources; } /** @@ -165,40 +143,40 @@ public static List getSourcesSingleFolderMode(File sourceFolder, * @return */ public static int runJob(Job job) { - int returnValue = job.run(); - if (returnValue != 0) { - SpecsLogs.getLogger().warning( - "Problems while running job: returned value '" + returnValue + "'.\n" + "Job:" - + job.toString() + "\n"); - } - - return returnValue; + int returnValue = job.run(); + if (returnValue != 0) { + SpecsLogs.getLogger().warning( + "Problems while running job: returned value '" + returnValue + "'.\n" + "Job:" + + job.toString() + "\n"); + } + + return returnValue; } /** - * Runs a batch of jobs. If any job terminated abruptly (a job has flag 'isInterruped' active), remaning jobs are - * cancelled. + * Runs a batch of jobs. If any job terminated abruptly (a job has flag + * 'isInterruped' active), remaning jobs are cancelled. * * @param jobs * @return true if all jobs completed successfully, false otherwise */ public static boolean runJobs(List jobs) { - JobProgress jobProgress = new JobProgress(jobs); - jobProgress.initialMessage(); + JobProgress jobProgress = new JobProgress(jobs); + jobProgress.initialMessage(); - for (Job job : jobs) { - jobProgress.nextMessage(); + for (Job job : jobs) { + jobProgress.nextMessage(); - runJob(job); + runJob(job); - // Check if we cancel other jobs. - if (job.isInterrupted()) { - SpecsLogs.getLogger().info("Cancelling remaining jobs."); - return false; - } - } + // Check if we cancel other jobs. + if (job.isInterrupted()) { + SpecsLogs.getLogger().info("Cancelling remaining jobs."); + return false; + } + } - return true; + return true; } /** @@ -213,29 +191,29 @@ public static boolean runJobs(List jobs) { * @return */ private static FileSet singleFolderProgramSource(File sourceFolder, - Collection extensions) { + Collection extensions) { - // Get source files for program - List files = SpecsIo.getFilesRecursive(sourceFolder, extensions); + // Get source files for program + List files = SpecsIo.getFilesRecursive(sourceFolder, extensions); - List sourceFilenames = new ArrayList<>(); - for (File file : files) { - sourceFilenames.add(file.getPath()); - } + List sourceFilenames = new ArrayList<>(); + for (File file : files) { + sourceFilenames.add(file.getPath()); + } - String baseFilename = sourceFolder.getName(); + String baseFilename = sourceFolder.getName(); - return new FileSet(sourceFolder, sourceFilenames, baseFilename); + return new FileSet(sourceFolder, sourceFilenames, baseFilename); } private static FileSet singleFileProgramSource(File sourceFile, String sourceFoldername) { - File sourceFolder = sourceFile.getParentFile(); + File sourceFolder = sourceFile.getParentFile(); - List sourceFilenames = new ArrayList<>(); - sourceFilenames.add(sourceFile.getPath()); + List sourceFilenames = new ArrayList<>(); + sourceFilenames.add(sourceFile.getPath()); - String outputName = SpecsIo.removeExtension(sourceFile.getName()); + String outputName = SpecsIo.removeExtension(sourceFile.getName()); - return new FileSet(sourceFolder, sourceFilenames, outputName); + return new FileSet(sourceFolder, sourceFilenames, outputName); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/JavaExecution.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/JavaExecution.java index d8e52ea6..a5a7eac3 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/JavaExecution.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/JavaExecution.java @@ -24,41 +24,41 @@ public class JavaExecution implements Execution { private String description; public JavaExecution(Runnable runnable) { - this.runnable = runnable; - this.interrupted = false; + this.runnable = runnable; + this.interrupted = false; - this.description = null; + this.description = null; } @Override public int run() { - try { - this.runnable.run(); - } catch (Exception e) { - SpecsLogs.warn(e.getMessage(), e); - this.interrupted = true; - return -1; - } + try { + this.runnable.run(); + } catch (Exception e) { + SpecsLogs.warn(e.getMessage(), e); + this.interrupted = true; + return -1; + } - return 0; + return 0; } @Override public boolean isInterrupted() { - return this.interrupted; + return this.interrupted; } @Override public String getDescription() { - if (this.description == null) { - return JavaExecution.DEFAULT_MESSAGE; - } + if (this.description == null) { + return JavaExecution.DEFAULT_MESSAGE; + } - return this.description; + return this.description; } public void setDescription(String description) { - this.description = description; + this.description = description; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/ProcessExecution.java b/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/ProcessExecution.java index c5d0cc10..e51b3472 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/ProcessExecution.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/jobs/execution/ProcessExecution.java @@ -33,10 +33,10 @@ public class ProcessExecution implements Execution { boolean interrupted; public ProcessExecution(List commandArgs, String workingFoldername) { - this.commandArgs = commandArgs; - this.workingFoldername = workingFoldername; + this.commandArgs = commandArgs; + this.workingFoldername = workingFoldername; - this.interrupted = false; + this.interrupted = false; } /** @@ -46,68 +46,37 @@ public ProcessExecution(List commandArgs, String workingFoldername) { */ @Override public int run() { - return SpecsSystem.run(this.commandArgs, new File(this.workingFoldername)); - /* - int result = -1; - try { - // LoggingUtils.msgLib("Command:" + commandToString(commandArgs)); - // result = ProcessUtils.runProcess(commandArgs, IoUtils.getWorkingDir().getPath()); - result = ProcessUtils.runProcess(commandArgs, workingFoldername); - - } catch (InterruptedException ex) { - LoggingUtils.msgInfo("Command cancelled."); - interrupted = true; - Thread.currentThread().interrupt(); - return 0; - } - return result; - */ + return SpecsSystem.run(this.commandArgs, new File(this.workingFoldername)); } - /* - public static String commandToString(List command) { - if (command.isEmpty()) { - return ""; - } - - StringBuilder builder = new StringBuilder(); - builder.append(command.get(0)); - for (int i = 1; i < command.size(); i++) { - builder.append(" "); - builder.append(command.get(i)); - } - - return builder.toString(); - } - */ @Override public boolean isInterrupted() { - return this.interrupted; + return this.interrupted; } public String getCommandString() { - if (this.commandArgs.isEmpty()) { - return ""; - } - - StringBuilder builder = new StringBuilder(); - builder.append(this.commandArgs.get(0)); - for (int i = 1; i < this.commandArgs.size(); i++) { - builder.append(" "); - builder.append(this.commandArgs.get(i)); - } - - return builder.toString(); + if (this.commandArgs.isEmpty()) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + builder.append(this.commandArgs.get(0)); + for (int i = 1; i < this.commandArgs.size(); i++) { + builder.append(" "); + builder.append(this.commandArgs.get(i)); + } + + return builder.toString(); } @Override public String toString() { - return getCommandString(); + return getCommandString(); } @Override public String getDescription() { - return "Run '" + this.commandArgs.get(0) + "'"; + return "Run '" + this.commandArgs.get(0) + "'"; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/lazy/Lazy.java b/SpecsUtils/src/pt/up/fe/specs/util/lazy/Lazy.java index 2c742384..91c8cb99 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/lazy/Lazy.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/lazy/Lazy.java @@ -28,7 +28,8 @@ public interface Lazy extends Supplier { /** * - * @return true if the value encapsulated by the Lazy object has been initialized + * @return true if the value encapsulated by the Lazy object has been + * initialized */ boolean isInitialized(); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/lazy/ThreadSafeLazy.java b/SpecsUtils/src/pt/up/fe/specs/util/lazy/ThreadSafeLazy.java index cca899a0..b4f2fe0b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/lazy/ThreadSafeLazy.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/lazy/ThreadSafeLazy.java @@ -18,7 +18,6 @@ /** * Encapsulates an object which has an expensive initialization. * - * * @author Luis Cubal * * @param @@ -48,7 +47,9 @@ public T getValue() { return get(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.Utilities.Lazy#get() */ @Override diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/ConsoleFormatter.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/ConsoleFormatter.java index ef67ea74..f739e18c 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/ConsoleFormatter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/ConsoleFormatter.java @@ -16,10 +16,9 @@ import java.util.logging.Formatter; import java.util.logging.LogRecord; -// import pt.up.fe.specs.util.Utilities.LineReader; - /** - * Extension of Formatter class, used for presenting logging information on a screen. + * Extension of Formatter class, used for presenting logging information on a + * screen. * * @author Joao Bispo */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/CustomConsoleHandler.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/CustomConsoleHandler.java index 5b6d4649..07a1dcc0 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/CustomConsoleHandler.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/CustomConsoleHandler.java @@ -24,7 +24,8 @@ public class CustomConsoleHandler extends StreamHandler { /** * Create a ConsoleHandler for System.err. *

- * The ConsoleHandler is configured based on LogManager properties (or their default values). + * The ConsoleHandler is configured based on LogManager + * properties (or their default values). * */ private CustomConsoleHandler(PrintStream printStream) { @@ -53,12 +54,12 @@ public static CustomConsoleHandler newStderr() { /** * Publish a LogRecord. *

- * The logging request was made initially to a Logger object, which initialized the LogRecord and - * forwarded it here. + * The logging request was made initially to a Logger object, which + * initialized the LogRecord and forwarded it here. *

* - * @param record - * description of the log event. A null record is silently ignored and is not published + * @param record description of the log event. A null record is silently ignored + * and is not published */ @Override public synchronized void publish(LogRecord record) { @@ -68,8 +69,8 @@ public synchronized void publish(LogRecord record) { } /** - * Override StreamHandler.close to do a flush but not to close the output stream. That is, we do not - * close System.err. + * Override StreamHandler.close to do a flush but not to close the + * output stream. That is, we do not close System.err. */ @Override public synchronized void close() { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/EnumLogger.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/EnumLogger.java index 4dc1843a..db4eb41f 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/EnumLogger.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/EnumLogger.java @@ -42,12 +42,4 @@ static > EnumLogger newInstance(Class enumClass) { return () -> enumClass; } - // default void warn(T tag, String message) { - // LogsHelper.logMessage(getClass().getName(), tag, message, (logger, msg) -> logger.warn(msg)); - // } - // - // default void warn(String message) { - // warn(null, message); - // } - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/LogSourceInfo.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/LogSourceInfo.java index 8cf48057..58792827 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/LogSourceInfo.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/LogSourceInfo.java @@ -45,7 +45,7 @@ public static LogSourceInfo getLogSourceInfo(Level level) { if (level == null) { return NONE; } - + LogSourceInfo info = LOGGER_SOURCE_INFO.get(level); return info != null ? info : NONE; @@ -59,7 +59,7 @@ public static void setLogSourceInfo(Level level, LogSourceInfo info) { if (info == null) { throw new NullPointerException("LogSourceInfo cannot be null"); } - + LOGGER_SOURCE_INFO.put(level, info); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggerWrapper.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggerWrapper.java index 82b7a4c9..bc63f1a1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggerWrapper.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggerWrapper.java @@ -16,7 +16,8 @@ import java.util.logging.Logger; /** - * Wrapper around java.util.logging.Logger, which extends class with some logging methods. + * Wrapper around java.util.logging.Logger, which extends class with some + * logging methods. * * @author JoaoBispo * @@ -33,7 +34,7 @@ public LoggerWrapper(String name) { if (name == null) { throw new NullPointerException("Logger name cannot be null"); } - + this.logger = Logger.getLogger(name); } @@ -51,7 +52,6 @@ public Logger getJavaLogger() { *

* Use this level to show messages to the user of a program. * - * * @param logger * @param msg */ @@ -72,7 +72,7 @@ private String parseMessage(String msg) { if (msg == null) { return null; } - + if (msg.isEmpty()) { return msg; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggingOutputStream.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggingOutputStream.java index 2f1fc775..e1eeabe9 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggingOutputStream.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/LoggingOutputStream.java @@ -22,7 +22,8 @@ * An OutputStream that writes contents to a Logger upon each call to flush(). * *

- * This class is used by LoggingUtils methods to redirect the System.out and System.err streams. + * This class is used by LoggingUtils methods to redirect the System.out and + * System.err streams. * * @author Joao Bispo * @author http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and @@ -38,41 +39,37 @@ public class LoggingOutputStream extends ByteArrayOutputStream { /** * Constructor * - * @param logger - * Logger to write to - * @param level - * Level at which to write the log message + * @param logger Logger to write to + * @param level Level at which to write the log message */ public LoggingOutputStream(Logger logger, Level level) { - super(); - this.logger = logger; - this.level = level; - // lineSeparator = System.getProperty("line.separator"); + super(); + this.logger = logger; + this.level = level; } /** - * Upon flush() write the existing contents of the OutputStream to the logger as a log record. + * Upon flush() write the existing contents of the OutputStream to the logger as + * a log record. * - * @throws java.io.IOException - * in case of error + * @throws java.io.IOException in case of error */ @Override public void flush() throws IOException { - String record; - synchronized (this) { - super.flush(); - record = this.toString(); - super.reset(); + String record; + synchronized (this) { + super.flush(); + record = this.toString(); + super.reset(); - // if (record.length() == 0 || record.equals(lineSeparator)) { - if (record.length() == 0) { - // avoid empty records - return; - } + if (record.length() == 0) { + // avoid empty records + return; + } - this.logger.logp(this.level, "", "", record); - } + this.logger.logp(this.level, "", "", record); + } } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/SimpleFileHandler.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/SimpleFileHandler.java index 164089e1..d65c23b6 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/SimpleFileHandler.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/SimpleFileHandler.java @@ -22,48 +22,36 @@ public class SimpleFileHandler extends StreamHandler { /** * Create a ConsoleHandler for System.err. *

- * The ConsoleHandler is configured based on LogManager properties (or their default values). + * The ConsoleHandler is configured based on LogManager + * properties (or their default values). * */ public SimpleFileHandler(PrintStream printStream) { - setOutputStream(printStream); + setOutputStream(printStream); } - /* - public static SimpleFileHandler newInstance(File logFile) { - FileOutputStream outputStream = null; - - try { - outputStream = new FileOutputStream(logFile); - } catch (FileNotFoundException e) { - return null; - } - - return new SimpleFileHandler(new PrintStream(outputStream)); - } - */ /** * Publish a LogRecord. *

- * The logging request was made initially to a Logger object, which initialized the LogRecord and - * forwarded it here. + * The logging request was made initially to a Logger object, which + * initialized the LogRecord and forwarded it here. *

* - * @param record - * description of the log event. A null record is silently ignored and is not published + * @param record description of the log event. A null record is silently ignored + * and is not published */ @Override public synchronized void publish(LogRecord record) { - super.publish(record); - flush(); + super.publish(record); + flush(); } /** - * Override StreamHandler.close to do a flush but not to close the output stream. That is, we do not - * close System.err. + * Override StreamHandler.close to do a flush but not to close the + * output stream. That is, we do not close System.err. */ @Override public synchronized void close() { - flush(); + flush(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLoggers.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLoggers.java index 2173615d..f1dcfafc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLoggers.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLoggers.java @@ -32,7 +32,7 @@ static Logger getLogger(String loggerName) { if (loggerName == null) { throw new NullPointerException("Logger name cannot be null"); } - + Logger logger = LOGGERS.get(loggerName); if (logger == null) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLogging.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLogging.java index 6a824d90..94143c8d 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLogging.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/SpecsLogging.java @@ -39,12 +39,9 @@ public class SpecsLogging { addClassToIgnore(TagLogger.class); } - // private final static Set METHOD_NAME_IGNORE = new HashSet<>( - // Arrays.asList("log", "info", "warn", "debug", "deprecated", "warning")); - /** - * Adds a class to the ignore list for determining what should appear when a stack trace or source code location is - * printed. + * Adds a class to the ignore list for determining what should appear when a + * stack trace or source code location is printed. * * @param aClass */ @@ -62,14 +59,14 @@ public static String getPrefix(Object tag) { public static String getLogSuffix(LogSourceInfo logSuffix, StackTraceElement[] stackTrace) { switch (logSuffix) { - case NONE: - return ""; - case SOURCE: - return getSourceCodeLocation(stackTrace); - case STACK_TRACE: - return getStackTrace(stackTrace); - default: - throw new NotImplementedException(logSuffix); + case NONE: + return ""; + case SOURCE: + return getSourceCodeLocation(stackTrace); + case STACK_TRACE: + return getStackTrace(stackTrace); + default: + throw new NotImplementedException(logSuffix); } } @@ -130,15 +127,6 @@ private static boolean ignoreStackTraceElement(StackTraceElement stackTraceEleme return true; } - // Check if in method name ignore list - // if (METHOD_NAME_IGNORE.contains(stackTraceElement.getMethodName())) { - // return true; - // } - - // System.out.println("File name:" + stackTraceElement.getFileName()); - // System.out.println("Class name:" + stackTraceElement.getClassName()); - // System.out.println("Method name:" + stackTraceElement.getMethodName()); - return false; } @@ -146,7 +134,6 @@ public static String getSourceCode(StackTraceElement s) { StringBuilder builder = new StringBuilder(); builder.append(" -> "); - // builder.append("[ "); builder.append(s.getClassName()); builder.append("."); builder.append(s.getMethodName()); @@ -155,7 +142,6 @@ public static String getSourceCode(StackTraceElement s) { builder.append(":"); builder.append(s.getLineNumber()); builder.append(")"); - // builder.append(" ]"); return builder.toString(); } @@ -188,7 +174,4 @@ public static String parseMessage(Object tag, String msg, LogSourceInfo logSuffi return parsedMessage; } - // public static String parseMessage(Object tag, String msg) { - // return parseMessage(tag, msg, Collections.emptyList()); - // } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/StringHandler.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/StringHandler.java index dc52e370..63166ec7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/StringHandler.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/StringHandler.java @@ -51,17 +51,17 @@ public synchronized void publish(LogRecord record) { if (record == null) { return; } - + // Check level filtering if (record.getLevel().intValue() < this.getLevel().intValue()) { return; } - + // Check filter if set if (this.getFilter() != null && !this.getFilter().isLoggable(record)) { return; } - + this.buffer.append(record.getMessage()); flush(); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/TagLogger.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/TagLogger.java index ef25f351..ce797fd8 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/TagLogger.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/TagLogger.java @@ -68,15 +68,6 @@ default void log(Level level, T tag, String message, LogSourceInfo logSourceInfo // Obtain logger Logger logger = SpecsLoggers.getLogger(getLoggerName(tag)); logger.log(level, SpecsLogging.parseMessage(tag, message, logSourceInfo, stackTrace)); - /* - // Obtain stack trace - - // Log using stack trace - - } else { - logger.log(level, SpecsLogging.parseMessage(tag, message)); - } - */ } default void log(Level level, String message) { @@ -85,37 +76,18 @@ default void log(Level level, String message) { default void info(T tag, String message) { log(Level.INFO, tag, message); - /* - // LogsHelper.logMessage(getLoggerName(tag), tag, message, (logger, msg) -> logger.info(msg)); - - // String prefix = SpecsLogging.getPrefix(tag); - - Logger logger = SpecsLoggers.getLogger(getLoggerName(tag)); - // System.out.println("LEVEL:" + logger.getJavaLogger().getLevel()); - - logger.info(SpecsLogging.parseMessage(tag, message)); - // System.out.println("ADASD"); - // logging.accept(logger, prefix + message); - */ - } default void info(String message) { info(null, message); } - // default void debug(String message) { - // debug(message, true); - // } - // - // default void debug(String message, boolean sourceInfo) { default void debug(String message) { debug(() -> message); } default void debug(Supplier message) { if (SpecsSystem.isDebug()) { - // LogSourceInfo sourceInfoLevel = sourceInfo ? LogSourceInfo.SOURCE : LogSourceInfo.NONE)); log(Level.INFO, null, "[DEBUG] " + message.get()); } } @@ -137,7 +109,8 @@ default void warn(String message) { } /** - * Adds a class to the ignore list when printing the stack trace, or the source code location. + * Adds a class to the ignore list when printing the stack trace, or the source + * code location. * * @param aClass */ @@ -145,121 +118,4 @@ default TagLogger addToIgnoreList(Class aClass) { SpecsLogging.addClassToIgnore(aClass); return this; } - - /* - default void warn(T tag, String msg, List elements, int startIndex, boolean appendCallingClass) { - - msg = "[WARNING]: " + msg; - msg = parseMessage(msg); - msg = buildErrorMessage(msg, elements.subList(startIndex, elements.size())); - - if (appendCallingClass) { - logger = logger == null ? getLoggerDebug() : logger; - logger.warning(msg); - // getLoggerDebug().warning(msg); - } else { - logger = logger == null ? getLogger() : logger; - logger.warning(msg); - // getLogger().warning(msg); - } - } - */ - - /** - * Writes a message to the logger with name defined by LOGGING_TAG. - * - *

- * Messages written with this method are recorded as a log at warning level. Use this level to show a message for - * cases that are supposed to never happen if the code is well used. - * - * @param msg - */ - /* - public static void msgWarn(String msg) { - - final List elements = Arrays.asList(Thread.currentThread().getStackTrace()); - final int startIndex = 2; - - msgWarn(msg, elements, startIndex, true, null); - } - - public static void msgWarn(Logger logger, String msg) { - - final List elements = Arrays.asList(Thread.currentThread().getStackTrace()); - final int startIndex = 2; - - msgWarn(msg, elements, startIndex, true, logger); - } - - private static void msgWarn(String msg, List elements, int startIndex, - boolean appendCallingClass, Logger logger) { - - msg = "[WARNING]: " + msg; - msg = parseMessage(msg); - msg = buildErrorMessage(msg, elements.subList(startIndex, elements.size())); - - if (appendCallingClass) { - logger = logger == null ? getLoggerDebug() : logger; - logger.warning(msg); - // getLoggerDebug().warning(msg); - } else { - logger = logger == null ? getLogger() : logger; - logger.warning(msg); - // getLogger().warning(msg); - } - } - - public static void msgWarn(String msg, Throwable ourCause) { - - // Get the root cause - while (ourCause.getCause() != null) { - ourCause = ourCause.getCause(); - } - - // Save current place where message is being issued - final List currentElements = Arrays.asList(Thread.currentThread().getStackTrace()); - final StackTraceElement currentElement = currentElements.get(2); - final String msgSource = "\n\n[Catch]:\n" + currentElement; - - String causeString = ourCause.getMessage(); - if (causeString == null) { - causeString = ourCause.toString(); - } - - final String causeMsg = causeString + msgSource; - - // msg = msg + "\nCause: [" + ourCause.getClass().getSimpleName() + "] " + ourCause.getMessage() + msgSource; - msg = msg + "\nCause: " + causeMsg; - - final List elements = Arrays.asList(ourCause.getStackTrace()); - final int startIndex = 0; - - msgWarn(msg, elements, startIndex, false, null); - } - - public static void msgWarn(Throwable cause) { - - final List elements = Arrays.asList(cause.getStackTrace()); - final int startIndex = 0; - - final String msg = cause.getClass().getName() + ": " + cause.getMessage(); - - msgWarn(msg, elements, startIndex, false, null); - - } - - */ - - // static > TagLogger newInstance(Class enumClass) { - // return () -> enumClass; - // } - - // default void warn(T tag, String message) { - // LogsHelper.logMessage(getClass().getName(), tag, message, (logger, msg) -> logger.warn(msg)); - // } - // - // default void warn(String message) { - // warn(null, message); - // } - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/logging/TextAreaHandler.java b/SpecsUtils/src/pt/up/fe/specs/util/logging/TextAreaHandler.java index e5cde36d..a4edb460 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/logging/TextAreaHandler.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/logging/TextAreaHandler.java @@ -40,12 +40,12 @@ public synchronized void publish(LogRecord record) { if (record == null) { return; } - + // Check level filtering if (record.getLevel().intValue() < this.getLevel().intValue()) { return; } - + // Check filter if set if (this.getFilter() != null && !this.getFilter().isLoggable(record)) { return; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/GenericCodec.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/GenericCodec.java index c8bf76e5..e986d733 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/GenericCodec.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/GenericCodec.java @@ -18,9 +18,6 @@ class GenericCodec implements StringCodec, Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private final Function encoder; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/ListParser.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/ListParser.java index fcddedd4..3df09efc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/ListParser.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/ListParser.java @@ -40,8 +40,8 @@ public List getList() { * * * @param aClass - * @return a list with the consecutive elements of the given class, starting at the head. These elements are removed - * from this list + * @return a list with the consecutive elements of the given class, starting at + * the head. These elements are removed from this list */ public List pop(Class aClass) { if (currentList.isEmpty()) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringCodec.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringCodec.java index 04fbbd69..732083a7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringCodec.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringCodec.java @@ -19,7 +19,8 @@ * Encodes/decodes values to/from Strings. * *

- * It is recommended that the decoder supports null strings as inputs, to be able to decode 'empty values'. + * It is recommended that the decoder supports null strings as inputs, to be + * able to decode 'empty values'. * * @author JoaoBispo * diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringDecoder.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringDecoder.java index ef2bd34f..667649f1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringDecoder.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/StringDecoder.java @@ -18,7 +18,8 @@ public interface StringDecoder extends Function { /** - * Attempts to decode the given String into an Object T. If the decoding fails, returns null. + * Attempts to decode the given String into an Object T. If the decoding fails, + * returns null. */ @Override T apply(String t); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/ArgumentsParser.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/ArgumentsParser.java index 732818a4..399f6890 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/ArgumentsParser.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/ArgumentsParser.java @@ -39,8 +39,8 @@ public ArgumentsParser(List delimiters, List gluers, List } /** - * Argument parser that delimits arguments by spaces (' '), glues them with double quotes ('"') and escapes single - * characters with backslash ('\'). + * Argument parser that delimits arguments by spaces (' '), glues them with + * double quotes ('"') and escapes single characters with backslash ('\'). * * @return */ @@ -120,7 +120,8 @@ public List parse(String string) { // Delimiters are only enabled if there is no current gluer if (currentGluer == null) { Optional delimiter = checkDelimiters(slice); - // If there is a delimiter, store current argument (if not empty) and reset current argument + // If there is a delimiter, store current argument (if not empty) and reset + // current argument if (delimiter.isPresent()) { // Update slice slice = slice.substring(delimiter.get().length()); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/Gluer.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/Gluer.java index a8da80e6..905a5dce 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/Gluer.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/Gluer.java @@ -27,7 +27,6 @@ public Gluer(String start, String end, boolean keepDelimiters) { this.delimiterStart = start; this.delimiterEnd = end; this.keepDelimiters = keepDelimiters; - } /** diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/MultiLineCommentRule.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/MultiLineCommentRule.java index eff28eb3..374e410a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/MultiLineCommentRule.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/MultiLineCommentRule.java @@ -58,10 +58,6 @@ public Optional apply(String line, Iterator iterator) { currentLine = iterator.next(); } - // If no endIndex found, comment is malformed - // Preconditions.checkArgument(endIndex != -1, - // "Could not find end of multi-line comment start at '" + filepath + "':" + lineNumber); - return Optional.of(TextElement.newInstance(TextElementType.MULTILINE_COMMENT, lines.stream().collect(Collectors.joining("\n")))); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/TextParserRule.java b/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/TextParserRule.java index 4af85810..b29a182e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/TextParserRule.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/parsing/comments/TextParserRule.java @@ -19,9 +19,10 @@ public interface TextParserRule { /** - * For single line rules, the iterator will not be needed. In cases where the rule can spawn multiple lines, the - * rule must leave the iterator ready for returning the next line to be processed. This means that it can only - * consume the lines it will process. + * For single line rules, the iterator will not be needed. In cases where the + * rule can spawn multiple lines, the rule must leave the iterator ready for + * returning the next line to be processed. This means that it can only consume + * the lines it will process. * * @param line * @param lineNumber diff --git a/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperties.java b/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperties.java index 0ab8e928..5476cc80 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperties.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperties.java @@ -51,7 +51,8 @@ public static SpecsProperties newEmpty() { } /** - * Helper method which accepts a ResourceProvider and copies the file if it does not exist. + * Helper method which accepts a ResourceProvider and copies the file if it does + * not exist. * * @param resource * @return @@ -59,14 +60,7 @@ public static SpecsProperties newEmpty() { public static SpecsProperties newInstance(ResourceProvider resource) { File propsFile = resource.writeVersioned(SpecsIo.getWorkingDir(), resource.getClass()).getFile(); - /* - File propsFile = new File(resource.getResourceName()); - - // If file does not exist, copy resource - if (!propsFile.isFile()) { - propsFile = IoUtils.resourceCopy(resource.getResource(), IoUtils.getWorkingDir(), false); - } - */ + return newInstance(propsFile); } @@ -81,15 +75,16 @@ public static SpecsProperties newInstance(File propertiesFile) { } /** - * Given a File object, loads the contents of the file into a Java Properties object. + * Given a File object, loads the contents of the file into a Java Properties + * object. * *

- * If an error occurs (ex.: the File argument does not represent a file, could not load the Properties object) - * returns null and logs the cause. + * If an error occurs (ex.: the File argument does not represent a file, could + * not load the Properties object) returns null and logs the cause. * - * @param file - * a File object representing a file. - * @return If successfull, a Properties objects with the contents of the file. Null otherwise. + * @param file a File object representing a file. + * @return If successfull, a Properties objects with the contents of the file. + * Null otherwise. */ private static SpecsProperties load(InputStream inputStream) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperty.java b/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperty.java index e1b9fd55..fbfe87f2 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperty.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/properties/SpecsProperty.java @@ -48,11 +48,13 @@ public enum SpecsProperty { */ WriteErroLog, /** - * Shows the stack trace when warning messages are called. Receives a boolean value. + * Shows the stack trace when warning messages are called. Receives a boolean + * value. */ ShowStackTrace, /** - * Opens a Swing window (if available) showing information about memory usage of the application. Receives a boolean + * Opens a Swing window (if available) showing information about memory usage of + * the application. Receives a boolean * value. */ ShowMemoryHeap, @@ -84,7 +86,8 @@ public static void applyProperties(Properties suikaProps) { } /** - * Looks for the file 'suika.properties' on the running folder and applies its options. + * Looks for the file 'suika.properties' on the running folder and applies its + * options. */ public static void applyProperties() { // Look for compatible files representing specs properties, return the first @@ -107,22 +110,13 @@ public static void applyProperties() { SpecsLogs.debug("Applying the SPeCS properties file '" + specsPropertiesFile.getAbsolutePath() + "'"); Properties specsProperties = SpecsProperties.newInstance(specsPropertiesFile).getProperties(); SpecsProperty.applyProperties(specsProperties); - - // File suikaPropsFile = new File("suika.properties"); - // if (!suikaPropsFile.isFile()) { - // // System.out.println("did not find file "+suikaPropsFile); - // return; - // } - - // Properties suikaProps = IoUtils.loadProperties(suikaPropsFile); - // Properties suikaProps = SpecsProperties.newInstance(suikaPropsFile).getProperties(); - // SpecsProperty.applyProperties(suikaProps); } /** * A default suika.properties file. * - * @return a Collection for Strings representing resources needed for this package to run. + * @return a Collection for Strings representing resources needed for this + * package to run. */ public static Collection getResources() { List resources = new ArrayList<>(); @@ -217,15 +211,6 @@ public void applyProperty(String value) { // Set Custom L&F SpecsSwing.setCustomLookAndFeel(lookAndFeel); - // try { - // System.out.println("CUSTOM LOOK: " + lookAndFeel); - // System.out.println("SYSTEM BEFORE: " + UIManager.getSystemLookAndFeelClassName()); - // UIManager.setLookAndFeel(lookAndFeel); - // System.out.println("SYSTEM AFTER: " + UIManager.getSystemLookAndFeelClassName()); - // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException - // | UnsupportedLookAndFeelException e) { - // throw new RuntimeException("Could not set custom Look&Feel", e); - // } return; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceManager.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceManager.java index 292536fc..ffca0bb9 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceManager.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceManager.java @@ -46,7 +46,7 @@ public class FileResourceManager { /** * Creates a FileResourceManager instance from an enum class. * - * @param the type of the enum + * @param the type of the enum * @param enumClass the class of the enum * @return a new FileResourceManager instance */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceProvider.java index e8767106..f8f18ce1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/FileResourceProvider.java @@ -44,9 +44,10 @@ static FileResourceProvider newInstance(File existingFile) { } /** - * Creates a new instance of FileResourceProvider for an existing file with a version suffix. + * Creates a new instance of FileResourceProvider for an existing file with a + * version suffix. * - * @param existingFile the file to be wrapped by the provider + * @param existingFile the file to be wrapped by the provider * @param versionSuffix the version suffix to be appended * @return a new instance of FileResourceProvider */ @@ -70,7 +71,7 @@ public static class ResourceWriteData { * Constructs a ResourceWriteData object. * * @param writtenFile the file that was written - * @param newFile whether the file is new + * @param newFile whether the file is new */ public ResourceWriteData(File writtenFile, boolean newFile) { Preconditions.checkNotNull(writtenFile, "writtenFile should not be null"); @@ -139,18 +140,21 @@ public void makeExecutable(boolean isLinux) { String getFilename(); /** - * Copies this resource to the destination folder. If the file already exists, uses method getVersion() to determine - * if the file should be overwritten or not. + * Copies this resource to the destination folder. If the file already exists, + * uses method getVersion() to determine if the file should be overwritten or + * not. *

- * If the file already exists but no versioning information is available in the system, the file is overwritten. + * If the file already exists but no versioning information is available in the + * system, the file is overwritten. *

- * The method will use the package of the class indicated in 'context' as the location to store the information - * about versioning. Keep in mind that calls using the same context will refer to the same local copy of the - * resource. + * The method will use the package of the class indicated in 'context' as the + * location to store the information about versioning. Keep in mind that calls + * using the same context will refer to the same local copy of the resource. * - * @param folder the destination folder + * @param folder the destination folder * @param context the class used to store versioning information - * @return a ResourceWriteData object containing information about the written file + * @return a ResourceWriteData object containing information about the written + * file */ default ResourceWriteData writeVersioned(File folder, Class context) { return writeVersioned(folder, context, true); @@ -159,14 +163,15 @@ default ResourceWriteData writeVersioned(File folder, Class context) { /** * Copies this resource to the destination folder with versioning information. * - * @param folder the destination folder - * @param context the class used to store versioning information - * @param writeIfNoVersionInfo whether to write the file if no versioning information is available - * @return a ResourceWriteData object containing information about the written file + * @param folder the destination folder + * @param context the class used to store versioning information + * @param writeIfNoVersionInfo whether to write the file if no versioning + * information is available + * @return a ResourceWriteData object containing information about the written + * file */ default ResourceWriteData writeVersioned(File folder, Class context, boolean writeIfNoVersionInfo) { // Create file - // String resourceOutput = usePath ? getFilepath() : getFilename(); String resourceOutput = getFilename(); File destination = new File(folder, resourceOutput); @@ -186,7 +191,8 @@ default ResourceWriteData writeVersioned(File folder, Class context, boolean String NOT_FOUND = ""; String version = prefs.get(key, NOT_FOUND); - // If current version is the same as the version of the resource just return the existing file + // If current version is the same as the version of the resource just return the + // existing file if (version.equals(getVersion())) { return new ResourceWriteData(destination, false); } @@ -221,9 +227,10 @@ default ResourceWriteData writeVersioned(File folder, Class context, boolean /** * Creates a resource for the given version. *

- * It changes the resource path by appending an underscore and the given version as a suffix, before any - * extension.
- * E.g., if the original resource is "path/executable.exe", returns a resource to "path/executable.exe". + * It changes the resource path by appending an underscore and the given version + * as a suffix, before any extension.
+ * E.g., if the original resource is "path/executable.exe", returns a resource + * to "path/executable.exe". *

* * @param version the version suffix to be appended diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyEnumNameProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyEnumNameProvider.java index 85be2dcd..4cdeed58 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyEnumNameProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyEnumNameProvider.java @@ -40,6 +40,6 @@ public interface KeyEnumNameProvider extends KeyStringProvider { */ @Override default String getKey() { - return name(); + return name(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyStringProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyStringProvider.java index b9aa0800..07c9842f 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyStringProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/KeyStringProvider.java @@ -34,7 +34,7 @@ public interface KeyStringProvider extends KeyProvider { * @return a list of string keys provided by the instances */ public static List toList(KeyStringProvider... providers) { - return toList(Arrays.asList(providers)); + return toList(Arrays.asList(providers)); } /** @@ -44,11 +44,11 @@ public static List toList(KeyStringProvider... providers) { * @return a list of string keys provided by the instances */ public static List toList(List providers) { - List strings = new ArrayList<>(); + List strings = new ArrayList<>(); - providers.forEach(stringProvider -> strings.add(stringProvider.getKey())); + providers.forEach(stringProvider -> strings.add(stringProvider.getKey())); - return strings; + return strings; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/ProvidersSupport.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/ProvidersSupport.java index cf44986e..350543a8 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/ProvidersSupport.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/ProvidersSupport.java @@ -28,7 +28,8 @@ */ public class ProvidersSupport { /** - * Retrieves a list of resources from a single enum class implementing the ResourceProvider interface. + * Retrieves a list of resources from a single enum class implementing the + * ResourceProvider interface. * * @param enumClass the class of the enum implementing ResourceProvider * @return a list of resources provided by the enum diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/ResourceProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/ResourceProvider.java index 52c57d46..a41b13fd 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/ResourceProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/ResourceProvider.java @@ -35,7 +35,8 @@ * Represents a class which provides a string to a Java resource. * *

- * The resource must exist, the ResourceProvider is responsible for guaranteeing that the resource is valid. + * The resource must exist, the ResourceProvider is responsible for guaranteeing + * that the resource is valid. * * @author Joao Bispo * @see SpecsIo#getResource(ResourceProvider) @@ -55,10 +56,11 @@ static ResourceProvider newInstance(String resource) { } /** - * Creates a new instance of ResourceProvider with the given resource string and version. + * Creates a new instance of ResourceProvider with the given resource string and + * version. * * @param resource the resource string - * @param version the version string + * @param version the version string * @return a new ResourceProvider instance */ static ResourceProvider newInstance(String resource, String version) { @@ -85,7 +87,8 @@ static String getDefaultVersion() { String getResource(); /** - * Returns a list with all the resources, in case this class is an enum. Otherwise, returns an empty list. + * Returns a list with all the resources, in case this class is an enum. + * Otherwise, returns an empty list. * * @return a list of ResourceProvider instances */ @@ -136,7 +139,8 @@ public static List getResourcesFromEnum(Class name // Write file boolean success = SpecsIo.resourceCopyWithName(getResource(), filename, folder); - /* - boolean success = SpecsIo.write(outputFile, SpecsIo.getResource(this)); - */ + if (!success) { throw new RuntimeException("Could not write file '" + outputFile + "'"); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/Resources.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/Resources.java index 7be71475..74d65ccc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/Resources.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/Resources.java @@ -38,7 +38,8 @@ public class Resources { private final List resources; /** - * Constructs a Resources object with a base folder and an array of resource names. + * Constructs a Resources object with a base folder and an array of resource + * names. * * @param baseFolder the base folder where resources are located * @param resources an array of resource names @@ -48,7 +49,8 @@ public Resources(String baseFolder, String... resources) { } /** - * Constructs a Resources object with a base folder and a list of resource names. + * Constructs a Resources object with a base folder and a list of resource + * names. * * @param baseFolder the base folder where resources are located * @param resources a list of resource names diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/StringProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/StringProvider.java index 8734b2e7..44955289 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/StringProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/StringProvider.java @@ -36,7 +36,8 @@ public interface StringProvider extends KeyProvider { String getString(); /** - * Returns the key associated with this StringProvider, which is the string itself. + * Returns the key associated with this StringProvider, which is the string + * itself. * * @return the key */ @@ -66,7 +67,8 @@ static StringProvider newInstance(File file) { } /** - * Creates a new StringProvider backed by the contents of the given ResourceProvider. + * Creates a new StringProvider backed by the contents of the given + * ResourceProvider. * * @param resource the resource whose contents will be provided * @return a new StringProvider instance diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/WebResourceProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/WebResourceProvider.java index cc179964..31a7079f 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/WebResourceProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/WebResourceProvider.java @@ -34,9 +34,10 @@ public interface WebResourceProvider extends FileResourceProvider { /** - * Creates a new instance of WebResourceProvider with the given root URL and resource URL. + * Creates a new instance of WebResourceProvider with the given root URL and + * resource URL. * - * @param rootUrl the root URL of the web resource + * @param rootUrl the root URL of the web resource * @param resourceUrl the specific resource URL * @return a new WebResourceProvider instance */ @@ -45,11 +46,12 @@ static WebResourceProvider newInstance(String rootUrl, String resourceUrl) { } /** - * Creates a new instance of WebResourceProvider with the given root URL, resource URL, and version. + * Creates a new instance of WebResourceProvider with the given root URL, + * resource URL, and version. * - * @param rootUrl the root URL of the web resource + * @param rootUrl the root URL of the web resource * @param resourceUrl the specific resource URL - * @param version the version of the resource + * @param version the version of the resource * @return a new WebResourceProvider instance */ static WebResourceProvider newInstance(String rootUrl, String resourceUrl, String version) { @@ -116,7 +118,8 @@ default String getVersion() { } /** - * Gets the filename of the web resource, which is the last part of the URL without the path. + * Gets the filename of the web resource, which is the last part of the URL + * without the path. * * @return the filename */ @@ -152,9 +155,10 @@ default File write(File folder) { /** * Creates a resource for the given version. *

- * It changes the resource path by appending an underscore and the given version as a suffix, before any - * extension.
- * E.g., if the original resource is "path/executable.exe", returns a resource to "path/executable.exe". + * It changes the resource path by appending an underscore and the given version + * as a suffix, before any extension.
+ * E.g., if the original resource is "path/executable.exe", returns a resource + * to "path/executable.exe". *

* * @param version the version to append to the resource path diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/CachedStringProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/CachedStringProvider.java index 3b184249..0ba7c2cf 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/CachedStringProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/CachedStringProvider.java @@ -19,8 +19,8 @@ import pt.up.fe.specs.util.providers.StringProvider; /** - * A StringProvider backed by the given File. The provider will return the contents of the file. - * + * A StringProvider backed by the given File. The provider will return the + * contents of the file. * * @author JoaoBispo * @@ -31,23 +31,23 @@ public class CachedStringProvider implements StringProvider { private Optional contents; public CachedStringProvider(StringProvider provider) { - this.provider = provider; - this.contents = Optional.empty(); + this.provider = provider; + this.contents = Optional.empty(); } @Override public String getString() { - // Load file, if not loaded yet - if (!this.contents.isPresent()) { - String string = this.provider.getString(); - if (string == null) { - SpecsLogs.warn("Could not get contents from provider"); - } + // Load file, if not loaded yet + if (!this.contents.isPresent()) { + String string = this.provider.getString(); + if (string == null) { + SpecsLogs.warn("Could not get contents from provider"); + } - this.contents = Optional.of(string); - } + this.contents = Optional.of(string); + } - return this.contents.get(); + return this.contents.get(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/GenericFileResourceProvider.java b/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/GenericFileResourceProvider.java index 0e584200..32d343f5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/GenericFileResourceProvider.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/providers/impl/GenericFileResourceProvider.java @@ -24,7 +24,6 @@ public class GenericFileResourceProvider implements FileResourceProvider { private final File existingFile; private final String version; private final boolean isVersioned; - // private final Lazy versionedFile; public static GenericFileResourceProvider newInstance(File file) { return newInstance(file, null); @@ -41,55 +40,19 @@ public static GenericFileResourceProvider newInstance(File file) { * @return */ public static GenericFileResourceProvider newInstance(File existingFile, String version) { - // File fileWithoutVersion = existingFile; - - // Remove version from file - // if (version != null) { - // String strippedFilename = SpecsIo.removeExtension(existingFile); - // Preconditions.checkArgument(strippedFilename.endsWith(version), "Given filename '" + existingFile - // + "' does not have the given version '" + version + "' as a suffix"); - // } - - // Create versioned file - // File versionedFile = getVersionedFile(fileWithoutVersion, version); - if (!existingFile.isFile()) { - // if (!versionedFile.isFile()) { - // System.out.println("FILE:" + versionedFile.getAbsolutePath()); - // throw new RuntimeException("File '" + versionedFile + "' does not exist"); throw new RuntimeException("File '" + existingFile + "' does not exist"); } return new GenericFileResourceProvider(existingFile, version, false); - // return new GenericFileResourceProvider(fileWithoutVersion, version); } - // private static File getVersionedFile(File file, String version) { - // if (version == null) { - // return file; - // } - // - // // Create new file - // String filenameNoExt = SpecsIo.removeExtension(file); - // String extension = SpecsIo.getExtension(file); - // extension = extension.isEmpty() ? extension : "." + extension; - // - // String newFilename = filenameNoExt + version + extension; - // - // return new File(SpecsIo.getParent(file), newFilename); - // } - private GenericFileResourceProvider(File existingFile, String version, boolean isVersioned) { this.existingFile = existingFile; this.version = version; this.isVersioned = isVersioned; - // this.versionedFile = Lazy.newInstance(() -> getVersionedFile(fileWithoutVersion, version)); } - // public File getFile() { - // return - // } - @Override public File write(File folder) { @@ -121,7 +84,8 @@ public File getFile() { } /** - * Only implemented for non-versioned resources, always returns itself with updated version. + * Only implemented for non-versioned resources, always returns itself with + * updated version. */ @Override public FileResourceProvider createResourceVersion(String version) { @@ -131,17 +95,6 @@ public FileResourceProvider createResourceVersion(String version) { // Create new versioned file return newInstance(existingFile, version); - - // File newVersionedFile = getVersionedFile(fileWithoutVersion, version); - // String filenameNoExt = SpecsIo.removeExtension(fileWithoutVersion); - // String extension = SpecsIo.getExtension(fileWithoutVersion); - // extension = extension.isEmpty() ? extension : "." + extension; - - // String newFilename = filenameNoExt + version + extension; - - // File newFile = new File(SpecsIo.getParent(fileWithoutVersion), newFilename); - // FileResourceProvider provider = newInstance(newVersionedFile, version); - // return provider; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/reporting/DefaultMessageType.java b/SpecsUtils/src/pt/up/fe/specs/util/reporting/DefaultMessageType.java index 1291a5f3..4d9758fc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/reporting/DefaultMessageType.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/reporting/DefaultMessageType.java @@ -38,8 +38,8 @@ class DefaultMessageType implements MessageType { * @param category the category of the message type */ public DefaultMessageType(String name, ReportCategory category) { - this.name = name; - this.category = category; + this.name = name; + this.category = category; } /** @@ -49,7 +49,7 @@ public DefaultMessageType(String name, ReportCategory category) { */ @Override public String getName() { - return this.name; + return this.name; } /** @@ -59,7 +59,7 @@ public String getName() { */ @Override public ReportCategory getMessageCategory() { - return this.category; + return this.category; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/reporting/MessageType.java b/SpecsUtils/src/pt/up/fe/specs/util/reporting/MessageType.java index 60511a68..cbbccc75 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/reporting/MessageType.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/reporting/MessageType.java @@ -30,7 +30,7 @@ public interface MessageType { * @return the name of the message type */ public default String getName() { - return toString(); + return toString(); } /** diff --git a/SpecsUtils/src/pt/up/fe/specs/util/reporting/Reporter.java b/SpecsUtils/src/pt/up/fe/specs/util/reporting/Reporter.java index 8d3c7da1..72c69a36 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/reporting/Reporter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/reporting/Reporter.java @@ -30,26 +30,24 @@ public interface Reporter { * Emits a warning or error. * *

- * A warning is a potential problem in the code that does not prevent the generation of valid C code. It usually - * indicates bugs or performance issues. + * A warning is a potential problem in the code that does not prevent the + * generation of valid C code. It usually indicates bugs or performance issues. * *

- * An error is an actual problem in the code that prevents the generation of C code and therefore should stop the - * code generation through an exception. + * An error is an actual problem in the code that prevents the generation of C + * code and therefore should stop the code generation through an exception. * - * @param type - * The type of message. - * @param message - * The message body. Messages should be formatted as one or more simple sentences. Usually ends in a "." - * or "?". + * @param type The type of message. + * @param message The message body. Messages should be formatted as one or more + * simple sentences. Usually ends in a "." + * or "?". */ public void emitMessage(MessageType type, String message); /** * Prints the stack trace to the provided PrintStream. * - * @param reportStream - * The stream where the stack trace will be printed. + * @param reportStream The stream where the stack trace will be printed. */ public void printStackTrace(PrintStream reportStream); @@ -64,52 +62,49 @@ public interface Reporter { * Emits an error. * *

- * An error is an actual problem in the code that prevents the generation of C code and therefore should stop the - * code generation through an exception. + * An error is an actual problem in the code that prevents the generation of C + * code and therefore should stop the code generation through an exception. * - * @param type - * The type of message. - * @param message - * The message body. Messages should be formatted as one or more simple sentences. Usually ends in a "." - * or "?". - * @return A null RuntimeException. It is merely meant to enable the "throw emitError()" syntax. + * @param type The type of message. + * @param message The message body. Messages should be formatted as one or more + * simple sentences. Usually ends in a "." + * or "?". + * @return A null RuntimeException. It is merely meant to enable the "throw + * emitError()" syntax. */ public default RuntimeException emitError(MessageType type, String message) { - Preconditions.checkArgument(type.getMessageCategory() == ReportCategory.ERROR); + Preconditions.checkArgument(type.getMessageCategory() == ReportCategory.ERROR); - emitMessage(type, message); + emitMessage(type, message); - return new RuntimeException(message); + return new RuntimeException(message); } /** * Emits a default warning message. * - * @param message - * The warning message to be emitted. + * @param message The warning message to be emitted. */ public default void warn(String message) { - emitMessage(MessageType.WARNING_TYPE, message); + emitMessage(MessageType.WARNING_TYPE, message); } /** * Emits a default info message. * - * @param message - * The info message to be emitted. + * @param message The info message to be emitted. */ public default void info(String message) { - emitMessage(MessageType.INFO_TYPE, message); + emitMessage(MessageType.INFO_TYPE, message); } /** * Emits a default error message. * - * @param message - * The error message to be emitted. + * @param message The error message to be emitted. * @return A RuntimeException containing the error message. */ public default RuntimeException error(String message) { - return emitError(MessageType.ERROR_TYPE, message); + return emitError(MessageType.ERROR_TYPE, message); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/reporting/ReporterUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/reporting/ReporterUtils.java index 9b0398c5..4ae3e7dc 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/reporting/ReporterUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/reporting/ReporterUtils.java @@ -29,7 +29,7 @@ private ReporterUtils() { * Formats a message with a given type and content. * * @param messageType the type of the message (e.g., "Error", "Warning") - * @param message the content of the message + * @param message the content of the message * @return a formatted message string */ public static String formatMessage(String messageType, @@ -42,11 +42,12 @@ public static String formatMessage(String messageType, } /** - * Formats a stack line for a file, including the file name, line number, and code line. + * Formats a stack line for a file, including the file name, line number, and + * code line. * - * @param fileName the name of the file + * @param fileName the name of the file * @param lineNumber the line number in the file - * @param codeLine the code line at the specified line number + * @param codeLine the code line at the specified line number * @return a formatted stack line string */ public static String formatFileStackLine(String fileName, int lineNumber, String codeLine) { @@ -57,12 +58,13 @@ public static String formatFileStackLine(String fileName, int lineNumber, String } /** - * Formats a stack line for a function, including the function name, file name, line number, and code line. + * Formats a stack line for a function, including the function name, file name, + * line number, and code line. * * @param functionName the name of the function - * @param fileName the name of the file - * @param lineNumber the line number in the file - * @param codeLine the code line at the specified line number + * @param fileName the name of the file + * @param lineNumber the line number in the file + * @param codeLine the code line at the specified line number * @return a formatted stack line string */ public static String formatFunctionStackLine(String functionName, String fileName, int lineNumber, @@ -87,7 +89,8 @@ public static String stackEnd() { * * @param code the code string * @param line the line number to retrieve - * @return the code line at the specified line number, or a message if the code is null + * @return the code line at the specified line number, or a message if the code + * is null */ public static String getErrorLine(String code, int line) { if (code == null) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserResult.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserResult.java index 505dbde7..47ecb95b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserResult.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserResult.java @@ -39,8 +39,4 @@ public static ParserResult> asOptional(ParserResult parserRes return new ParserResult<>(parserResult.getModifiedString(), Optional.of(parserResult.getResult())); } - // public void trim() { - // modifiedString = modifiedString.trim(); - // } - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam2.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam2.java index 98a868ca..be65d7a5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam2.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam2.java @@ -29,10 +29,8 @@ public interface ParserWorkerWithParam2 { /** * Applies this function to the given arguments. * - * @param t - * the first function argument - * @param u - * the second function argument + * @param t the first function argument + * @param u the second function argument * @return the function result */ ParserResult apply(StringSlice s, U u, V v); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam3.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam3.java index 8330c22b..93e52450 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam3.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam3.java @@ -30,12 +30,9 @@ public interface ParserWorkerWithParam3 { /** * Applies this function to the given arguments. * - * @param t - * the first function argument - * @param u - * the second function argument - * @param w - * the third function argument + * @param t the first function argument + * @param u the second function argument + * @param w the third function argument * @return the function result */ ParserResult apply(StringSlice s, U u, V v, W w); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam4.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam4.java index 19ed703a..ee9f6f33 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam4.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/ParserWorkerWithParam4.java @@ -30,14 +30,10 @@ public interface ParserWorkerWithParam4 { /** * Applies this function to the given arguments. * - * @param t - * the first function argument - * @param u - * the second function argument - * @param w - * the third function argument - * @param y - * the fourth function argument + * @param t the first function argument + * @param u the second function argument + * @param w the third function argument + * @param y the fourth function argument * @return the function result */ ParserResult apply(StringSlice s, U u, V v, W w, Y y); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParser.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParser.java index fc45e7e7..2b21731a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParser.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParser.java @@ -23,7 +23,8 @@ * Utility class for performing parsing over a String. * *

- * Uses a mutable StringSlice to apply parsing rules over the string which can update it. + * Uses a mutable StringSlice to apply parsing rules over the string which can + * update it. * * @author JoaoBispo * @@ -57,7 +58,6 @@ public StringSlice getCurrentString() { public T applyPrivate(ParserResult result) { int originalLength = currentString.length(); - // currentString = currentString.setString(result.getModifiedString()); currentString = result.getModifiedString(); // Apply trim if there where modifications @@ -78,47 +78,21 @@ public T apply(ParserWorker worker) { ParserResult result = worker.apply(currentString); return applyPrivate(result); - /* - int originalLength = currentString.length(); - currentString = result.getModifiedString(); - - // Apply trim if there where modifications - if (currentString.length() != originalLength) { - currentString = currentString.trim(); - } - - return result.getResult(); - */ } public T apply(ParserWorkerWithParam worker, U parameter) { ParserResult result = worker.apply(currentString, parameter); return applyPrivate(result); - /* - currentString = result.getModifiedString(); - - return result.getResult(); - */ } public T apply(ParserWorkerWithParam2 worker, U parameter1, V parameter2) { ParserResult result = worker.apply(currentString, parameter1, parameter2); return applyPrivate(result); - /* - currentString = result.getModifiedString(); - - return result.getResult(); - */ } public T apply(ParserWorkerWithParam3 worker, U parameter1, V parameter2, W parameter3) { ParserResult result = worker.apply(currentString, parameter1, parameter2, parameter3); return applyPrivate(result); - /* - currentString = result.getModifiedString(); - - return result.getResult(); - */ } public T apply(ParserWorkerWithParam4 worker, U parameter1, V parameter2, @@ -146,7 +120,6 @@ public String substring(int beginIndex) { public String clear() { String consumedString = currentString.toString(); - // currentString = new StringSlice(""); currentString = currentString.clear(); return consumedString; } @@ -156,7 +129,8 @@ public void trim() { } /** - * Checks if the internal string is empty, after trimming. If it is not, throws an Exception. + * Checks if the internal string is empty, after trimming. If it is not, throws + * an Exception. */ public void checkEmpty() { if (currentString.trim().isEmpty()) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsers.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsers.java index cdc3d97e..2f8e3f7c 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsers.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsers.java @@ -41,8 +41,8 @@ public class StringParsers { } /** - * Receives a string starting with generic string separated by a whitespace, or the complete string if no whitespace - * is found. + * Receives a string starting with generic string separated by a whitespace, or + * the complete string if no whitespace is found. * * @param string * @return @@ -51,7 +51,6 @@ public static ParserResult parseWord(StringSlice string) { int endIndex = string.indexOf(' '); if (endIndex == -1) { endIndex = string.length(); - // throw new RuntimeException("Expected a space in string '" + string + "'"); } String element = string.substring(0, endIndex).toString(); @@ -63,8 +62,8 @@ public static ParserResult parseWord(StringSlice string) { } /** - * Receives a string starting with generic string separated by a whitespace, or the complete string if no whitespace - * is found. + * Receives a string starting with generic string separated by a whitespace, or + * the complete string if no whitespace is found. * * @param string * @return @@ -129,7 +128,6 @@ public static ParserResult> checkDigit(StringSlice string) { public static ParserResult> checkHexDigit(StringSlice string) { return checkCharacter(string, HEXDIGITS_LOWER); - } /** @@ -144,7 +142,8 @@ public static ParserResult> checkStringStarts(StringSlice strin } /** - * Returns an optional with the string if it starts with the given prefix, removes it from parsing. + * Returns an optional with the string if it starts with the given prefix, + * removes it from parsing. * * @param string * @param prefix @@ -183,7 +182,8 @@ public static ParserResult peekStartsWith(StringSlice string, String pr } /** - * Checks if it starts with the given String, but does not change the contents if it is either true of false. + * Checks if it starts with the given String, but does not change the contents + * if it is either true of false. * * @param string * @param prefix @@ -200,7 +200,8 @@ public static ParserResult peekStartsWith(StringSlice string, String pr } /** - * String must start with double quote, and appends characters until there is an unescaped double quote. + * String must start with double quote, and appends characters until there is an + * unescaped double quote. * * @param string * @return the contents inside the double quoted string @@ -247,8 +248,8 @@ public static ParserResult parseDoubleQuotedString(StringSlice string) { } /** - * Receives a string starting with the given prefix, returns the prefix. Throws exception if the prefix is not - * found. + * Receives a string starting with the given prefix, returns the prefix. Throws + * exception if the prefix is not found. * * @param string * @return @@ -264,7 +265,8 @@ public static ParserResult parseString(StringSlice string, String prefix } /** - * Parses a string between the given begin and end characters, trims the slice in the end. + * Parses a string between the given begin and end characters, trims the slice + * in the end. * * @param string * @param begin @@ -275,8 +277,6 @@ public static ParserResult parseString(StringSlice string, String prefix public static ParserResult parseNested(StringSlice string, char begin, char end, BiPredicate endPredicate) { - // string = string.trim(); - Preconditions.checkArgument(!string.isEmpty()); if (string.charAt(0) != begin) { @@ -289,7 +289,6 @@ public static ParserResult parseNested(StringSlice string, char begin, c endIndex++; // If found end char, decrement - // if (string.charAt(endIndex) == end) { if (endPredicate.test(string, endIndex)) { counter--; continue; @@ -318,8 +317,8 @@ public static ParserResult parseNested(StringSlice string, char begin, c /** * Parses a string inside primes ('), separated by spaces. *

- * Receives a string starting with "'{element}' ( '{element}')*", returns a list with the elements, without the - * primes. + * Receives a string starting with "'{element}' ( '{element}')*", returns a list + * with the elements, without the primes. * * @param string * @return @@ -338,12 +337,9 @@ public static String removeSuffix(String string, String suffix) { return string.substring(0, string.length() - suffix.length()); } - // public static > ParserResult parseEnum(StringSlice string, Class enumClass) { - // return parseEnum(string, enumClass, null, Collections.emptyMap()); - // } - /** - * Helper method which does not use the example value as a default value. Throws exception if the enum is not found. + * Helper method which does not use the example value as a default value. Throws + * exception if the enum is not found. * * @param string * @param exampleValue @@ -359,8 +355,7 @@ public static & StringProvider> ParserResult parseEnum( * * @param string * @param exampleValue - * @param useAsDefault - * if true, uses the given value as the default + * @param useAsDefault if true, uses the given value as the default * @return */ public static & StringProvider> ParserResult parseEnum( @@ -386,7 +381,8 @@ public static & StringProvider> ParserResult parseEnum( } /** - * Helper method which converts the word to upper case (enum values by convention should be uppercase). + * Helper method which converts the word to upper case (enum values by + * convention should be uppercase). * * @param string * @param enumClass @@ -396,14 +392,6 @@ public static > ParserResult parseEnum(StringSlice string, K defaultValue) { return parseEnum(string, enumClass, defaultValue, Collections.emptyMap()); - /* - ParserResult> enumTry = checkEnum(string, enumClass, true, Collections.emptyMap()); - - K result = enumTry.getResult().orElseThrow(() -> new RuntimeException("Could not convert string '" - + parseWord(string) + "' to enum '" + Arrays.toString(enumClass.getEnumConstants()) + "'")); - - return new ParserResult<>(enumTry.getModifiedString(), result); - */ } public static > ParserResult parseEnum(StringSlice string, Class enumClass) { @@ -416,13 +404,6 @@ public static > ParserResult parseEnum(StringSlice string, // Copy StringSlice, in case the function does not found the enum ParserResult word = StringParsers.parseWord(new StringSlice(string)); - // String wordToTest = word.getResult(); - - // Convert to upper case if needed - // if (toUpper) { - // wordToTest = wordToTest.toUpperCase(); - // } - // Check if enumeration contains element with the same name as the string K anEnum = SpecsEnums.valueOf(enumClass, word.getResult().toUpperCase()); if (anEnum != null) { @@ -465,7 +446,8 @@ public static & StringProvider> ParserResult checkEnum( } /** - * Checks if string starts with a word representing an enumeration of the given example value. + * Checks if string starts with a word representing an enumeration of the given + * example value. * * @param string * @param exampleValue diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsersLegacy.java b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsersLegacy.java index f185fb7a..eaf1a578 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsersLegacy.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringparser/StringParsersLegacy.java @@ -43,8 +43,8 @@ public static ParserResult parseParenthesis(StringSlice string) { } /** - * Receives a string starting with "'{element}'({separator}'{element}')*", returns a list with the elements, without - * the primes. + * Receives a string starting with "'{element}'({separator}'{element}')*", + * returns a list with the elements, without the primes. * *

* Trims the string after processing. @@ -65,8 +65,6 @@ public static ParserResult> parsePrimesSeparatedByString(StringSlic throw new RuntimeException("Given string does not start with quote ('):" + string); } - // return new ParserResult<>(string, elements); - // While string starts with a prime (') while (string.startsWith("'")) { // Get string between primes @@ -79,7 +77,6 @@ public static ParserResult> parsePrimesSeparatedByString(StringSlic // If there is not a separator, with a prime following it, return if (!string.startsWith(separator + "'")) { // Trim string - // string = string; string = string.trim(); return new ParserResult<>(string, elements); } @@ -89,36 +86,11 @@ public static ParserResult> parsePrimesSeparatedByString(StringSlic } throw new RuntimeException("Should not arrive here, current string: '" + string + "'"); - /* - ParserResult> primesResult; - // While the result of parsing primes is not empty - while (!(primesResult = parsePrimes(string)).getResult().isEmpty()) { - // Update string - string = primesResult.getModifiedString(); - - // System.out.println("NEW STRING:" + string); - // System.out.println("RESULTS:" + primesResult.getResult()); - - // Add result - Preconditions.checkArgument(primesResult.getResult().size() == 1, "Expected only one element"); - elements.add(primesResult.getResult().get(0)); - - // Remove separator - if (string.startsWith(separator)) { - string = string.substring(separator.length()); - } - // Check that there is no more primes - else { - Preconditions.checkArgument(!string.startsWith("'"), "Did not expect a prime here:" + string); - } - } - - return new ParserResult<>(string, elements); - */ } /** - * Receives a string starting with "(line|col):{number}(:{number})? and ending with a whitespace + * Receives a string starting with "(line|col):{number}(:{number})? and ending + * with a whitespace * * @param string * @return @@ -184,7 +156,6 @@ private static Optional testPath(StringSlice string) { // Linux path if (string.startsWith("/")) { return Optional.of(0); - // throw new RuntimeException("Parsing of Linux paths not done yet, current path:" + testString); } // Windows path @@ -207,19 +178,6 @@ public static ParserResult parseRemaining(StringSlice string) { return new ParserResult<>(string, rem); } - /* - private static ParserResult> parseWordTry(StringSlice string) { - // Check if first character is an alphabetic character - if (!string.isEmpty() && !Character.isLetter(string.charAt(0))) { - return new ParserResult<>(string, Optional.empty()); - } - - ParserResult result = StringParsers.parseWord(string); - - return new ParserResult<>(result.getModifiedString(), Optional.of(result.getResult())); - } - */ - /** * Makes sure the string has the given prefix at the beginning. * @@ -242,8 +200,8 @@ public static ParserResult ensurePrefix(StringSlice string, String pref } /** - * Makes sure the string has the given string at the beginning, separated by a whitespace, or is the complete string - * if no whitespace is found. + * Makes sure the string has the given string at the beginning, separated by a + * whitespace, or is the complete string if no whitespace is found. * * @param string * @param word @@ -264,8 +222,8 @@ public static ParserResult ensureWord(StringSlice string, String word) } /** - * Checks if starts with the given string, separated by a whitespace or if there is no whitespace, until the end of - * the string. + * Checks if starts with the given string, separated by a whitespace or if there + * is no whitespace, until the end of the string. * * @param string * @param string @@ -288,8 +246,8 @@ public static ParserResult checkWord(StringSlice string, String word) { } /** - * Checks if ends with the given string, separated by a whitespace or if there is no whitespace, considers the whole - * string. + * Checks if ends with the given string, separated by a whitespace or if there + * is no whitespace, considers the whole string. * * @param string * @param string @@ -316,7 +274,8 @@ public static ParserResult checkLastString(StringSlice string, String w } /** - * Returns true if the string starts with the given prefix, removes it from parsing. + * Returns true if the string starts with the given prefix, removes it from + * parsing. * *

* Helper method which enables case-sensitiveness by default. @@ -330,7 +289,8 @@ public static ParserResult checkStringStarts(StringSlice string, String } /** - * Returns true if the string starts with the given prefix, removes it from parsing. + * Returns true if the string starts with the given prefix, removes it from + * parsing. * * @param string * @param prefix @@ -341,14 +301,7 @@ public static ParserResult checkStringStarts(StringSlice string, String boolean startsWith = caseSensitive ? string.startsWith(prefix) : string.toString().toLowerCase().startsWith(prefix.toLowerCase()); - /* - if(caseSensitive) { - string.startsWith(prefix) - } else { - string.toString().toLowerCase().startsWith(prefix.toLowerCase()) - } - */ - // if (string.startsWith(prefix)) { + if (startsWith) { string = string.substring(prefix.length()); return new ParserResult<>(string, true); @@ -388,7 +341,8 @@ public static ParserResult checkStringEndsStrict(StringSlice string, St /** * * @param string - * @return true if the string starts with '->', false if it starts with '.', throws an exception otherwise + * @return true if the string starts with '->', false if it starts with '.', + * throws an exception otherwise */ public static ParserResult checkArrow(StringSlice string) { if (string.startsWith("->")) { @@ -405,10 +359,12 @@ public static ParserResult checkArrow(StringSlice string) { } /** - * Starts at the end of the string, looking for a delimited by possibly nested symbols 'start' and 'end'. + * Starts at the end of the string, looking for a delimited by possibly nested + * symbols 'start' and 'end'. * *

- * Example: ("a string ", '<', '>') should return "another string" + * Example: ("a string ", '<', '>') should return "another + * string" * * @param string * @param start @@ -448,11 +404,12 @@ public static ParserResult reverseNested(StringSlice string, char start, } /** - * Receives a string starting with '0x' and interprets the next characters as an hexadecimal number, until there is - * a whitespace or the string ends. + * Receives a string starting with '0x' and interprets the next characters as an + * hexadecimal number, until there is a whitespace or the string ends. * * @param string - * @return an Integer representing the decoded hexadecimal, or -1 if no hex was found + * @return an Integer representing the decoded hexadecimal, or -1 if no hex was + * found */ public static ParserResult parseHex(StringSlice string) { if (!string.startsWith("0x")) { @@ -475,11 +432,12 @@ public static ParserResult parseHex(StringSlice string) { } /** - * Receives a string ending with a 'word' starting with '0x' and interprets the next characters as an hexadecimal - * number, until the string ends. + * Receives a string ending with a 'word' starting with '0x' and interprets the + * next characters as an hexadecimal number, until the string ends. * * @param string - * @return an Integer representing the decoded hexadecimal, or -1 if no hex was found + * @return an Integer representing the decoded hexadecimal, or -1 if no hex was + * found */ public static ParserResult reverseHex(StringSlice string) { int startIndex = string.lastIndexOf(' '); @@ -487,7 +445,6 @@ public static ParserResult reverseHex(StringSlice string) { startIndex = 0; } - // StringSlice hexString = string.substring(startIndex + 1, string.length()).trim(); StringSlice hexString = string.substring(startIndex + 1, string.length()); if (!hexString.startsWith("0x")) { @@ -505,11 +462,12 @@ public static ParserResult reverseHex(StringSlice string) { } /** - * Receives a string and interprets the next characters as an integer number, until there is a whitespace or the - * string ends. + * Receives a string and interprets the next characters as an integer number, + * until there is a whitespace or the string ends. * * @param string - * @return an Integer representing the decoded hexadecimal, or -1 if no hex was found + * @return an Integer representing the decoded hexadecimal, or -1 if no hex was + * found */ public static ParserResult parseInt(StringSlice string) { return parseDecodedWord(string, intString -> Integer.decode(intString), 0); @@ -531,13 +489,6 @@ public static ParserResult parseDecodedWord(StringSlice string, Function< return new ParserResult<>(string, decodedValue); } - // private static > ParserResult checkEnum(StringSlice string, Class enumClass, K - // defaultValue, - // Map customMappings) { - // - // return checkEnum(string, enumClass, defaultValue, true, customMappings); - // } - public static & StringProvider> ParserResult> parseElements(StringSlice string, EnumHelperWithValue enumHelper) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSliceWithSplit.java b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSliceWithSplit.java index a4d58019..ad01d4da 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSliceWithSplit.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSliceWithSplit.java @@ -62,7 +62,8 @@ public StringSliceWithSplit setSeparator(Predicate separator) { } /** - * Parses a word according to the current rules (i.e., trim, reverse and separator). + * Parses a word according to the current rules (i.e., trim, reverse and + * separator). *

* If no separator is found, the result contains the remaining string. * @@ -102,7 +103,6 @@ private SplitResult nextRegular(int internalSeparatorIndex) { separator); return new SplitResult<>(modifiedSlice, word); - } private SplitResult nextReverse(int internalSeparatorIndex) { @@ -152,24 +152,6 @@ private int indexOfInternal(Predicate target, boolean reverse) { } } - // Using class methods - // // Test reverse order - // if (reverse) { - // for (int i = length() - 1; i >= 0; i--) { - // if (target.test(charAtUnchecked(i))) { - // return i; - // } - // } - // } - // // Test original order - // else { - // for (int i = 0; i < length(); i++) { - // if (target.test(charAtUnchecked(i))) { - // return i; - // } - // } - // } - return -1; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitter.java b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitter.java index 632eb8b8..7ad85b95 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitter.java @@ -72,7 +72,8 @@ private Optional check(SplitRule rule, Predicate predicate, boolean } /** - * Similar to {@link StringSplitter#parseTry(SplitRule)}, but throws exception if the rule does not match. + * Similar to {@link StringSplitter#parseTry(SplitRule)}, but throws exception + * if the rule does not match. * * @param rule * @return @@ -99,8 +100,9 @@ public List parse(SplitRule rule, int numElements) { } /** - * Applies the rule over the current string. If the rule matches, returns the match and consumes the corresponding - * string. Otherwise, returns an empty Optional and leaves the current string unchanged. + * Applies the rule over the current string. If the rule matches, returns the + * match and consumes the corresponding string. Otherwise, returns an empty + * Optional and leaves the current string unchanged. * * @param rule * @return @@ -111,8 +113,9 @@ public Optional parseTry(SplitRule rule) { } /** - * Applies the given rule, and if it matches, checks if the results passes the predicate. The current string is only - * consumed if both the rule and the predicate match. + * Applies the given rule, and if it matches, checks if the results passes the + * predicate. The current string is only consumed if both the rule and the + * predicate match. * * @param rule * @param checker @@ -123,7 +126,8 @@ public Optional parseIf(SplitRule rule, Predicate predicate) { } /** - * Applies the rule over the current string, but does not consume the string even if the rule matches. + * Applies the rule over the current string, but does not consume the string + * even if the rule matches. * * @param rule * @return @@ -144,8 +148,9 @@ public Optional peekIf(SplitRule rule, Predicate predicate) { } /** - * Similar to {@link StringSplitter#parseIf(SplitRule, Predicate)}, but discards the result and returns if the value - * is present or not, consuming the corresponding string. + * Similar to {@link StringSplitter#parseIf(SplitRule, Predicate)}, but discards + * the result and returns if the value is present or not, consuming the + * corresponding string. * * @param rule * @param predicate @@ -155,11 +160,10 @@ public boolean check(SplitRule rule, Predicate predicate) { return parseIf(rule, predicate).isPresent(); } - // boolean hasWord4 = parser.check(StringSplitterRules::string, string -> string.equals("word4")); - /** - * Similar to {@link StringSplitter#parseIf(SplitRule, Predicate)}, but discards the result and throws exception if - * the value is not present, consuming the corresponding string. + * Similar to {@link StringSplitter#parseIf(SplitRule, Predicate)}, but discards + * the result and throws exception if the value is not present, consuming the + * corresponding string. * * @param * @param rule diff --git a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitterRules.java b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitterRules.java index 8e33f5c3..2fbc988b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitterRules.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/stringsplitter/StringSplitterRules.java @@ -20,8 +20,8 @@ public class StringSplitterRules { /** - * Looks for a string defined by the {@link StringSliceWithSplit} separator, or the complete string if no separator - * was found. + * Looks for a string defined by the {@link StringSliceWithSplit} separator, or + * the complete string if no separator was found. * *

* The default separator is a whitespace, as determined by the function @@ -37,8 +37,9 @@ public static SplitResult string(StringSliceWithSplit string) { } /** - * Looks for a word (as defined by {@link StringSplitterRules#string(StringSlice)}) and tries to transform into an - * object using the provided decoder. + * Looks for a word (as defined by + * {@link StringSplitterRules#string(StringSlice)}) and tries to transform into + * an object using the provided decoder. * * @param string * @param decoder diff --git a/SpecsUtils/src/pt/up/fe/specs/util/swing/GenericActionListener.java b/SpecsUtils/src/pt/up/fe/specs/util/swing/GenericActionListener.java index f8dc6430..20a902cd 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/swing/GenericActionListener.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/swing/GenericActionListener.java @@ -43,7 +43,7 @@ public class GenericActionListener extends AbstractAction { * @return a new instance of GenericActionListener */ public static GenericActionListener newInstance(Consumer consumer) { - return new GenericActionListener(consumer); + return new GenericActionListener(consumer); } /** @@ -52,7 +52,7 @@ public static GenericActionListener newInstance(Consumer consumer) * @param consumer the consumer to handle the action event */ public GenericActionListener(Consumer consumer) { - this.consumer = consumer; + this.consumer = consumer; } /** @@ -62,7 +62,7 @@ public GenericActionListener(Consumer consumer) { */ @Override public void actionPerformed(ActionEvent e) { - consumer.accept(e); + consumer.accept(e); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModel.java b/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModel.java index 849e7dc4..95b14819 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModel.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModel.java @@ -28,9 +28,6 @@ */ public class MapModel, V> extends AbstractTableModel { - /** - * - */ private static final long serialVersionUID = 1L; private final Map map; private final boolean rowWise; @@ -40,164 +37,137 @@ public class MapModel, V> extends AbstractTableM private List columnNames; - /** - * @param map - */ public MapModel(Map map, boolean rowWise, Class valueClass) { - this(map, new ArrayList<>(map.keySet()), rowWise, valueClass); + this(map, new ArrayList<>(map.keySet()), rowWise, valueClass); } public MapModel(Map map, List keys, boolean rowWise, Class valueClass) { - this.map = map == null ? Collections.emptyMap() : new HashMap<>(map); + this.map = map == null ? Collections.emptyMap() : new HashMap<>(map); - this.rowWise = rowWise; + this.rowWise = rowWise; - this.keys = keys; - this.valueClass = valueClass; + this.keys = keys; + this.valueClass = valueClass; - this.columnNames = null; - // keys.addAll(map.keySet()); - // Collections.sort(keys); + this.columnNames = null; } public static , V> TableModel newTableModel(Map map, - boolean rowWise, Class valueClass) { - - return new MapModel<>(map, rowWise, valueClass); - + boolean rowWise, Class valueClass) { + return new MapModel<>(map, rowWise, valueClass); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getRowCount() */ @Override public int getRowCount() { - if (this.rowWise) { - return 2; - } + if (this.rowWise) { + return 2; + } - return this.map.size(); + return this.map.size(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getColumnCount() */ @Override public int getColumnCount() { - if (this.rowWise) { - return this.map.size(); - } + if (this.rowWise) { + return this.map.size(); + } - return 2; + return 2; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getValueAt(int, int) */ @Override public Object getValueAt(int rowIndex, int columnIndex) { - int shortIndex, longIndex; - if (this.rowWise) { - shortIndex = rowIndex; - longIndex = columnIndex; - } else { - shortIndex = columnIndex; - longIndex = rowIndex; - } - - // Key - if (shortIndex == 0) { - return this.keys.get(longIndex); - } - - return this.map.get(this.keys.get(longIndex)); + int shortIndex, longIndex; + if (this.rowWise) { + shortIndex = rowIndex; + longIndex = columnIndex; + } else { + shortIndex = columnIndex; + longIndex = rowIndex; + } + + // Key + if (shortIndex == 0) { + return this.keys.get(longIndex); + } + + return this.map.get(this.keys.get(longIndex)); } - /* (non-Javadoc) - * @see javax.swing.table.TableModel#getValueAt(int, int) - */ - /* - public K getKeyAt(int rowIndex, int columnIndex) { - int shortIndex, longIndex; - if (rowWise) { - shortIndex = rowIndex; - longIndex = columnIndex; - } else { - shortIndex = columnIndex; - longIndex = rowIndex; - } - - // Key - if (shortIndex == 0) { - return keys.get(longIndex); - } else { - return keys.get(longIndex); - } - } - */ - public void setColumnNames(List columnNames) { - this.columnNames = columnNames; + this.columnNames = columnNames; } @Override public String getColumnName(int column) { - if (this.columnNames == null) { - return super.getColumnName(column); - } + if (this.columnNames == null) { + return super.getColumnName(column); + } - if (column >= this.columnNames.size()) { - return super.getColumnName(column); - } + if (column >= this.columnNames.size()) { + return super.getColumnName(column); + } - return this.columnNames.get(column); + return this.columnNames.get(column); } - // @SuppressWarnings("unchecked") // Method must accept Object, cannot to check - @SuppressWarnings("unchecked") - // It is being checked using valueClass + @SuppressWarnings("unchecked") // It is being checked using valueClass @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - if (!this.valueClass.isInstance(aValue)) { - throw new RuntimeException("Gave an object to type '" + aValue.getClass().getName() + "', expected type '" - + this.valueClass.getName() + "' "); - } + if (!this.valueClass.isInstance(aValue)) { + throw new RuntimeException("Gave an object to type '" + aValue.getClass().getName() + "', expected type '" + + this.valueClass.getName() + "' "); + } - updateValue((V) aValue, rowIndex, columnIndex); - fireTableCellUpdated(rowIndex, columnIndex); + updateValue((V) aValue, rowIndex, columnIndex); + fireTableCellUpdated(rowIndex, columnIndex); } private void updateValue(V aValue, int rowIndex, int columnIndex) { - if (!this.rowWise) { - // If column index is 0, set key - if (columnIndex == 0) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - // If column index is 1, set value - if (columnIndex == 1) { - - K key = this.keys.get(rowIndex); - System.out.println("ROW INDEX:" + rowIndex); - System.out.println("KEY:" + key); - this.map.put(key, aValue); - return; - } - - } else { - // If row index is 0, set key - if (rowIndex == 0) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - // If row index is 1, set value - if (rowIndex == 1) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - throw new RuntimeException("Unsupported column index:" + columnIndex); - } - + if (!this.rowWise) { + // If column index is 0, set key + if (columnIndex == 0) { + throw new UnsupportedOperationException("Not yet implemented"); + } + + // If column index is 1, set value + if (columnIndex == 1) { + + K key = this.keys.get(rowIndex); + System.out.println("ROW INDEX:" + rowIndex); + System.out.println("KEY:" + key); + this.map.put(key, aValue); + return; + } + + } else { + // If row index is 0, set key + if (rowIndex == 0) { + throw new UnsupportedOperationException("Not yet implemented"); + } + + // If row index is 1, set value + if (rowIndex == 1) { + throw new UnsupportedOperationException("Not yet implemented"); + } + + throw new RuntimeException("Unsupported column index:" + columnIndex); + } } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModelV2.java b/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModelV2.java index 41f9b66b..c4afa4ea 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModelV2.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/swing/MapModelV2.java @@ -33,11 +33,7 @@ public class MapModelV2 extends AbstractTableModel { public static final Color COLOR_DEFAULT = new Color(0, 0, 0, 0); - /** - * - */ private static final long serialVersionUID = 1L; - // private final Map map; private final List keys; private final List values; @@ -49,121 +45,92 @@ public class MapModelV2 extends AbstractTableModel { * @param map * @param columnNames */ - // public MapModelV2(Map map, List columnNames) { public MapModelV2(Map map) { - this.keys = new ArrayList<>(); - this.values = new ArrayList<>(); - this.rowColors = new ArrayList<>(); + this.keys = new ArrayList<>(); + this.values = new ArrayList<>(); + this.rowColors = new ArrayList<>(); - this.columnNames = null; - // this.columnNames = FactoryUtils.newArrayList(columnNames); + this.columnNames = null; - // Initialize keys and values - for (Object key : map.keySet()) { - Object value = map.get(key); + // Initialize keys and values + for (Object key : map.keySet()) { + Object value = map.get(key); - this.keys.add(key); - this.values.add(value); - } + this.keys.add(key); + this.values.add(value); + } - // Set default color to translucent - for (int i = 0; i < this.keys.size(); i++) { - this.rowColors.add(MapModelV2.COLOR_DEFAULT); - } + // Set default color to translucent + for (int i = 0; i < this.keys.size(); i++) { + this.rowColors.add(MapModelV2.COLOR_DEFAULT); + } } public static TableCellRenderer getRenderer() { - return new DefaultTableCellRenderer() { - - /** - * - */ - private static final long serialVersionUID = -2074238717877716002L; - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - MapModelV2 model = (MapModelV2) table.getModel(); - Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, - row, column); - c.setBackground(model.getRowColour(row)); - return c; - } - - }; + return new DefaultTableCellRenderer() { + + private static final long serialVersionUID = -2074238717877716002L; + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + MapModelV2 model = (MapModelV2) table.getModel(); + Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, + row, column); + c.setBackground(model.getRowColour(row)); + return c; + } + + }; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getRowCount() */ @Override public int getRowCount() { - return this.keys.size(); + return this.keys.size(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getColumnCount() */ @Override public int getColumnCount() { - return 2; + return 2; } public Color getRowColour(int row) { - return this.rowColors.get(row); + return this.rowColors.get(row); } public void setRowColor(int row, Color c) { - this.rowColors.set(row, c); - fireTableRowsUpdated(row, row); + this.rowColors.set(row, c); + fireTableRowsUpdated(row, row); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.swing.table.TableModel#getValueAt(int, int) */ @Override public Object getValueAt(int rowIndex, int columnIndex) { - // int shortIndex, longIndex; - - // shortIndex = columnIndex; - // longIndex = rowIndex; - - // If column == 0, return Key - if (columnIndex == 0) { - return this.keys.get(rowIndex); - } - - // if column == 1, return value - if (columnIndex == 1) { - return this.values.get(rowIndex); - } + if (columnIndex == 0) { + return this.keys.get(rowIndex); + } - throw new RuntimeException("Column index can only have the values 0 or 1"); + if (columnIndex == 1) { + return this.values.get(rowIndex); + } - } - - /* (non-Javadoc) - * @see javax.swing.table.TableModel#getValueAt(int, int) - */ - /* - public K getKeyAt(int rowIndex, int columnIndex) { - int shortIndex, longIndex; - if (rowWise) { - shortIndex = rowIndex; - longIndex = columnIndex; - } else { - shortIndex = columnIndex; - longIndex = rowIndex; - } + throw new RuntimeException("Column index can only have the values 0 or 1"); - // Key - if (shortIndex == 0) { - return keys.get(longIndex); - } else { - return keys.get(longIndex); - } } - */ /** * Helper method with variadic inputs. @@ -171,69 +138,52 @@ public K getKeyAt(int rowIndex, int columnIndex) { * @param columnNames */ public void setColumnNames(String... columnNames) { - setColumnNames(Arrays.asList(columnNames)); + setColumnNames(Arrays.asList(columnNames)); } public void setColumnNames(List columnNames) { - this.columnNames = columnNames; + this.columnNames = columnNames; } @Override public String getColumnName(int column) { - if (this.columnNames == null) { - return super.getColumnName(column); - } + if (this.columnNames == null) { + return super.getColumnName(column); + } - if (column >= this.columnNames.size()) { - return super.getColumnName(column); - } + if (column >= this.columnNames.size()) { + return super.getColumnName(column); + } - return this.columnNames.get(column); + return this.columnNames.get(column); } - /* - public void setValueAt(Object value, int arg0, int arg1) { - try { - K key = getKeyAt(arg0, arg1); - map.put(key, value); - } catch (Exception e) { - e.printStackTrace(); - } - } - */ - @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - try { - updateValue(aValue, rowIndex, columnIndex); - fireTableCellUpdated(rowIndex, columnIndex); - } catch (Exception e) { - e.printStackTrace(); - } + try { + updateValue(aValue, rowIndex, columnIndex); + fireTableCellUpdated(rowIndex, columnIndex); + } catch (Exception e) { + e.printStackTrace(); + } } - /* - public void insertValue(Integer key, Object aValue) { - - } - */ - private void updateValue(Object aValue, int rowIndex, int columnIndex) { - // If column index is 0, set key - if (columnIndex == 0) { - this.keys.set(rowIndex, aValue); - return; - } + // If column index is 0, set key + if (columnIndex == 0) { + this.keys.set(rowIndex, aValue); + return; + } - // If column index is 1, set value - if (columnIndex == 1) { - this.values.set(rowIndex, aValue); - return; - } + // If column index is 1, set value + if (columnIndex == 1) { + this.values.set(rowIndex, aValue); + return; + } - throw new RuntimeException("Column index can only have the values 0 or 1"); + throw new RuntimeException("Column index can only have the values 0 or 1"); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutput.java b/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutput.java index 01769da4..622b3a39 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutput.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutput.java @@ -51,7 +51,8 @@ public Optional getOutputException() { * @return true if there was an error, false otherwise */ public boolean isError() { - // If the return value was anything other than 0, we can assume there was an execution error + // If the return value was anything other than 0, we can assume there was an + // execution error return this.returnValue != 0; } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutputAsString.java b/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutputAsString.java index 944ccbaa..e4ff8c1c 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutputAsString.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/system/ProcessOutputAsString.java @@ -25,7 +25,8 @@ public ProcessOutputAsString(int returnValue, String stdOut, String stdErr) { } /** - * Returns the contents of the standard output, followed by the contents of the standard error. + * Returns the contents of the standard output, followed by the contents of the + * standard error. * * @return */ @@ -39,8 +40,8 @@ public String getOutput() { return out; } - // Add new line if standard out does not end with a newline, and if both standard output and standard error is - // not empty. + // Add new line if standard out does not end with a newline, and if both + // standard output and standard error is not empty. builder.append(out); if (!out.isEmpty() && !out.endsWith("\n")) { builder.append("\n"); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/system/StreamCatcher.java b/SpecsUtils/src/pt/up/fe/specs/util/system/StreamCatcher.java index db68a997..d76dbe51 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/system/StreamCatcher.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/system/StreamCatcher.java @@ -37,23 +37,22 @@ public class StreamCatcher implements Runnable { * */ public enum OutputType { - StdErr { - @Override - public void print(String stdline) { - System.err.print(stdline); - } - }, - StdOut { - @Override - public void print(String stdline) { - System.out.print(stdline); - } - }; - - public abstract void print(String stdline); + StdErr { + @Override + public void print(String stdline) { + System.err.print(stdline); + } + }, + StdOut { + @Override + public void print(String stdline) { + System.out.print(stdline); + } + }; + + public abstract void print(String stdline); } - // private final BufferedReader reader; private final InputStream inputStream; private final OutputType type; private final boolean storeOutput; @@ -62,94 +61,80 @@ public void print(String stdline) { private StringBuilder printBuffer; private final StringBuilder builder; - /** - * @param reader - */ - // public OutputCatcher(BufferedReader reader, OutputType type, boolean - // storeOutput) { public StreamCatcher(InputStream inputStream, OutputType type, boolean storeOutput, - boolean printOutput) { - // this.reader = reader; - this.inputStream = inputStream; - this.type = type; - this.storeOutput = storeOutput; - this.printOutput = printOutput; - - this.printBuffer = new StringBuilder(); - this.builder = new StringBuilder(); + boolean printOutput) { + this.inputStream = inputStream; + this.type = type; + this.storeOutput = storeOutput; + this.printOutput = printOutput; + + this.printBuffer = new StringBuilder(); + this.builder = new StringBuilder(); } @Override public void run() { - BufferedReader reader = new BufferedReader(new InputStreamReader(this.inputStream)); - // InputStreamReader reader = new InputStreamReader(inputStream); - - try { - // Reading individual characters instead of lines to prevent - // blocking the execution - // due to the program filling the buffer before a newline appears - // int character = -1; - String stdline = null; - while ((stdline = reader.readLine()) != null) { - // while ((character = reader.read()) != -1) { - // System.out.println("READ CHAR:"+(char)character); - // processCharacter(character); - - if (this.printOutput) { - this.type.print(stdline + StreamCatcher.NEW_LINE); - } - - // System.err.println(stdline); - - // Save output - if (this.storeOutput) { - this.builder.append(stdline).append(StreamCatcher.NEW_LINE); - } - - } - - // Clean any characters left in the buffer - if (this.printOutput) { - String line = this.printBuffer.toString(); - this.type.print(line); - this.printBuffer = new StringBuilder(); - } - - } catch (IOException e) { - SpecsLogs.warn("IOException during program execution:" + e.getMessage()); - } + BufferedReader reader = new BufferedReader(new InputStreamReader(this.inputStream)); + + try { + // Reading individual characters instead of lines to prevent + // blocking the execution due to the program filling the buffer before a newline + // appears int character = -1; + String stdline = null; + while ((stdline = reader.readLine()) != null) { + if (this.printOutput) { + this.type.print(stdline + StreamCatcher.NEW_LINE); + } + + // Save output + if (this.storeOutput) { + this.builder.append(stdline).append(StreamCatcher.NEW_LINE); + } + + } + + // Clean any characters left in the buffer + if (this.printOutput) { + String line = this.printBuffer.toString(); + this.type.print(line); + this.printBuffer = new StringBuilder(); + } + + } catch (IOException e) { + SpecsLogs.warn("IOException during program execution:" + e.getMessage()); + } } /* - private void processCharacter(int character) { - char aChar = (char) character; - - // Add character to current buffer - - if (printOutput) { - printBuffer.append(aChar); - // type.print(stdline); - } - - // System.err.println(stdline); - - // Save output - if (storeOutput) { - // builder.append(stdline).append("\n"); - builder.append(aChar); - } - - // If character equals new line, print outputs and clean buffer - if (aChar == '\n' && printOutput) { - String line = printBuffer.toString(); - type.print(line); - printBuffer = new StringBuilder(); - } - - } + * private void processCharacter(int character) { + * char aChar = (char) character; + * + * // Add character to current buffer + * + * if (printOutput) { + * printBuffer.append(aChar); + * // type.print(stdline); + * } + * + * // System.err.println(stdline); + * + * // Save output + * if (storeOutput) { + * // builder.append(stdline).append("\n"); + * builder.append(aChar); + * } + * + * // If character equals new line, print outputs and clean buffer + * if (aChar == '\n' && printOutput) { + * String line = printBuffer.toString(); + * type.print(line); + * printBuffer = new StringBuilder(); + * } + * + * } */ public String getOutput() { - return this.builder.toString(); + return this.builder.toString(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/system/StreamToString.java b/SpecsUtils/src/pt/up/fe/specs/util/system/StreamToString.java index c0ef06f3..531f69dd 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/system/StreamToString.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/system/StreamToString.java @@ -51,13 +51,6 @@ public String apply(InputStream inputStream) { String stdline = null; - // int currentChar = -1; - // System.out.println("START: " + reader.read()); - // while ((currentChar = reader.read()) != -1) { - // System.out.println("ADAS"); - // type.print(String.valueOf((char) currentChar)); - // } - while ((stdline = reader.readLine()) != null) { if (this.printOutput) { @@ -72,7 +65,6 @@ public String apply(InputStream inputStream) { } - // inputStream.close(); reader.close(); } catch (IOException e) { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/AObjectStream.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/AObjectStream.java index 69fb5aae..1a79b258 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/AObjectStream.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/AObjectStream.java @@ -14,7 +14,8 @@ public AObjectStream(T poison) { } /* - * MUST be implemented by children (e.g., may come from a ConcurrentChannel, or Linestream, etc + * MUST be implemented by children (e.g., may come from a ConcurrentChannel, or + * Linestream, etc */ protected abstract T consumeFromProvider(); @@ -38,8 +39,8 @@ protected T getNext() { public T next() { /* - * First call of getNext is done here instead of the constructor, since - * the channel may block if this ObjectStream is used (as it should) + * First call of getNext is done here instead of the constructor, since + * the channel may block if this ObjectStream is used (as it should) * to read from a ChannelProducer which executes in another thread * which may not have yet been launched */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ConsumerThread.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ConsumerThread.java index 3a6a7f96..719af5a5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ConsumerThread.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ConsumerThread.java @@ -8,10 +8,8 @@ * * @author nuno * - * @param - * Type of input object from ObjectStream - * @param - * Type of consumption output + * @param Type of input object from ObjectStream + * @param Type of consumption output */ public class ConsumerThread implements Runnable { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/GenericObjectStream.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/GenericObjectStream.java index 0b00a951..92ee2711 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/GenericObjectStream.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/GenericObjectStream.java @@ -17,7 +17,6 @@ protected T consumeFromProvider() { try { ret = this.consumer.take(); } catch (InterruptedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } return ret; @@ -25,7 +24,6 @@ protected T consumeFromProvider() { @Override public void close() throws Exception { - // TODO Auto-generated method stub // TODO: how to implement here?? } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectProducer.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectProducer.java index 91ec4d89..54be8327 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectProducer.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectProducer.java @@ -1,10 +1,6 @@ package pt.up.fe.specs.util.threadstream; public interface ObjectProducer extends AutoCloseable { - - /* - * - */ default T getPoison() { return null; }; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectStream.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectStream.java index 01de364d..435c5aa0 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectStream.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ObjectStream.java @@ -2,23 +2,11 @@ public interface ObjectStream extends AutoCloseable { - /* - * - */ public T next(); - /* - * - */ public boolean hasNext(); - /* - * - */ public T peekNext(); - /* - * - */ public boolean isClosed(); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerEngine.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerEngine.java index 368f6bf4..635ad2be 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerEngine.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerEngine.java @@ -10,10 +10,8 @@ * * @author nuno * - * @param - * Type of produced object - * @param - * Type of producer object + * @param Type of produced object + * @param Type of producer object */ public class ProducerEngine> { @@ -41,33 +39,21 @@ private ProducerEngine(ProducerThread producer) { this.consumers = new ArrayList>(); } - /* - * - */ public ConsumerThread subscribe(Function, ?> consumeFunction) { var thread = new ConsumerThread<>(consumeFunction); this.subscribe(thread); return thread; } - /* - * - */ private void subscribe(ConsumerThread consumer) { this.consumers.add(consumer); consumer.provide(this.producer.newChannel()); } - /* - * - */ public ConsumerThread getConsumer(int idx) { return this.consumers.get(idx); } - /* - * - */ public List> getConsumers() { return consumers; } @@ -106,7 +92,6 @@ public void launch() { thread.join(); } catch (InterruptedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerThread.java b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerThread.java index 66e5e99d..954f1c80 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerThread.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/threadstream/ProducerThread.java @@ -24,9 +24,6 @@ public class ProducerThread> implements Runnable */ private final K producer; - /* - * - */ private final Function produceFunction; /* @@ -53,7 +50,8 @@ protected ProducerThread(K producer, Function produceFunction, } /* - * creates a new channel into which this runnable object will pump data, with depth 1 + * creates a new channel into which this runnable object will pump data, with + * depth 1 */ protected ObjectStream newChannel() { return this.newChannel(1); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/ATreeNode.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/ATreeNode.java index 649e9f25..f14c0af7 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/ATreeNode.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/ATreeNode.java @@ -66,28 +66,19 @@ private List initChildren(Collection children) { return new ArrayList<>(children.size()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#getChildren() */ @Override public List getChildren() { - return this.children; - - // Currently cannot enforce immutable children view due to MATISSE passes that directly modify children - // return Collections.unmodifiableList(this.children); + return Collections.unmodifiableList(this.children); } - /** - * - * - * @return a mutable view of the children - */ - // @Override - // public List getChildrenMutable() { - // return this.children; - // } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#setChildren(java.util.Collection) */ @Override @@ -106,7 +97,9 @@ public void setChildren(Collection children) { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#removeChild(int) */ @Override @@ -124,7 +117,9 @@ public K removeChild(int index) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#setChild(int, K) */ @Override @@ -187,7 +182,9 @@ public void removeParent() { this.parent = null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#addChild(K) */ @Override @@ -215,7 +212,9 @@ public void addChildren(List children) { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#addChild(int, K) */ @Override @@ -230,7 +229,8 @@ public K addChild(int index, K child) { } /** - * Returns a new copy of the node with the same content and type, but not children. + * Returns a new copy of the node with the same content and type, but not + * children. * * @return */ @@ -242,11 +242,13 @@ public K copyShallow() { } /** - * Creates a deep copy of the node, including children. No guarantees are made regarding the contents of each node, - * they can be the same object as in the original node, and if mutable, changing the content in one node might be + * Creates a deep copy of the node, including children. No guarantees are made + * regarding the contents of each node, they can be the same object as in the + * original node, and if mutable, changing the content in one node might be * reflected in the copy. - */ - /* (non-Javadoc) + * + * (non-Javadoc) + * * @see pt.up.fe.specs.util.treenode.TreeNode#copy() */ @Override @@ -272,8 +274,8 @@ public K copy() { * Returns a reference to the object that implements this interface. * *

- * This method is needed because of Java generics not having information about K. - * + * This method is needed because of Java generics not having information about + * K. * * @return */ @@ -309,8 +311,6 @@ public K getRoot() { // If it has no parents, return self if (parent == null) { - // return (K) this; - return getThis(); } @@ -350,7 +350,8 @@ public List indexesOf(Class aClass) { } /** - * Normalizes the token according to a given bypass set. The nodes in the bypass set can have only one child. + * Normalizes the token according to a given bypass set. The nodes in the bypass + * set can have only one child. * * @param bypassSet * @return diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/ChildrenIterator.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/ChildrenIterator.java index 3668f12e..29de5e2d 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/ChildrenIterator.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/ChildrenIterator.java @@ -27,20 +27,10 @@ public ChildrenIterator(TreeNode parent) { this.parent = parent; // Currently cannot enforce immutable children view due to MATISSE passes this.iterator = parent.getChildren().listIterator(); - // this.iterator = parent.getChildrenMutable().listIterator(); - // Create a mutable iterator - // this.iterator = new ArrayList<>(parent.getChildren()).listIterator(); - // this.iterator = parent.getChildrenMutable().listIterator(); this.lastReturned = null; } - /* - protected ListIterator getIterator() { - return iterator; - } - */ - @Override public boolean hasNext() { return this.iterator.hasNext(); @@ -122,7 +112,8 @@ public void add(N e) { * Moves the cursor back the given amount of places. * *

- * If the given amount is bigger than the number of positions, stops when the cursor is at the beginning. + * If the given amount is bigger than the number of positions, stops when the + * cursor is at the beginning. * * @param amount */ @@ -145,7 +136,6 @@ public N back(int amount) { * @return the next node that is an instance of the given class */ public Optional next(Class nodeClass) { - // while (iterator.hasNext()) { while (hasNext()) { N node = next(); if (nodeClass.isInstance(node)) { @@ -173,12 +163,15 @@ public Optional nextNot(Class nodeClass) { } /** - * Returns the next element that is in the position specified by the given amount. + * Returns the next element that is in the position specified by the given + * amount. * *

* If amount is zero, returns the last returned node;
- * If the amount is greater than one, returns the nth node of the amount. next(1) is equivalent to next();
- * If the amount is less than one, returns the -nth node of the amount. next(-1) is equivalent to previous();
+ * If the amount is greater than one, returns the nth node of the amount. + * next(1) is equivalent to next();
+ * If the amount is less than one, returns the -nth node of the amount. next(-1) + * is equivalent to previous();
* * @param i * @return @@ -205,13 +198,12 @@ public N move(int amount) { } /** - * Removes a number of previous nodes, and replaces them with the given node. This call can only be made once per - * call to next or previous. + * Removes a number of previous nodes, and replaces them with the given node. + * This call can only be made once per call to next or previous. * *

- * At the end of the method, the cursor of the iterator is before the inserted node. - * - * + * At the end of the method, the cursor of the iterator is before the inserted + * node. * * @param node * @param numberOfPreviousNodes @@ -227,14 +219,11 @@ public void replace(N node, int numberOfPreviousNodes) { // Set new node set(node); - - // Move iterator forward - // iterator.next(); } /** - * Advances the cursor, and if it finds a statement of the given class, returns it. The cursor advances event if it - * returns an empty optional. + * Advances the cursor, and if it finds a statement of the given class, returns + * it. The cursor advances event if it returns an empty optional. * * @param nodeClass * diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/IteratorUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/IteratorUtils.java index bb33c3b1..55475ee6 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/IteratorUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/IteratorUtils.java @@ -20,20 +20,20 @@ public class IteratorUtils { public static > List getTokens(Iterator depthIterator, - TokenTester loopTest) { + TokenTester loopTest) { - List tokens = new ArrayList<>(); + List tokens = new ArrayList<>(); - while (depthIterator.hasNext()) { - K token = depthIterator.next(); - if (!loopTest.test(token)) { - continue; - } + while (depthIterator.hasNext()) { + K token = depthIterator.next(); + if (!loopTest.test(token)) { + continue; + } - tokens.add(token); - } + tokens.add(token); + } - return tokens; + return tokens; } /** @@ -44,46 +44,47 @@ public static > List getTokens(Iterator depthIterato * @return */ public static > Iterator getDepthIterator(K token, TokenTester loopTest) { - return getDepthIterator(token, loopTest, false); + return getDepthIterator(token, loopTest, false); } /** - * Returns a depth-first iterator for the children of the given token that passes the given test. + * Returns a depth-first iterator for the children of the given token that + * passes the given test. * * @param token * @return */ public static > Iterator getDepthIterator(K token, TokenTester loopTest, - boolean prune) { - // Build list with nodes in depth-first order - List depthFirstTokens = new ArrayList<>(); + boolean prune) { + // Build list with nodes in depth-first order + List depthFirstTokens = new ArrayList<>(); - for (K child : token.getChildren()) { - getDepthFirstTokens(child, depthFirstTokens, loopTest, prune); - } + for (K child : token.getChildren()) { + getDepthFirstTokens(child, depthFirstTokens, loopTest, prune); + } - return depthFirstTokens.iterator(); + return depthFirstTokens.iterator(); } private static > void getDepthFirstTokens(K token, List currentTokens, - TokenTester loopTest, boolean prune) { + TokenTester loopTest, boolean prune) { - boolean tokenPasses = loopTest.test(token); + boolean tokenPasses = loopTest.test(token); - // Add self token if it passes the test - if (tokenPasses) { - currentTokens.add(token); - } + // Add self token if it passes the test + if (tokenPasses) { + currentTokens.add(token); + } - // If pruning active and token passed the test, do not process children - if (tokenPasses && prune) { - return; - } + // If pruning active and token passed the test, do not process children + if (tokenPasses && prune) { + return; + } - // Add children - for (K child : token.getChildren()) { - getDepthFirstTokens(child, currentTokens, loopTest, prune); - } + // Add children + for (K child : token.getChildren()) { + getDepthFirstTokens(child, currentTokens, loopTest, prune); + } } /** @@ -92,20 +93,8 @@ private static > void getDepthFirstTokens(K token, List * @return */ public static > TokenTester newTypeTest(Class type) { - return token -> { - return type.isInstance(token); - }; + return token -> { + return type.isInstance(token); + }; } - /* - public static > TokenTester newTypeTest(final E type) { - return token -> { - if (!token.getType().equals(type)) { - return false; - } - - return true; - }; - } - */ - } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/NodeInsertUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/NodeInsertUtils.java index 593f9f68..dfcb0c08 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/NodeInsertUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/NodeInsertUtils.java @@ -45,9 +45,9 @@ public static > void insertBefore(K baseToken, K newToken) * * @param baseToken * @param newToken - * @param move - * if true, makes sure parent of newToken is null, removing it from the parent if necessary. Otherwise, - * if parent is not null, inserts a copy. + * @param move if true, makes sure parent of newToken is null, removing it + * from the parent if necessary. Otherwise, + * if parent is not null, inserts a copy. */ public static > void insertBefore(K baseToken, K newToken, boolean move) { @@ -62,14 +62,13 @@ public static > void insertBefore(K baseToken, K newToken, int rootTokenIndex = children.indexOf(baseToken); // If 'move' is false, just do nothing - // This means that if parent is not null, it will do a copy; if it is null, will just insert it + // This means that if parent is not null, it will do a copy; if it is null, will + // just insert it if (move) { processNewToken(newToken); } - // System.out.println("CHILDREN BEFORE:\n"+parent.getChildren()); parent.addChild(rootTokenIndex, newToken); - // System.out.println("CHILDREN AFTER:\n"+parent.getChildren()); } /** @@ -108,7 +107,8 @@ public static > void insertAfter(K baseToken, K newToken, int rootTokenIndex = children.indexOf(baseToken) + 1; // If 'move' is false, just do nothing - // This means that if parent is not null, it will do a copy; if it is null, will just insert it + // This means that if parent is not null, it will do a copy; if it is null, will + // just insert it if (move) { processNewToken(newToken); } @@ -121,7 +121,8 @@ public static > void insertAfter(K baseToken, K newToken, * * @param baseToken * @param newToken - * @return The new inserted token (same as newToken if newToken.getParent() was null, and a copy of newToken + * @return The new inserted token (same as newToken if newToken.getParent() was + * null, and a copy of newToken * otherwise). */ public static > K replace(K baseToken, K newToken) { @@ -145,35 +146,29 @@ public static > K replace(K baseToken, K newToken, boolean return newToken; } - // List children = parent.getChildren(); - // int rootTokenIndex = children.indexOf(baseToken); - - // System.out.println("BEFIRE:" + parent.getChildren()); - int rootTokenIndex = parent.indexOfChild(baseToken); // If move is enabled, remove parent before setting if (move && newToken.hasParent()) { - // newToken.removeParent(); newToken.detach(); } parent.setChild(rootTokenIndex, newToken); - // parent.setChild(baseToken, newToken); - // System.out.println("ADFTER:" + parent.getChildren()); - // return parent.getChild(rootTokenIndex); return newToken; } /** - * Replaces 'baseToken' with 'newToken' while preserving the children from 'baseToken'. - * This is a convenience method that combines set() and replace() operations. + * Replaces 'baseToken' with 'newToken' while preserving the children from + * 'baseToken'. This is a convenience method that combines set() and replace() + * operations. * * @param baseToken the token to be replaced - * @param newToken the replacement token - * @param move if true, detaches newToken from its current parent if it has one - * @return the new inserted token (same as newToken if newToken.getParent() was null, and a copy of newToken otherwise) + * @param newToken the replacement token + * @param move if true, detaches newToken from its current parent if it has + * one + * @return the new inserted token (same as newToken if newToken.getParent() was + * null, and a copy of newToken otherwise) */ public static > K replacePreservingChildren(K baseToken, K newToken, boolean move) { // If move is enabled, detach newToken from its current parent first @@ -181,7 +176,8 @@ public static > K replacePreservingChildren(K baseToken, K newToken.detach(); } - // Use the set method which preserves children from baseToken to newToken and replaces + // Use the set method which preserves children from baseToken to newToken and + // replaces set(baseToken, newToken); return newToken; } @@ -207,7 +203,8 @@ public static > void delete(K baseToken) { } /** - * Replaces 'baseToken' with 'newNode'. Uses the children of 'baseToken' instead of 'newNode'. + * Replaces 'baseToken' with 'newNode'. Uses the children of 'baseToken' instead + * of 'newNode'. * * @param baseToken * @param newToken @@ -241,12 +238,6 @@ public static > void set(K baseToken, K newToken) { } throw new RuntimeException("Should have found the base node"); - - // List newTokenChildren = newToken.getChildren(); - - // baseToken.setChildren(newTokenChildren); - // baseToken.setType(newToken.getType()); - // baseToken.setContent(newToken.getContent()); } /** @@ -276,8 +267,6 @@ public static > List getRank(K token, TokenTester Integer selfRank = getSelfRank(parent, currentToken, test); rank.add(0, selfRank); - // Integer currentRank = getSelfRank(token, test); - // System.out.println("SELF RANK:"+currentRank); return rank; } @@ -290,15 +279,6 @@ public static > List getRank(K token, TokenTester */ private static > Integer getSelfRank(K parent, K token, TokenTester test) { - - // Get first parent that passes the test - // K parent = getParent(token, test); - - // If null, get root node - // if(parent == null) { - // parent = token.getRoot(); - // } - // Get iterator with pruning Iterator iterator = IteratorUtils.getDepthIterator(parent, test, true); int counter = 1; @@ -337,13 +317,13 @@ public static > K getParent(K token, TokenTester test) { * Swaps the positions of node1 and node2. * *

- * If 'swapSubtrees' is enabled, this transformation is not allowed if any of the nodes is a part of the subtree of - * the other. + * If 'swapSubtrees' is enabled, this transformation is not allowed if any of + * the nodes is a part of the subtree of the other. * * @param node1 * @param node2 - * @param swapSubtrees - * if true, swaps the complete subtrees. Otherwise, swaps only the nodes, and children are kept in place. + * @param swapSubtrees if true, swaps the complete subtrees. Otherwise, swaps + * only the nodes, and children are kept in place. */ public static > void swap(K node1, K node2, boolean swapSubtrees) { // If swap subtrees is enable, check if a node is an ancestor of the other diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNode.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNode.java index 5b406c82..f506e1d1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNode.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNode.java @@ -31,12 +31,6 @@ public interface TreeNode> { - /** - * - * @return a mutable view of the children - */ - // List getChildrenMutable(); - /** * * @return @@ -60,7 +54,6 @@ default boolean hasChildren() { */ default String toNodeString() { String prefix = getNodeName(); - // String prefix = getType().toString(); String content = toContentString(); if (content.isEmpty()) { return prefix; @@ -187,7 +180,8 @@ default K getChild(int index1, int index2, int... indexes) { * Returns an unmodifiable view of the children of the token. * *

- * To modify the children of the token use methods such as addChild() or removeChild(). + * To modify the children of the token use methods such as addChild() or + * removeChild(). * * @return the children */ @@ -220,7 +214,8 @@ default List getChildrenOf(Class aClass) { } /** - * Searches for a child of the given class. If more than one child is found, throws exception. + * Searches for a child of the given class. If more than one child is found, + * throws exception. * * @param * @param aClass @@ -244,8 +239,6 @@ default List getChildren(Class aClass, int startIndex) { return cast(subList(getChildren(), startIndex), aClass); } - // Object getContent(); - /** * * @return a string representing the contents of the node @@ -253,22 +246,7 @@ default List getChildren(Class aClass, int startIndex) { String toContentString(); /** - * If getContent() returns null, this method returns an empty string. - * - * @return - */ - // default String toContentString() { - // Object content = getContent(); - // if (content == null) { - // return ""; - // } - // - // return getContent().toString(); - // } - - /** - * @param children - * the children to set + * @param children the children to set */ void setChildren(Collection children); @@ -322,7 +300,8 @@ default int removeChild(K child) { } /** - * Replaces the token at the specified position in this list with the specified token. + * Replaces the token at the specified position in this list with the specified + * token. * * @param index * @param token @@ -332,8 +311,8 @@ default int removeChild(K child) { /** * * @param child - * @return the object that was really inserted in the tree (e.g., if child already had a parent, usually a copy is - * inserted) + * @return the object that was really inserted in the tree (e.g., if child + * already had a parent, usually a copy is inserted) */ // boolean addChild(K child); K addChild(K child); @@ -368,7 +347,8 @@ default void addChildren(List children) { K copy(); /** - * Returns a new copy of the node with the same content and type, but not children. + * Returns a new copy of the node with the same content and type, but not + * children. * * @return */ @@ -387,8 +367,7 @@ default T getAncestor(Class type) { /** * Tests whether the given node is an ancestor of this node. * - * @param node - * the node to test + * @param node the node to test * @return true if it is ancestor, false otherwise */ default boolean isAncestor(K node) { @@ -434,7 +413,8 @@ default boolean hasParent() { } /** - * @return the index of this token in its parent token, or -1 if it does not have a parent + * @return the index of this token in its parent token, or -1 if it does not + * have a parent */ default int indexOfSelf() { if (!hasParent()) { @@ -447,7 +427,8 @@ default int indexOfSelf() { /** * * @param nodeClass - * @return the index of the first child that is an instance of the given class, or -1 if none is found + * @return the index of the first child that is an instance of the given class, + * or -1 if none is found */ default int getChildIndex(Class nodeClass) { for (int i = 0; i < getNumChildren(); i++) { @@ -485,10 +466,12 @@ default Optional getChildTry(Class nodeClass, int index) { } /** - * Convenience method to get a child by index safely, without requiring a class parameter. + * Convenience method to get a child by index safely, without requiring a class + * parameter. * * @param index the index of the child to retrieve - * @return an Optional containing the child if the index is valid, Optional.empty() otherwise + * @return an Optional containing the child if the index is valid, + * Optional.empty() otherwise */ default Optional getChildTry(int index) { if (index < 0 || index >= getNumChildren()) { @@ -497,12 +480,6 @@ default Optional getChildTry(int index) { return Optional.of(getChild(index)); } - /* - default boolean is(Class nodeClass) { - return nodeClass.isInstance(this); - } - */ - /** * By default, returns the name of the class. * @@ -517,10 +494,8 @@ default String getNodeName() { * * * @param token - * @param startIndex - * (inclusive) - * @param endIndex - * (exclusive) + * @param startIndex (inclusive) + * @param endIndex (exclusive) */ default void removeChildren(int startIndex, int endIndex) { @@ -542,8 +517,8 @@ default void removeChildren(int startIndex, int endIndex) { } /** - * Sets 'newChild' in 'token' at the position 'startIndex', and removes tokens from startIndex+1 (inclusive) to - * endIndex (exclusive). + * Sets 'newChild' in 'token' at the position 'startIndex', and removes tokens + * from startIndex+1 (inclusive) to endIndex (exclusive). * *

* If startIndex+1 is equal to endIndex, no tokens are removed from the list. @@ -591,7 +566,8 @@ default int indexOfChild(K child) { /** * Returns an Iterator of the children of the node. * - * @return a ListIterator over the children of the node. The iterator supports methods that modify the node (set, + * @return a ListIterator over the children of the node. The iterator supports + * methods that modify the node (set, * remove, insert...) */ default ChildrenIterator getChildrenIterator() { @@ -604,12 +580,14 @@ default ChildrenIterator getChildrenIterator() { public void removeParent(); /** - * Detaches this node from the parent. If this node does not have a parent, throws an exception. + * Detaches this node from the parent. If this node does not have a parent, + * throws an exception. */ public void detach(); /** - * Sets this node as the parent of the given node. If the given node already has a parent, throws an exception. + * Sets this node as the parent of the given node. If the given node already has + * a parent, throws an exception. * * @param childToken */ @@ -649,7 +627,8 @@ default List getRightSiblings() { /** * - * @return the depth of this node (e.g., 0 if it has no parent, 1 if it is a child of the root node) + * @return the depth of this node (e.g., 0 if it has no parent, 1 if it is a + * child of the root node) */ default int getDepth() { if (!hasParent()) { @@ -662,9 +641,9 @@ default int getDepth() { /** * * @param child - * the child left of which the sibling will be inserted + * the child left of which the sibling will be inserted * @param sibling - * the node to be inserted + * the node to be inserted */ default public void addChildLeftOf(K child, K sibling) { var idx = indexOfChild(child); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeIndexUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeIndexUtils.java index 55d8f897..080e718a 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeIndexUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeIndexUtils.java @@ -28,24 +28,24 @@ public class TreeNodeIndexUtils { /** - * Returns all indexes where the MatlabToken of the given type appears. If no token of that type is found returns an - * empty list. + * Returns all indexes where the MatlabToken of the given type appears. If no + * token of that type is found returns an empty list. * * @param tokenType * @param tokens * @return */ public static > List indexesOf( - List tokens, Class type) { + List tokens, Class type) { - List indexes = new ArrayList<>(); - for (int i = 0; i < tokens.size(); i++) { - if (type.isInstance(tokens.get(i))) { - indexes.add(i); - } - } + List indexes = new ArrayList<>(); + for (int i = 0; i < tokens.size(); i++) { + if (type.isInstance(tokens.get(i))) { + indexes.add(i); + } + } - return indexes; + return indexes; } /** @@ -56,90 +56,87 @@ public static > List indexesOf( * @return */ public static > K getChild(K root, Integer... indexes) { - return getChild(root, Arrays.asList(indexes)); + return getChild(root, Arrays.asList(indexes)); } /** - * Returns a child corresponding to the consecutive accesses indicated by the given indexes. + * Returns a child corresponding to the consecutive accesses indicated by the + * given indexes. * *

- * E.g.: In a structure A -> B -> C, getChild(A, 0, 0) will access the index 0 of A, which is B, and then the index - * 0 of B, returning token C. + * E.g.: In a structure A -> B -> C, getChild(A, 0, 0) will access the index 0 + * of A, which is B, and then the index 0 of B, returning token C. * *

- * If any problem happens (e.g., trying to access a child that does not exist) an exception is thrown. + * If any problem happens (e.g., trying to access a child that does not exist) + * an exception is thrown. * * @param indexes * @return */ public static > K getChild(K root, - List indexes) { + List indexes) { - K currentToken = root; - for (Integer index : indexes) { - if (!currentToken.hasChildren()) { - throw new RuntimeException("Trying to access index '" + index - + "' of a token without children.\nToken:" + currentToken); - } + K currentToken = root; + for (Integer index : indexes) { + if (!currentToken.hasChildren()) { + throw new RuntimeException("Trying to access index '" + index + + "' of a token without children.\nToken:" + currentToken); + } - if (index >= currentToken.getChildren().size()) { - throw new RuntimeException("Trying to access index '" + index - + "' of a token which has size '" + currentToken.getChildren().size() - + "'.\nToken:" + currentToken); - } + if (index >= currentToken.getChildren().size()) { + throw new RuntimeException("Trying to access index '" + index + + "' of a token which has size '" + currentToken.getChildren().size() + + "'.\nToken:" + currentToken); + } - currentToken = currentToken.getChildren().get(index); - } + currentToken = currentToken.getChildren().get(index); + } - return currentToken; + return currentToken; } /** - * In the object root, replaces the child got by using the method getChild(Token, int...) by the object - * childToInsert. + * In the object root, replaces the child got by using the method + * getChild(Token, int...) by the object childToInsert. * *

* If indexInsertion is empty or null, no modifications are made. * - * @param root - * the MatlabToken object to replace a child in. - * @param nodeToInsert - * the MatlabToken object to insert - * @param indexInsertion - * an array representing the indexes of the children to select until getting the child to replace. + * @param root the MatlabToken object to replace a child in. + * @param nodeToInsert the MatlabToken object to insert + * @param indexInsertion an array representing the indexes of the children to + * select until getting the child to replace. * - * @return root once the insertion of the object childToInsert has been done. If indexInsertion is empty or null, + * @return root once the insertion of the object childToInsert has been done. If + * indexInsertion is empty or null, * returns root. */ public static > void replaceChild(K root, - K nodeToInsert, List indexInsertion) { - - // control of the indexInsertion parameter - if (indexInsertion == null) { - return; - } - - if (indexInsertion.isEmpty()) { - return; - } - - // Node where the child will be replaced - K parentNode = null; - if (indexInsertion.size() == 1) { - parentNode = root; - } else { - int lastIdx = indexInsertion.size() - 1; - parentNode = getChild(root, indexInsertion.subList(0, lastIdx)); - } - - // Index of the child to be replaced - int lastIdx = indexInsertion.size() - 1; - int replaceIdx = indexInsertion.get(lastIdx); - // System.out.println("INDEX LIST:"+indexInsertion); - // System.out.println("INDEX TO SET:"+replaceIdx); - // System.out.println("TOKEN TO INSERT:\n"+nodeToInsert); - // System.out.println("PARENT SETTING CHILD:\n"+parentNode); - parentNode.setChild(replaceIdx, nodeToInsert); + K nodeToInsert, List indexInsertion) { + + // control of the indexInsertion parameter + if (indexInsertion == null) { + return; + } + + if (indexInsertion.isEmpty()) { + return; + } + + // Node where the child will be replaced + K parentNode = null; + if (indexInsertion.size() == 1) { + parentNode = root; + } else { + int lastIdx = indexInsertion.size() - 1; + parentNode = getChild(root, indexInsertion.subList(0, lastIdx)); + } + + // Index of the child to be replaced + int lastIdx = indexInsertion.size() - 1; + int replaceIdx = indexInsertion.get(lastIdx); + parentNode.setChild(replaceIdx, nodeToInsert); } /** @@ -151,13 +148,13 @@ public static > void replaceChild(K root, * @return */ public static > Optional lastIndexOf(List nodes, Class type) { - for (int i = nodes.size() - 1; i >= 0; i--) { - if (type.isInstance(nodes.get(i))) { - return Optional.of(i); - } - } + for (int i = nodes.size() - 1; i >= 0; i--) { + if (type.isInstance(nodes.get(i))) { + return Optional.of(i); + } + } - return Optional.empty(); + return Optional.empty(); } /** @@ -169,27 +166,27 @@ public static > Optional lastIndexOf(List node */ public static > Optional lastIndexExcept(List nodes, - Collection> exceptions) { + Collection> exceptions) { - int currentIndex = nodes.size() - 1; - while (currentIndex >= 0) { - K token = nodes.get(currentIndex); + int currentIndex = nodes.size() - 1; + while (currentIndex >= 0) { + K token = nodes.get(currentIndex); - boolean isException = false; - for (Class exception : exceptions) { - if (exception.isInstance(token)) { - isException = true; - } - } + boolean isException = false; + for (Class exception : exceptions) { + if (exception.isInstance(token)) { + isException = true; + } + } - if (!isException) { - return Optional.of(currentIndex); - } + if (!isException) { + return Optional.of(currentIndex); + } - currentIndex -= 1; - } + currentIndex -= 1; + } - return Optional.empty(); + return Optional.empty(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeUtils.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeUtils.java index 0154e5f6..1b4aee7c 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeUtils.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeUtils.java @@ -27,10 +27,9 @@ public class TreeNodeUtils { * Ensures that the token has a null parent. * * @param token - * @return the given token if it does not have a parent, or a copy of the token if it has (a copy of a token does - * not have a parent) + * @return the given token if it does not have a parent, or a copy of the token + * if it has (a copy of a token does not have a parent) */ - // public static , K extends TreeNode> K sanitizeToken(K token) { public static > K sanitizeNode(K token) { if (!token.hasParent()) { return token; @@ -41,13 +40,10 @@ public static > K sanitizeNode(K token) { return tokenCopy; } - // public static , E extends Enum> String toString(K token, String prefix) { public static > String toString(K token, String prefix) { StringBuilder builder = new StringBuilder(); - // builder.append(prefix).append(token.getType()); builder.append(prefix); - // builder.append(token.toNodeString() + "(" + token.getClass().getSimpleName() + ")"); builder.append(token.toNodeString()); builder.append("\n"); @@ -77,8 +73,9 @@ public static > List getDesce } /** - * Gets all the descendants of a certain type from a collection of nodes. In addition, if any of the provided nodes - * are of that class, then they are returned as well. + * Gets all the descendants of a certain type from a collection of nodes. In + * addition, if any of the provided nodes are of that class, then they are + * returned as well. * * @param aClass * @param nodes @@ -108,35 +105,11 @@ public static > Optional lastNodeExcept(List nodes, } return Optional.of(nodes.get(index.get())); - - /* - return currentTokens.get(index); - - int currentIndex = nodes.size() - 1; - while (currentIndex >= 0) { - K token = nodes.get(currentIndex); - - boolean isException = false; - for (Class exception : exceptions) { - if (exception.isInstance(token)) { - isException = true; - } - } - - if (!isException) { - return Optional.of(nodes.get(currentIndex)); - } - - currentIndex -= 1; - } - - return Optional.empty(); - */ } /** - * Tests two nodes, to check if one is ancestor of the other. If this is the case, returns the ancestor, otherwise - * returns Optional.empty(). + * Tests two nodes, to check if one is ancestor of the other. If this is the + * case, returns the ancestor, otherwise returns Optional.empty(). * * @param node1 * @param node2 @@ -159,11 +132,6 @@ public static , EK extends K> List copy(List nodes return nodes.stream() .map(node -> (EK) node.copy()) .collect(Collectors.toList()); - // public List getIncludesList() { - // return getIncludes().getIncludes().stream() - // .map(includeDecl -> (IncludeDecl) includeDecl.copy()) - // .collect(Collectors.toList()); - // } } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeWalker.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeWalker.java index 39a139f7..0800376e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeWalker.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/TreeNodeWalker.java @@ -1,7 +1,8 @@ package pt.up.fe.specs.util.treenode; /** - * Base class for any walker of anything that extends @{pt.up.fe.specs.util.treenode.ATreeNode} + * Base class for any walker of anything that + * extends @{pt.up.fe.specs.util.treenode.ATreeNode} * * @author Nuno * diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/ANodeTransform.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/ANodeTransform.java index 867913aa..37d78a89 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/ANodeTransform.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/ANodeTransform.java @@ -24,23 +24,23 @@ public abstract class ANodeTransform> implements NodeTrans private final List operands; public ANodeTransform(String type, List operands) { - this.type = type; - this.operands = operands; + this.type = type; + this.operands = operands; } @Override public String getType() { - return type; + return type; } @Override public List getOperands() { - return operands; + return operands; } @Override public String toString() { - return getType() + " " + getOperands().stream().map(node -> Integer.toHexString(node.hashCode())) - .collect(Collectors.joining(" ")); + return getType() + " " + getOperands().stream().map(node -> Integer.toHexString(node.hashCode())) + .collect(Collectors.joining(" ")); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformQueue.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformQueue.java index 8d0746e8..4f3a2f16 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformQueue.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformQueue.java @@ -44,11 +44,6 @@ public String getId() { * Applies the transformations in the queue, empties the queue. */ public void apply() { - // for (NodeTransform transform : getTransforms()) { - // transform.execute(); - // } - // - // instructions.clear(); applyPrivate(getTransforms()); } @@ -78,10 +73,6 @@ public String toString() { return instructions.toString(); } - // public void replace(K originalNode, K newNode) { - // replace(originalNode, newNode, getClass()); - // } - /** * * diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformResult.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformResult.java index 6f3e2fcc..0cc75a43 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformResult.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformResult.java @@ -18,7 +18,8 @@ public interface TransformResult { /** - * If true, applies this transformation to the nodes children, when using pre-order traversal strategy.
+ * If true, applies this transformation to the nodes children, when using + * pre-order traversal strategy.
* * By default returns true. * @@ -27,7 +28,7 @@ public interface TransformResult { boolean visitChildren(); static TransformResult empty() { - return new DefaultTransformResult(true); + return new DefaultTransformResult(true); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformRule.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformRule.java index ebaa162b..85f9b7b1 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformRule.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/TransformRule.java @@ -30,8 +30,8 @@ public interface TransformRule, T extends TransformResult> * Applies a transformation over a TreeNode instance. * *

- * IMPORTANT: The tree itself should not be modified inside this method, instead the method must queue the changes - * using methods from the 'queue' object. + * IMPORTANT: The tree itself should not be modified inside this method, instead + * the method must queue the changes using methods from the 'queue' object. * * @param node * @param queue @@ -42,7 +42,7 @@ public interface TransformRule, T extends TransformResult> TraversalStrategy getTraversalStrategy(); default void visit(K node) { - getTraversalStrategy().apply(node, this); + getTraversalStrategy().apply(node, this); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/impl/DefaultTransformResult.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/impl/DefaultTransformResult.java index edea315a..16d9d16c 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/impl/DefaultTransformResult.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/impl/DefaultTransformResult.java @@ -20,12 +20,12 @@ public class DefaultTransformResult implements TransformResult { private final boolean visitChildren; public DefaultTransformResult(boolean visitChildren) { - this.visitChildren = visitChildren; + this.visitChildren = visitChildren; } @Override public boolean visitChildren() { - return visitChildren; + return visitChildren; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/MoveBeforeTransform.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/MoveBeforeTransform.java index 48180423..822187cf 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/MoveBeforeTransform.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/MoveBeforeTransform.java @@ -20,12 +20,12 @@ public class MoveBeforeTransform> extends TwoOperandTransform { public MoveBeforeTransform(K baseNode, K newNode) { - super("move-before", baseNode, newNode); + super("move-before", baseNode, newNode); } @Override public void execute() { - NodeInsertUtils.insertBefore(getNode1(), getNode2(), true); + NodeInsertUtils.insertBefore(getNode1(), getNode2(), true); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/ReplaceTransform.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/ReplaceTransform.java index 473b3bf7..fab95429 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/ReplaceTransform.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/ReplaceTransform.java @@ -20,13 +20,12 @@ public class ReplaceTransform> extends TwoOperandTransform { public ReplaceTransform(K baseNode, K newNode) { - super("replace", baseNode, newNode); - + super("replace", baseNode, newNode); } @Override public void execute() { - NodeInsertUtils.replace(getOperands().get(0), getOperands().get(1), true); + NodeInsertUtils.replace(getOperands().get(0), getOperands().get(1), true); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/SwapTransform.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/SwapTransform.java index 9aced818..da183ee5 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/SwapTransform.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/transformations/SwapTransform.java @@ -21,22 +21,12 @@ public class SwapTransform> extends TwoOperandTransform private final boolean swapSubtrees; - /** - * Helper constructors that enables 'swapSubtrees' by default. - * - * @param baseNode - * @param newNode - */ - // public SwapTransform(K baseNode, K newNode) { - // this(baseNode, newNode, true); - // } - /** * Swaps the positions of node1 and node2. * *

- * If 'swapSubtrees' is enabled, this transformation is not allowed if any of the nodes is a part of the subtree of - * the other. + * If 'swapSubtrees' is enabled, this transformation is not allowed if any of + * the nodes is a part of the subtree of the other. * * @param node1 * @param node2 diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/util/TraversalStrategy.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/util/TraversalStrategy.java index c718af28..c47f70f0 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/util/TraversalStrategy.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/transform/util/TraversalStrategy.java @@ -53,20 +53,21 @@ public , T extends TransformResult> TransformQueue getT private , T extends TransformResult> void traverseTree(K node, TransformRule rule, TransformQueue queue) { switch (this) { - case POST_ORDER: - bottomUpTraversal(node, rule, queue); - return; - case PRE_ORDER: - topDownTraversal(node, rule, queue); - return; - default: - SpecsLogs.warn("Case not defined:" + this); - return; + case POST_ORDER: + bottomUpTraversal(node, rule, queue); + return; + case PRE_ORDER: + topDownTraversal(node, rule, queue); + return; + default: + SpecsLogs.warn("Case not defined:" + this); + return; } } /** - * Apply the rule to the given token and all children in the token tree, bottom up. + * Apply the rule to the given token and all children in the token tree, bottom + * up. * * @param node * @param rule @@ -84,7 +85,8 @@ private , T extends TransformResult> void bottomUpTraversa } /** - * Apply the rule to the given token and all children in the token tree, top down. + * Apply the rule to the given token and all children in the token tree, top + * down. * * @param node * @param rule diff --git a/SpecsUtils/src/pt/up/fe/specs/util/treenode/utils/JsonWriter.java b/SpecsUtils/src/pt/up/fe/specs/util/treenode/utils/JsonWriter.java index 51e25817..c96b3162 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/treenode/utils/JsonWriter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/treenode/utils/JsonWriter.java @@ -25,51 +25,51 @@ public class JsonWriter> { private final FunctionClassMap jsonTranslators; public JsonWriter(FunctionClassMap jsonTranslator) { - this.jsonTranslators = jsonTranslator; + this.jsonTranslators = jsonTranslator; } public String toJson(K node) { - return toJson(node, 0); + return toJson(node, 0); } private String toJson(K node, int identationLevel) { - BuilderWithIndentation builder = new BuilderWithIndentation(identationLevel, " "); + BuilderWithIndentation builder = new BuilderWithIndentation(identationLevel, " "); - builder.addLines("{"); - builder.increaseIndentation(); + builder.addLines("{"); + builder.increaseIndentation(); - // Get JSON for the node - String nodeJson = jsonTranslators.apply(node); - builder.addLines(nodeJson); + // Get JSON for the node + String nodeJson = jsonTranslators.apply(node); + builder.addLines(nodeJson); - // Add children - List children = node.getChildren(); - if (children.size() == 0) { - builder.addLines("\"children\": []"); - } else { - StringBuilder childrenBuilder = new StringBuilder(); - childrenBuilder.append("\"children\": [\n"); + // Add children + List children = node.getChildren(); + if (children.size() == 0) { + builder.addLines("\"children\": []"); + } else { + StringBuilder childrenBuilder = new StringBuilder(); + childrenBuilder.append("\"children\": [\n"); - String childrenString = children.stream() - .map(child -> toJson(child, builder.getCurrentIdentation() - 1)) - .collect(Collectors.joining(",\n")); + String childrenString = children.stream() + .map(child -> toJson(child, builder.getCurrentIdentation() - 1)) + .collect(Collectors.joining(",\n")); - childrenBuilder.append(childrenString); - childrenBuilder.append("]"); + childrenBuilder.append(childrenString); + childrenBuilder.append("]"); - builder.addLines(childrenBuilder.toString()); - } + builder.addLines(childrenBuilder.toString()); + } - builder.decreaseIndentation(); - builder.add("}"); + builder.decreaseIndentation(); + builder.add("}"); - return builder.toString(); + return builder.toString(); } public static String escape(String string) { - String escapedString = string.replace("\\", "\\\\"); - escapedString = escapedString.replace("\"", "\\\""); + String escapedString = string.replace("\\", "\\\\"); + escapedString = escapedString.replace("\"", "\\\""); - return escapedString; + return escapedString; } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/AverageType.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/AverageType.java index 361525a3..da680669 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/AverageType.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/AverageType.java @@ -31,35 +31,34 @@ public enum AverageType { HARMONIC_MEAN(false); private AverageType(boolean ignoresZeros) { - this.ignoresZeros = ignoresZeros; + this.ignoresZeros = ignoresZeros; } public boolean ignoresZeros() { - return this.ignoresZeros; + return this.ignoresZeros; } public double calcAverage(Collection values) { - if (values == null) { - return 0; - } + if (values == null) { + return 0; + } - switch (this) { - case ARITHMETIC_MEAN: - return SpecsMath.arithmeticMean(values); - case ARITHMETIC_MEAN_WITHOUT_ZEROS: - return SpecsMath.arithmeticMeanWithoutZeros(values); - case GEOMETRIC_MEAN: - return SpecsMath.geometricMean(values, false); - case GEOMETRIC_MEAN_WITHOUT_ZEROS: - return SpecsMath.geometricMean(values, true); - case HARMONIC_MEAN: - // return CalcUtils.harmonicMean(values); - return SpecsMath.harmonicMean(values, true); - default: - SpecsLogs.getLogger(). - warning("Case not implemented: '" + this + "'"); - return 0.0; - } + switch (this) { + case ARITHMETIC_MEAN: + return SpecsMath.arithmeticMean(values); + case ARITHMETIC_MEAN_WITHOUT_ZEROS: + return SpecsMath.arithmeticMeanWithoutZeros(values); + case GEOMETRIC_MEAN: + return SpecsMath.geometricMean(values, false); + case GEOMETRIC_MEAN_WITHOUT_ZEROS: + return SpecsMath.geometricMean(values, true); + case HARMONIC_MEAN: + // return CalcUtils.harmonicMean(values); + return SpecsMath.harmonicMean(values, true); + default: + SpecsLogs.getLogger().warning("Case not implemented: '" + this + "'"); + return 0.0; + } } private final boolean ignoresZeros; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/Buffer.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/Buffer.java index be08f986..32bcf2be 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/Buffer.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/Buffer.java @@ -45,7 +45,8 @@ public Buffer(int numBuffers, Supplier constructor) { } /** - * Returns the buffer according to the relative index. If index is 0, returns the current buffer. + * Returns the buffer according to the relative index. If index is 0, returns + * the current buffer. * * @param index * @return @@ -72,7 +73,8 @@ public T getCurrent() { } /** - * Moves the relative index of the current buffer to the next buffer, returns the next buffer. + * Moves the relative index of the current buffer to the next buffer, returns + * the next buffer. * * @return */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/BufferedStringBuilder.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/BufferedStringBuilder.java index a20abb26..a9595a29 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/BufferedStringBuilder.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/BufferedStringBuilder.java @@ -40,7 +40,8 @@ public BufferedStringBuilder(File outputFile) { } /** - * WARNING: The contents of the file given to this class will be erased when the object is created. + * WARNING: The contents of the file given to this class will be erased when the + * object is created. * * @param outputFile */ @@ -64,7 +65,6 @@ public void close() { } save(); - // IoUtils.append(writeFile, builder.toString()); this.builder = null; this.isClosed = true; } @@ -95,11 +95,8 @@ public BufferedStringBuilder append(String string) { // Add to StringBuilder this.builder.append(string); - // System.out.println("BUILDER ("+this.hashCode()+"):\n"+builder.toString()); - // if (builder.length() > DEFAULT_BUFFER_CAPACITY) { if (this.builder.length() >= this.bufferCapacity) { - // System.out.println("ADASDADADADASD BUILDER ("+this.hashCode()+"):\n"+builder.toString()); save(); } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/BuilderWithIndentation.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/BuilderWithIndentation.java index 3b1cde1b..5e38c450 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/BuilderWithIndentation.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/BuilderWithIndentation.java @@ -90,13 +90,6 @@ public BuilderWithIndentation addLines(String lines) { .forEach(line -> addLine(line)); return this; - /* - try (LineStream reader = LineStream.createLineReader(lines)) { - for (String line : reader.getIterable()) { - addLineHelper(line); - } - } - */ } @Override @@ -105,7 +98,8 @@ public String toString() { } /** - * Appends the current indentation, the string and a newline to the current buffer. + * Appends the current indentation, the string and a newline to the current + * buffer. * * @param line */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ClassMapper.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ClassMapper.java index 7f8a9226..ebee73a8 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ClassMapper.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ClassMapper.java @@ -21,8 +21,9 @@ import java.util.Set; /** - * Maps classes to other assignable classes that have been added to this instance, respecting the hierarchy and the - * order by which classes where added. + * Maps classes to other assignable classes that have been added to this + * instance, respecting the hierarchy and the order by which classes where + * added. * * @author jbispo * diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/JarPath.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/JarPath.java index 1c9960da..32ab12ea 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/JarPath.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/JarPath.java @@ -73,10 +73,9 @@ private String buildJarPathInternal() { jarPath = jarPath.replace('\\', '/'); jarPath = jarPath.substring(0, jarPath.lastIndexOf("/") + 1); - // 3. As last resort, return current directory. Warn user and recommend to set property + // 3. As last resort, return current directory. Warn user and recommend to set + // property if (verbose) { - // SpecsLogs.warn("Could not find Jar path (maybe application is being run from " - // + "another application in a different process)"); SpecsLogs.debug(() -> "Could not find Jar path (maybe application is being run from " + "another application in a different process)"); SpecsLogs.msgInfo( @@ -87,7 +86,6 @@ private String buildJarPathInternal() { } return jarPath; - } private Optional buildJarPathInternalTry() { diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/LastUsedItems.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/LastUsedItems.java index 01dcb462..d295d7fd 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/LastUsedItems.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/LastUsedItems.java @@ -33,36 +33,24 @@ public class LastUsedItems { private final LinkedList currentItemsList; public LastUsedItems(int capacity) { - this.capacity = capacity; - currentItemsSet = new HashSet<>(capacity); - currentItemsList = new LinkedList<>(); + this.capacity = capacity; + currentItemsSet = new HashSet<>(capacity); + currentItemsList = new LinkedList<>(); } public LastUsedItems(int capacity, List items) { - this(capacity); - - for (T item : items) { - - // Do not add more after reaching maximum capacity - if (currentItemsList.size() == capacity) { - break; - } - - currentItemsList.add(item); - currentItemsSet.add(item); - } - - // - // // Go to the end of the list - // ListIterator iterator = items.listIterator(); - // while (iterator.hasNext()) { - // iterator.next(); - // } - // - // // Add items of the list in reverse order - // for (int i = 0; i < items.size(); i++) { - // used(items.listIterator().previous()); - // } + this(capacity); + + for (T item : items) { + + // Do not add more after reaching maximum capacity + if (currentItemsList.size() == capacity) { + break; + } + + currentItemsList.add(item); + currentItemsSet.add(item); + } } /** @@ -72,34 +60,34 @@ public LastUsedItems(int capacity, List items) { * @return true if there were changes to the list of items */ public boolean used(T item) { - // Check if item is already in the list - if (currentItemsSet.contains(item)) { - // If is already the first one, return - if (currentItemsList.getFirst().equals(item)) { - return false; - } - - // Otherwise, move item to the top - currentItemsList.remove(item); - currentItemsList.addFirst(item); - return true; - } - - // Check if there is still place to add the item to the head of the list - if (currentItemsList.size() < capacity) { - currentItemsList.addFirst(item); - currentItemsSet.add(item); - return true; - } - - // No more space, remove last item and add item to the head of the list - T lastElement = currentItemsList.removeLast(); - currentItemsSet.remove(lastElement); - - currentItemsList.addFirst(item); - currentItemsSet.add(item); - - return true; + // Check if item is already in the list + if (currentItemsSet.contains(item)) { + // If is already the first one, return + if (currentItemsList.getFirst().equals(item)) { + return false; + } + + // Otherwise, move item to the top + currentItemsList.remove(item); + currentItemsList.addFirst(item); + return true; + } + + // Check if there is still place to add the item to the head of the list + if (currentItemsList.size() < capacity) { + currentItemsList.addFirst(item); + currentItemsSet.add(item); + return true; + } + + // No more space, remove last item and add item to the head of the list + T lastElement = currentItemsList.removeLast(); + currentItemsSet.remove(lastElement); + + currentItemsList.addFirst(item); + currentItemsSet.add(item); + + return true; } /** @@ -107,14 +95,14 @@ public boolean used(T item) { * @return the current list of items */ public List getItems() { - return currentItemsList; + return currentItemsList; } public Optional getHead() { - if (currentItemsList.isEmpty()) { - return Optional.empty(); - } + if (currentItemsList.isEmpty()) { + return Optional.empty(); + } - return Optional.of(currentItemsList.getFirst()); + return Optional.of(currentItemsList.getFirst()); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/LineStream.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/LineStream.java index 8beeff3a..622b020d 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/LineStream.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/LineStream.java @@ -102,7 +102,8 @@ public long getReadChars() { } /** - * Helper method which uses the name of the resource as the name of the stream by default. + * Helper method which uses the name of the resource as the name of the stream + * by default. * * @param resource * @return @@ -115,8 +116,8 @@ public static LineStream newInstance(ResourceProvider resource) { * Creates a new LineStream from a resource. * * @param resource - * @param useResourceName - * if true, uses the resource name as the name of the line reader. Otherwise, uses no name + * @param useResourceName if true, uses the resource name as the name of the + * line reader. Otherwise, uses no name * @return */ public static LineStream newInstance(ResourceProvider resource, boolean useResourceName) { @@ -137,11 +138,14 @@ public static LineStream newInstance(ResourceProvider resource, boolean useResou /** * * @param file - * @return a new LineStream backed by the given file. If the object could not be created, throws a RuntimeException. + * @return a new LineStream backed by the given file. If the object could not be + * created, throws a RuntimeException. */ - // Cannot close resource, since the stream must remain open after LineStream is created. - // However, LineStream is a decorator of the FileInputStream, that will close it when the LineStream is closed public static LineStream newInstance(File file) { + // Cannot close resource, since the stream must remain open after LineStream is + // created. + // However, LineStream is a decorator of the FileInputStream, that will close it + // when the LineStream is closed try { final FileInputStream fileStream = new FileInputStream(file); @@ -160,18 +164,6 @@ public static LineStream newInstance(String string) { } catch (final IOException e) { throw new RuntimeException("Problem while using LineStream backed by a String", e); } - - /* - try { - final InputStreamReader streamReader = new InputStreamReader( - new ByteArrayInputStream(string.getBytes("UTF-8"))); - - return newInstance(streamReader, Optional.empty()); - - } catch (final IOException e) { - throw new RuntimeException("Problem while using LineStream backed by a String", e); - } - */ } public static LineStream newInstance(InputStream inputStream, String name) { @@ -183,8 +175,8 @@ public static LineStream newInstance(InputStream inputStream, String name) { * * @param reader * @param name - * @return a new LineStream backed by the given Reader. If the object could not be created, throws a - * RuntimeException. + * @return a new LineStream backed by the given Reader. If the object could not + * be created, throws a RuntimeException. */ public static LineStream newInstance(Reader reader, Optional name) { final BufferedReader newReader = new BufferedReader(reader); @@ -207,7 +199,8 @@ public String peekNextLine() { /** * TODO: Rename 'next' * - * @return the next line in the file, or null if the end of the stream has been reached. + * @return the next line in the file, or null if the end of the stream has been + * reached. */ public String nextLine() { if (nextLine != null) { @@ -263,17 +256,13 @@ private String nextLineHelper() { return line; } catch (final IOException ex) { - // SpecsLogs.warn("Could not read line.", ex); - // fileEnded = true; - // reader.close(); throw new RuntimeException("Could not read line.", ex); - // LoggingUtils.msgWarn("Could not read line.", ex); - // return null; } } /** - * @return the next line which is not empty, or null if the end of the stream has been reached. + * @return the next line which is not empty, or null if the end of the stream + * has been reached. */ public String nextNonEmptyLine() { for (;;) { @@ -308,7 +297,8 @@ private static List readLines(LineStream lineReader) { } /** - * Creates an Iterable over the LineReader. LineReader has to be disposed after use. + * Creates an Iterable over the LineReader. LineReader has to be disposed after + * use. * * @return */ @@ -349,7 +339,8 @@ public void remove() { } /** - * Creates a stream over the LineReader. LineReader has to be disposed after use. + * Creates a stream over the LineReader. LineReader has to be disposed after + * use. * * @return */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/MemoryProfiler.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/MemoryProfiler.java index 6b01e9ad..b5244207 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/MemoryProfiler.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/MemoryProfiler.java @@ -30,7 +30,8 @@ import pt.up.fe.specs.util.SpecsSystem; /** - * Launches a thread that periodically calls the garbage collector and reads the memory used after collection. + * Launches a thread that periodically calls the garbage collector and reads the + * memory used after collection. * * @author JBispo * @@ -48,25 +49,18 @@ public MemoryProfiler(long period, TimeUnit timeUnit, File outputFile) { } /** - * Helper constructor, which measure memory every 500 milliseconds, to a file "memory_profile.csv" in the current - * working directory. + * Helper constructor, which measure memory every 500 milliseconds, to a file + * "memory_profile.csv" in the current working directory. */ public MemoryProfiler() { this(500, TimeUnit.MILLISECONDS, new File("memory_profile.csv")); } - // public static void run(long period, TimeUnit timeUnit, ) { - // ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - // scheduler.scheduleAtFixedRate(yourRunnable, 0, period, timeUnit); - // } - public void execute() { - // Launch thread var threadExecutor = Executors.newSingleThreadExecutor(); threadExecutor.execute(this::profile); threadExecutor.shutdown(); - } private void profile() { @@ -105,7 +99,6 @@ public void run() { while (true) { // Sleep - // SpecsLogs.info("Sleeping..."); try { Thread.sleep(totalMillis, (int) partialNanos); } catch (InterruptedException e) { @@ -125,15 +118,10 @@ public void run() { // Write to file writer.write(line, 0, line.length()); - // writer.flush(); - // System.out.println("WROTE " + line); } } catch (Exception e) { SpecsLogs.info("Interrupting memory profile, " + e.getMessage()); } - - // SpecsIo.append(file, contents) - // try() } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/PatternDetector.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/PatternDetector.java index fb63ac3b..51a9e692 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/PatternDetector.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/PatternDetector.java @@ -33,15 +33,14 @@ public class PatternDetector { */ private final int maxPatternSize; private final BitSet[] matchQueues; - // private PushingQueue queue; private final PushingQueue queue2; private int currentPatternSize; private PatternState state; private final boolean priorityToBiggerPatterns; /** - * Creates a new PatternFinder which will try to find patterns of maximum size 'maxPatternSize', in the given - * integer values. + * Creates a new PatternFinder which will try to find patterns of maximum size + * 'maxPatternSize', in the given integer values. * * @param maxPatternSize */ @@ -57,18 +56,13 @@ public PatternDetector(int maxPatternSize, boolean priorityToBiggerPatterns) { for (int i = 0; i < maxPatternSize; i++) { this.matchQueues[i] = new BitSet(); } - // queue = new PushingQueue(maxPatternSize + 1); - // queue2 = new PushingQueueOld<>(maxPatternSize + 1); + this.queue2 = new MixedPushingQueue<>(maxPatternSize + 1); // Initialize Queue for (int i = 0; i < this.queue2.size(); i++) { this.queue2.insertElement(null); } - // for (int i = 0; i < queue.size(); i++) { - // queue.insertElement(null); - // } - } public int getMaxPatternSize() { @@ -82,12 +76,10 @@ public int getMaxPatternSize() { */ public PatternState step(Integer hashValue) { // Insert new element - // queue.insertElement(hashValue); this.queue2.insertElement(hashValue); // Compare first element with all other elements and store result on // match queues - // List elements = queue.getElements(1, maxPatternSize + 1); Iterator iterator = this.queue2.iterator(); // Ignore first element of the queue @@ -96,9 +88,7 @@ public PatternState step(Integer hashValue) { for (int i = 0; i < this.maxPatternSize; i++) { // Check if there is a match - // if (hashValue.equals(queue.getElement(i + 1))) { if (hashValue.equals(iterator.next())) { - // if (hashValue.equals(elements.get(i))) { // We have a match. // Shift match queue to the left this.matchQueues[i] = this.matchQueues[i].get(1, i + 1); @@ -126,63 +116,6 @@ public PatternState step(Integer hashValue) { return this.state; } - /** - * Gives another value to check for pattern. - * - * @param value - */ - /* - public PatternState step2(Integer hashValue) { - // Insert new element - this.queue2.insertElement(hashValue); - - // Ignore first element of the queue - IntStream.range(1, queue2.size()) - .forEach(i -> ); - - // this.queue2.stream() - - // .skip(1) - // . - // Compare first element with all other elements and store result on - // match queues - Iterator iterator = this.queue2.iterator(); - - // Ignore first element of the queue - iterator.next(); - - for (int i = 0; i < this.maxPatternSize; i++) { - - // Check if there is a match - if (hashValue.equals(iterator.next())) { - // We have a match. - // Shift match queue to the left - this.matchQueues[i] = this.matchQueues[i].get(1, i + 1); - // Set the bit. - this.matchQueues[i].set(i); - } else { - // Reset queue - this.matchQueues[i].clear(); - } - } - - // Put all the results in a single bit array - BitSet bitArray = new BitSet(); - for (int i = 0; i < this.matchQueues.length; i++) { - if (this.matchQueues[i].get(0)) { - bitArray.set(i); - } else { - bitArray.clear(i); - } - } - - int newPatternSize = calculatePatternSize(bitArray, this.currentPatternSize, this.priorityToBiggerPatterns); - this.state = calculateState(this.currentPatternSize, newPatternSize); - this.currentPatternSize = newPatternSize; - return this.state; - } - */ - public int getPatternSize() { return this.currentPatternSize; } @@ -238,7 +171,9 @@ else if (patternSize == 0) { return newState; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/PersistenceFormat.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/PersistenceFormat.java index cb4cfc6c..19706b7f 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/PersistenceFormat.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/PersistenceFormat.java @@ -32,8 +32,8 @@ public abstract class PersistenceFormat { * @return */ public boolean write(File outputFile, Object anObject) { - String contents = to(anObject); - return SpecsIo.write(outputFile, contents); + String contents = to(anObject); + return SpecsIo.write(outputFile, contents); } /** @@ -45,8 +45,8 @@ public boolean write(File outputFile, Object anObject) { * @return */ public T read(File inputFile, Class classOfObject) { - String contents = SpecsIo.read(inputFile); - return from(contents, classOfObject); + String contents = SpecsIo.read(inputFile); + return from(contents, classOfObject); } public abstract String to(Object anObject); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ProgressCounter.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ProgressCounter.java index 69bbeda1..f7a5c2c0 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ProgressCounter.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ProgressCounter.java @@ -26,15 +26,8 @@ public ProgressCounter(int maxCount) { } public String next() { - // if (this.currentCount <= this.max_count) { - // this.currentCount += 1; - // } else { - // LoggingUtils.msgWarn("Already reached the maximum count (" + this.max_count + ")"); - // } - int currentCount = nextInt(); - // String message = "(" + this.currentCount + "/" + this.max_count + ")"; String message = "(" + currentCount + "/" + this.max_count + ")"; return message; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ScheduledLinesBuilder.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ScheduledLinesBuilder.java index 0e150ff5..b8285bb8 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/ScheduledLinesBuilder.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/ScheduledLinesBuilder.java @@ -18,57 +18,58 @@ import pt.up.fe.specs.util.SpecsStrings; /** - * Builds a string representation of a scheduling, according to elements and levels. + * Builds a string representation of a scheduling, according to elements and + * levels. * * Ex.: element1 | element2 element3 | * - * TODO: Instead of building the map iteratively, store the data and build the lines when asked, to use the same space - * for the elements + * TODO: Instead of building the map iteratively, store the data and build the + * lines when asked, to use the same space for the elements * * @author Joao Bispo */ public class ScheduledLinesBuilder { public ScheduledLinesBuilder() { - this.scheduledLines = new HashMap<>(); + this.scheduledLines = new HashMap<>(); } public void addElement(String element, int nodeLevel) { - String line = this.scheduledLines.get(nodeLevel); - if (line == null) { - line = ""; - } else { - line += " | "; - } + String line = this.scheduledLines.get(nodeLevel); + if (line == null) { + line = ""; + } else { + line += " | "; + } - line += element; + line += element; - this.scheduledLines.put(nodeLevel, line); + this.scheduledLines.put(nodeLevel, line); } @Override public String toString() { - int maxLevel = this.scheduledLines.size() - 1; - return toString(maxLevel); + int maxLevel = this.scheduledLines.size() - 1; + return toString(maxLevel); } public String toString(int maxLevel) { - StringBuilder builder = new StringBuilder(); - int numberSize = Integer.toString(maxLevel).length(); - for (int i = 0; i <= maxLevel; i++) { - String line = this.scheduledLines.get(i); - if (line == null) { - line = "---"; - } - builder.append(SpecsStrings.padLeft(Integer.toString(i), numberSize, '0')). - append(" -> ").append(line).append("\n"); - } + StringBuilder builder = new StringBuilder(); + int numberSize = Integer.toString(maxLevel).length(); + for (int i = 0; i <= maxLevel; i++) { + String line = this.scheduledLines.get(i); + if (line == null) { + line = "---"; + } + builder.append(SpecsStrings.padLeft(Integer.toString(i), numberSize, '0')).append(" -> ").append(line) + .append("\n"); + } - return builder.toString(); + return builder.toString(); } public Map getScheduledLines() { - return this.scheduledLines; + return this.scheduledLines; } private final Map scheduledLines; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringLines.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringLines.java index 7a6e3571..8ab30fb3 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringLines.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringLines.java @@ -62,7 +62,8 @@ private StringLines(BufferedReader reader) { } /** - * Builds a StringLines from the given String. If the object could not be created, throws an exception. + * Builds a StringLines from the given String. If the object could not be + * created, throws an exception. * * @param string * @return @@ -78,7 +79,8 @@ public int getLastLineIndex() { } /** - * @return the next line in the file, or null if the end of the stream has been reached. + * @return the next line in the file, or null if the end of the stream has been + * reached. */ public String nextLine() { if (nextLine != null) { @@ -120,7 +122,8 @@ private String nextLineHelper() { } /** - * @return the next line which is not empty, or null if the end of the stream has been reached. + * @return the next line which is not empty, or null if the end of the stream + * has been reached. */ public String nextNonEmptyLine() { boolean foundAnswer = false; @@ -186,7 +189,8 @@ public void remove() { } /** - * Creates a stream over the LineReader. LineReader has to be disposed after use. + * Creates a stream over the LineReader. LineReader has to be disposed after + * use. * * @return */ diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringList.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringList.java index bdcfc82c..e2a812c6 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringList.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringList.java @@ -89,10 +89,10 @@ public String toString() { } /** - * Creates a StringList with the file names from the files on the list passed as parameter. + * Creates a StringList with the file names from the files on the list passed as + * parameter. * - * @param files - * - the list of files + * @param files the list of files * @return a new StringList instance */ public static StringList newInstanceFromListOfFiles(List files) { @@ -106,7 +106,9 @@ public static StringList newInstanceFromListOfFiles(List files) { return new StringList(strings); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ @Override @@ -117,7 +119,9 @@ public int hashCode() { return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ @Override diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringSlice.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringSlice.java index c601a56c..d9540060 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringSlice.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/StringSlice.java @@ -27,7 +27,6 @@ public class StringSlice implements CharSequence { protected final int startIndex; protected final int endIndex; - /** * Builds a new StringSlice, with 'whitespace' as the default separator. * @@ -271,7 +270,6 @@ public int lastIndexOf(char aChar) { return -1; } - /** * * @return an empty StringSlice. diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/Table.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/Table.java index 1f004992..8342e268 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/Table.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/Table.java @@ -28,126 +28,67 @@ public class Table { public final Map> bimap; public final Set yKeys; - // private int maxY; - // private int maxX; - public Table() { - this.bimap = new HashMap<>(); - this.yKeys = new HashSet<>(); - // maxY = 0; - // maxX = 0; + this.bimap = new HashMap<>(); + this.yKeys = new HashSet<>(); } public void put(X x, Y y, V value) { - Map yMap = this.bimap.get(x); - if (yMap == null) { - yMap = new HashMap<>(); - this.bimap.put(x, yMap); - } - - yMap.put(y, value); - this.yKeys.add(y); + Map yMap = this.bimap.get(x); + if (yMap == null) { + yMap = new HashMap<>(); + this.bimap.put(x, yMap); + } - // maxX = Math.max(maxX, x + 1); - // maxY = Math.max(maxY, y + 1); + yMap.put(y, value); + this.yKeys.add(y); } public V get(X x, Y y) { - Map yMap = this.bimap.get(x); - if (yMap == null) { - return null; - } + Map yMap = this.bimap.get(x); + if (yMap == null) { + return null; + } - return yMap.get(y); + return yMap.get(y); } public String getBoolString(X x, Y y) { - V value = get(x, y); - if (value == null) { - return "-"; - } + V value = get(x, y); + if (value == null) { + return "-"; + } - return "x"; + return "x"; } public Set xSet() { - return this.bimap.keySet(); + return this.bimap.keySet(); } public Set ySet() { - return this.yKeys; + return this.yKeys; } - /* - public void put(int x, int y, T value) { - // Y is the first list - List xList = null; - if(y < bimap.size()) { - xList = bimap.get(y); - } - - if(xList == null) { - xList = new ArrayList(); - bimap.add(y, xList); - } - - xList.add(value); - } - - public T get(int x, int y) { - // Y is the first list - List xList = null; - if(y < bimap.size()) { - xList = bimap.get(y); - } - - if(xList == null) { - return null; - } - - if(x >= xList.size()) { - return null; - } - return xList.get(x); - } - */ - /* @Override public String toString() { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - for (int y = 0; y < maxY; y++) { - if (maxX > 0) { - builder.append(getBoolString(0, y)); - } - for (int x = 1; x < maxX; x++) { - builder.append(getBoolString(x, y)); + builder.append(" "); + for (Y y : ySet()) { + builder.append(y).append(" "); } builder.append("\n"); - } - return builder.toString(); - } - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - - builder.append(" "); - for (Y y : ySet()) { - builder.append(y).append(" "); - } - builder.append("\n"); - - for (X x : xSet()) { - builder.append(x).append(" "); - for (Y y : ySet()) { - builder.append(this.bimap.get(x).get(y)).append(" "); - } - builder.append("\n"); - } - - return builder.toString(); + for (X x : xSet()) { + builder.append(x).append(" "); + for (Y y : ySet()) { + builder.append(this.bimap.get(x).get(y)).append(" "); + } + builder.append("\n"); + } + + return builder.toString(); } } diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapBar.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapBar.java index a1f6941e..81ca3d4b 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapBar.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapBar.java @@ -32,7 +32,8 @@ import pt.up.fe.specs.util.swing.GenericMouseListener; /** - * Shows a Swing frame with information about the current and maximum memory of the heap. + * Shows a Swing frame with information about the current and maximum memory of + * the heap. * * @author Ancora Group */ @@ -76,15 +77,12 @@ public void run() { } /** - * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The - * content of this method is always regenerated by the Form Editor. + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ private void initComponents() { setLayout(new BorderLayout()); - // UIManager.put("ProgressBar.background", Color.CYAN); - // UIManager.put("ProgressBar.foreground", Color.BLACK); - // UIManager.put("ProgressBar.selectionBackground", Color.BLACK); - // UIManager.put("ProgressBar.selectionForeground", Color.WHITE); jProgressBar1 = new javax.swing.JProgressBar(); jProgressBar1.setToolTipText("Click to run spGarbage Collector"); jProgressBar1.addMouseListener(GenericMouseListener.click(HeapBar::performGC)); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapWindow.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapWindow.java index 91cdd2dc..a6239e74 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapWindow.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/HeapWindow.java @@ -27,7 +27,8 @@ import pt.up.fe.specs.util.SpecsSystem; /** - * Shows a Swing frame with information about the current and maximum memory of the heap. + * Shows a Swing frame with information about the current and maximum memory of + * the heap. * * @author Ancora Group */ @@ -39,136 +40,100 @@ public class HeapWindow extends javax.swing.JFrame { /** Creates new form HeapWindow */ public HeapWindow() { - initComponents(); - long heapMaxSize = Runtime.getRuntime().maxMemory(); - - long maxSizeMb = (long) (heapMaxSize / (Math.pow(1024, 2))); - this.jLabel2.setText(this.jLabel2Prefix + maxSizeMb + "Mb"); - - final MemProgressBarUpdater memProgressBar = new MemProgressBarUpdater(this.jProgressBar1); - this.timer = new Timer(); - this.timer.scheduleAtFixedRate(new TimerTask() { - - @Override - public void run() { - try { - // (new MemProgressBarUpdater(jProgressBar1)).doInBackground(); - memProgressBar.doInBackground(); - } catch (Exception ex) { - Logger.getLogger(HeapWindow.class.getName()).log(Level.SEVERE, null, ex); - } - } - // }, 0, 750); - }, 0, HeapWindow.UPDATE_PERIOD_MS); - - /* - SwingWorker swingWorker = new SwingWorker() { - - @Override - protected Object doInBackground() throws Exception { - long heapSize = Runtime.getRuntime().totalMemory(); - long heapFreeSize = Runtime.getRuntime().freeMemory(); - long usedMemory = heapSize - heapFreeSize; - - //jProgressBar1.setString(jLabel2Prefix); - System.err.println(jProgressBar1.isStringPainted()); - - return null; - } - }; - */ + initComponents(); + long heapMaxSize = Runtime.getRuntime().maxMemory(); + + long maxSizeMb = (long) (heapMaxSize / (Math.pow(1024, 2))); + this.jLabel2.setText(this.jLabel2Prefix + maxSizeMb + "Mb"); + + final MemProgressBarUpdater memProgressBar = new MemProgressBarUpdater(this.jProgressBar1); + this.timer = new Timer(); + this.timer.scheduleAtFixedRate(new TimerTask() { + + @Override + public void run() { + try { + memProgressBar.doInBackground(); + } catch (Exception ex) { + Logger.getLogger(HeapWindow.class.getName()).log(Level.SEVERE, null, ex); + } + } + }, 0, HeapWindow.UPDATE_PERIOD_MS); } /** - * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The - * content of this method is always regenerated by the Form Editor. + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ - // @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { - this.jProgressBar1 = new javax.swing.JProgressBar(); - this.jLabel1 = new javax.swing.JLabel(); - this.jLabel2 = new javax.swing.JLabel(); - - setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); - - this.jLabel1.setText("Heap Use/Size"); - - this.jLabel2.setText("Max. Size:"); - - javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); - getContentPane().setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup( - layout.createSequentialGroup() - .addContainerGap() - .addGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup( - layout.createSequentialGroup() - .addComponent(this.jProgressBar1, - javax.swing.GroupLayout.DEFAULT_SIZE, - 172, Short.MAX_VALUE) - .addContainerGap()) - .addGroup( - layout.createSequentialGroup() - .addComponent(this.jLabel1) - .addPreferredGap( - javax.swing.LayoutStyle.ComponentPlacement.RELATED, - 19, Short.MAX_VALUE) - .addComponent(this.jLabel2) - .addContainerGap(44, Short.MAX_VALUE)))) - ); - layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup( - layout.createSequentialGroup() - .addContainerGap() - .addGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(this.jLabel1) - .addComponent(this.jLabel2)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(this.jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, - javax.swing.GroupLayout.DEFAULT_SIZE, - javax.swing.GroupLayout.PREFERRED_SIZE) - .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - ); - - pack(); + this.jProgressBar1 = new javax.swing.JProgressBar(); + this.jLabel1 = new javax.swing.JLabel(); + this.jLabel2 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + this.jLabel1.setText("Heap Use/Size"); + + this.jLabel2.setText("Max. Size:"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addComponent(this.jProgressBar1, + javax.swing.GroupLayout.DEFAULT_SIZE, + 172, Short.MAX_VALUE) + .addContainerGap()) + .addGroup( + layout.createSequentialGroup() + .addComponent(this.jLabel1) + .addPreferredGap( + javax.swing.LayoutStyle.ComponentPlacement.RELATED, + 19, Short.MAX_VALUE) + .addComponent(this.jLabel2) + .addContainerGap(44, Short.MAX_VALUE))))); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(this.jLabel1) + .addComponent(this.jLabel2)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(this.jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, + javax.swing.GroupLayout.DEFAULT_SIZE, + javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); + + pack(); }// //GEN-END:initComponents public void run() { - java.awt.EventQueue.invokeLater(() -> { - setTitle("Heap - " + SpecsSystem.getProgramName()); - setVisible(true); - }); + java.awt.EventQueue.invokeLater(() -> { + setTitle("Heap - " + SpecsSystem.getProgramName()); + setVisible(true); + }); } public void close() { - java.awt.EventQueue.invokeLater(() -> { - HeapWindow.this.timer.cancel(); - dispose(); - }); - } - - /** - * @param args - * the command line arguments - */ - /* - public static void main(String args[]) { - java.awt.EventQueue.invokeLater(new Runnable() { - public void run() { - new HeapWindow().setVisible(true); - } + java.awt.EventQueue.invokeLater(() -> { + HeapWindow.this.timer.cancel(); + dispose(); }); } - * - */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; diff --git a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/MemProgressBarUpdater.java b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/MemProgressBarUpdater.java index 70d4f70b..58fcaecf 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/MemProgressBarUpdater.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/utilities/heapwindow/MemProgressBarUpdater.java @@ -34,7 +34,6 @@ protected Object doInBackground() throws Exception { long usedMemory = heapSize - heapFreeSize; long mbFactor = (long) Math.pow(1024, 2); - // long kbFactor = (long) Math.pow(1024, 1); heapSizeMb = (int) (heapSize / mbFactor); currentSizeMb = (int) (usedMemory / mbFactor); @@ -48,8 +47,6 @@ protected Object doInBackground() throws Exception { MemProgressBarUpdater.this.jProgressBar.setMaximum(MemProgressBarUpdater.this.heapSizeMb); MemProgressBarUpdater.this.jProgressBar.setValue(MemProgressBarUpdater.this.currentSizeMb); MemProgressBarUpdater.this.jProgressBar.setString(barString); - // System.err.println("Heap Size:"+heapSizeMb); - // System.err.println("Current Size:"+currentSizeMb); }); return null; @@ -57,14 +54,6 @@ protected Object doInBackground() throws Exception { @Override protected void done() { - /* - jProgressBar.setMinimum(0); - jProgressBar.setMaximum(heapSizeMb); - jProgressBar.setValue(currentSizeMb); - System.err.println("Heap Size:"+heapSizeMb); - System.err.println("Current Size:"+currentSizeMb); - * - */ } /** diff --git a/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlElement.java b/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlElement.java index 0da26cd1..35922bd3 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlElement.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlElement.java @@ -40,7 +40,8 @@ public String getName() { /** * * @param name - * @return the value of the attribute with the given name, or empty string if no attribute with that name is present + * @return the value of the attribute with the given name, or empty string if no + * attribute with that name is present */ public String getAttribute(String name) { return element.getAttribute(name); @@ -54,8 +55,8 @@ public String getAttribute(String name, String defaultValue) { /** * * @param name - * @return the value of the attribute with the given name, or throws exception if no attribute with that name is - * present + * @return the value of the attribute with the given name, or throws exception + * if no attribute with that name is present */ public String getAttributeStrict(String name) { var result = getAttribute(name); @@ -71,7 +72,8 @@ public String getAttributeStrict(String name) { * * @param name * @param value - * @return the previous value set to the given name, of null if no value was set for that name + * @return the previous value set to the given name, of null if no value was set + * for that name */ public String setAttribute(String name, String value) { var previousValue = getAttribute(name); diff --git a/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlNode.java b/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlNode.java index 4ba8f2c9..e6c7e20e 100644 --- a/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlNode.java +++ b/SpecsUtils/src/pt/up/fe/specs/util/xml/XmlNode.java @@ -82,15 +82,14 @@ default public List getElementsByName(String name) { /** * * @param name - * @return the element that has the given name, null if no element is found, and exception if more than one element - * with that name is found + * @return the element that has the given name, null if no element is found, and + * exception if more than one element with that name is found */ default public XmlElement getElementByName(String name) { var elements = getElementsByName(name); if (elements.isEmpty()) { return null; - // throw new RuntimeException("No element with name '" + name + "'"); } if (elements.size() > 1) { @@ -126,7 +125,6 @@ default void write(StreamResult result) { Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(getNode()); - // System.out.println("CHILD NODE : " + document.getChildNodes().item(0).getChildNodes().getLength()); transformer.transform(source, result); } catch (Exception e) { @@ -147,12 +145,7 @@ default public String getString() { StreamResult result = new StreamResult(stringWriter); write(result); - // stringWriter.flush(); - // try { - // stringWriter.close(); - // } catch (IOException e) { - // throw new RuntimeException("Could not ", e); - // } + return stringWriter.toString(); } }