From 2bb1409b82c0e75fbdee37f36e7225b35636ddf7 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Sun, 3 Dec 2023 16:21:32 -0800 Subject: [PATCH] Clean up Java style (#5990) Also make equivalent changes in C++ where applicable. Co-authored-by: Sriman Achanta <68172138+srimanachanta@users.noreply.github.com> --- .../wpi/first/apriltag/LoadConfigTest.java | 3 +- .../src/main/java/edu/wpi/Main.java | 2 +- .../wpi/first/cameraserver/CameraServer.java | 2 +- .../edu/wpi/first/cscore/VideoListener.java | 2 +- .../java/edu/wpi/first/hal/DMAJNISample.java | 3 +- .../wpi/first/networktables/NetworkTable.java | 2 +- .../networktables/ProtobufEntryImpl.java | 6 +- .../first/networktables/ProtobufTopic.java | 12 ++-- .../networktables/StructArrayEntryImpl.java | 7 +-- .../first/networktables/StructArrayTopic.java | 12 ++-- .../first/networktables/StructEntryImpl.java | 6 +- .../wpi/first/networktables/StructTopic.java | 12 ++-- .../first/networktables/NetworkTableTest.java | 5 +- .../edu/wpi/first/networktables/RawTest.java | 43 +++++++------ .../wpilibj2/command/CommandScheduler.java | 4 +- .../command/ParallelRaceGroupTest.java | 2 +- .../command/SchedulingRecursionTest.java | 2 +- wpilibc/src/main/native/cpp/I2C.cpp | 3 +- wpilibc/src/main/native/cpp/PneumaticHub.cpp | 8 +-- .../simulation/DifferentialDrivetrainSim.cpp | 28 ++++----- .../main/native/include/frc/PneumaticHub.h | 1 + .../edu/wpi/first/wpilibj/ADIS16448_IMU.java | 16 ++--- .../edu/wpi/first/wpilibj/ADIS16470_IMU.java | 7 +-- .../edu/wpi/first/wpilibj/DriverStation.java | 2 + .../main/java/edu/wpi/first/wpilibj/I2C.java | 2 +- .../edu/wpi/first/wpilibj/MotorSafety.java | 2 +- .../java/edu/wpi/first/wpilibj/Notifier.java | 4 +- .../edu/wpi/first/wpilibj/PneumaticHub.java | 9 +-- .../first/wpilibj/PneumaticsModuleType.java | 2 +- .../wpi/first/wpilibj/PowerDistribution.java | 4 +- .../java/edu/wpi/first/wpilibj/RobotBase.java | 9 +-- .../wpi/first/wpilibj/RobotController.java | 2 +- .../edu/wpi/first/wpilibj/SensorUtil.java | 60 +++++++++---------- .../edu/wpi/first/wpilibj/SerialPort.java | 2 +- .../java/edu/wpi/first/wpilibj/Tracer.java | 4 +- .../java/edu/wpi/first/wpilibj/Watchdog.java | 4 +- .../first/wpilibj/livewindow/LiveWindow.java | 7 +-- .../first/wpilibj/motorcontrol/Victor.java | 3 +- .../simulation/DifferentialDrivetrainSim.java | 19 ++---- .../wpilibj/simulation/GenericHIDSim.java | 2 +- .../wpilibj/smartdashboard/FieldObject2d.java | 13 ++-- .../smartdashboard/ListenerExecutor.java | 4 +- .../edu/wpi/first/wpilibj/TimedRobotTest.java | 57 ++++-------------- .../wpi/first/wpilibj/TimesliceRobotTest.java | 20 ++----- .../edu/wpi/first/wpilibj/WatchdogTest.java | 42 ++----------- .../ShuffleboardInstanceTest.java | 2 +- .../simulation/AddressableLEDSimTest.java | 2 +- .../wpilibj/simulation/DCMotorSimTest.java | 2 +- .../wpilibj/simulation/DigitalPWMSimTest.java | 2 +- .../wpilibj/simulation/RelaySimTest.java | 4 +- .../wpilibj/simulation/SimDeviceSimTest.java | 40 +++---------- .../smartdashboard/SendableChooserTest.java | 2 +- .../ReplaceMeTrapezoidProfileCommand.java | 4 +- .../examples/apriltagsvision/Robot.java | 2 +- .../drivedistanceoffboard/RobotContainer.java | 2 +- .../commands/DriveDistanceProfiled.java | 2 +- .../subsystems/Pneumatics.java | 16 ++--- .../wpilibj/examples/solenoid/Robot.java | 38 ++++-------- .../examples/unittest/subsystems/Intake.java | 2 +- .../first/wpilibj/AbstractInterruptTest.java | 2 +- .../wpilibj/BuiltInAccelerometerTest.java | 4 +- .../wpi/first/wpilibj/MotorEncoderTest.java | 4 +- .../wpi/first/wpilibj/MotorInvertingTest.java | 4 +- .../java/edu/wpi/first/wpilibj/PDPTest.java | 6 +- .../java/edu/wpi/first/wpilibj/PIDTest.java | 6 +- .../first/wpilibj/test/AbstractComsSetup.java | 2 +- .../first/wpilibj/test/AbstractTestSuite.java | 6 +- .../first/wpilibj/test/AntJunitLauncher.java | 3 +- .../edu/wpi/first/wpilibj/test/TestBench.java | 23 ++++--- .../edu/wpi/first/wpilibj/test/TestSuite.java | 45 +++++++------- .../main/java/edu/wpi/first/math/Matrix.java | 9 ++- ...ontrolAffinePlantInversionFeedforward.java | 9 ++- .../controller/ImplicitModelFollower.java | 4 +- .../LTVDifferentialDriveController.java | 4 +- .../controller/LTVUnicycleController.java | 8 +-- .../LinearPlantInversionFeedforward.java | 4 +- .../controller/LinearQuadraticRegulator.java | 31 +++++----- .../math/estimator/ExtendedKalmanFilter.java | 14 ++--- .../first/math/estimator/KalmanFilter.java | 25 ++++---- .../estimator/SteadyStateKalmanFilter.java | 25 ++++---- .../math/estimator/UnscentedKalmanFilter.java | 19 +++--- .../wpi/first/math/filter/LinearFilter.java | 10 +++- .../wpi/first/math/geometry/Rotation3d.java | 15 ++--- .../first/math/path/TravelingSalesman.java | 2 +- .../first/math/system/LinearSystemLoop.java | 4 +- .../constraint/TrajectoryConstraint.java | 2 +- .../java/edu/wpi/first/math/DARETest.java | 6 +- ...olAffinePlantInversionFeedforwardTest.java | 6 +- .../controller/ImplicitModelFollowerTest.java | 4 +- .../LinearPlantInversionFeedforwardTest.java | 2 +- .../DifferentialDrivePoseEstimatorTest.java | 5 +- .../estimator/ExtendedKalmanFilterTest.java | 3 +- .../MecanumDrivePoseEstimatorTest.java | 5 +- .../SwerveDrivePoseEstimatorTest.java | 5 +- .../estimator/UnscentedKalmanFilterTest.java | 3 +- .../first/math/filter/LinearFilterTest.java | 20 +++---- .../wpi/first/math/geometry/Pose3dTest.java | 10 ++-- .../optimization/SimulatedAnnealingTest.java | 4 +- .../math/spline/CubicHermiteSplineTest.java | 3 +- .../math/system/NumericalIntegrationTest.java | 7 +-- .../system/RungeKuttaTimeVaryingTest.java | 7 +-- ...ifferentialDriveVoltageConstraintTest.java | 5 +- .../trajectory/TrajectoryGeneratorTest.java | 5 +- .../wpi/first/util/CombinedRuntimeLoader.java | 3 +- .../wpi/first/util/cleanup/CleanupPool.java | 2 +- .../first/util/datalog/ProtobufLogEntry.java | 2 +- .../util/datalog/StructArrayLogEntry.java | 2 +- .../first/util/datalog/StructLogEntry.java | 2 +- .../first/util/protobuf/ProtobufBuffer.java | 2 +- .../wpi/first/util/struct/StructBuffer.java | 2 +- .../util/struct/StructDescriptorDatabase.java | 4 +- .../src/printlog/java/printlog/PrintLog.java | 8 +-- .../first/util/struct/parser/ParserTest.java | 49 +++++++-------- 113 files changed, 428 insertions(+), 619 deletions(-) diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java index 901c72bd89b..d5deb573af9 100644 --- a/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java @@ -12,7 +12,6 @@ import edu.wpi.first.math.geometry.Pose3d; import edu.wpi.first.math.geometry.Rotation3d; import edu.wpi.first.math.util.Units; -import java.io.IOException; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -28,7 +27,7 @@ void testLoad(AprilTagFields field) { } @Test - void test2022RapidReact() throws IOException { + void test2022RapidReact() { AprilTagFieldLayout layout = AprilTagFields.k2022RapidReact.loadAprilTagLayoutField(); // Blue Hangar Truss - Hub diff --git a/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java b/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java index 1f791821898..f69a6feec53 100644 --- a/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java +++ b/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java @@ -98,7 +98,7 @@ public static boolean readConfig() { // parse file JsonElement top; try { - top = new JsonParser().parse(Files.newBufferedReader(Paths.get(configFile))); + top = JsonParser.parseReader(Files.newBufferedReader(Paths.get(configFile))); } catch (IOException ex) { System.err.println("could not open '" + configFile + "': " + ex); return false; diff --git a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java index 376f9608bd4..397cd20809e 100644 --- a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java +++ b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java @@ -114,7 +114,7 @@ void update(VideoEvent event) { } @Override - public void close() throws Exception { + public void close() { if (m_booleanValueEntry != null) { m_booleanValueEntry.close(); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java index 652d12db763..c95e5458be1 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java @@ -102,7 +102,7 @@ private static void startThread() { listener.accept(event); } catch (Throwable throwable) { System.err.println( - "Unhandled exception during listener callback: " + throwable.toString()); + "Unhandled exception during listener callback: " + throwable); throwable.printStackTrace(); } } diff --git a/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java b/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java index 22f21c8c6b6..7c496a17677 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java +++ b/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java @@ -131,8 +131,7 @@ public int getAnalogInputAveraged(int analogInputHandle) { } // + 2 Hack, but needed to not have to call into JNI - int value = readValue(data.m_valueType + 2, data.m_index); - return value; + return readValue(data.m_valueType + 2, data.m_index); } public void getAnalogAccumulator(int analogInputHandle, AccumulatorResult result) { diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java index 3c6593809b3..c88ce8b3c87 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java @@ -574,7 +574,7 @@ public int addSubTableListener(SubTableListener listener) { return m_inst.addListener( new String[] {m_pathWithSep}, EnumSet.of(NetworkTableEvent.Kind.kPublish, NetworkTableEvent.Kind.kImmediate), - new Consumer() { + new Consumer<>() { final Set m_notifiedTables = new HashSet<>(); @Override diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java index b4359eaf030..6d891c45169 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java @@ -190,14 +190,14 @@ private T fromRaw(byte[] raw, T defaultValue) { private TimestampedObject fromRaw(TimestampedRaw raw, T defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); } } catch (IOException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java index c3dad133a58..15313d7f683 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java @@ -32,7 +32,7 @@ private ProtobufTopic(NetworkTableInstance inst, int handle, Protobuf prot * @return ProtobufTopic for value class */ public static ProtobufTopic wrap(Topic topic, Protobuf proto) { - return new ProtobufTopic(topic, proto); + return new ProtobufTopic<>(topic, proto); } /** @@ -47,7 +47,7 @@ public static ProtobufTopic wrap(Topic topic, Protobuf proto) { */ public static ProtobufTopic wrap( NetworkTableInstance inst, int handle, Protobuf proto) { - return new ProtobufTopic(inst, handle, proto); + return new ProtobufTopic<>(inst, handle, proto); } /** @@ -63,7 +63,7 @@ public static ProtobufTopic wrap( * @return subscriber */ public ProtobufSubscriber subscribe(T defaultValue, PubSubOption... options) { - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.subscribe( @@ -87,7 +87,7 @@ public ProtobufSubscriber subscribe(T defaultValue, PubSubOption... options) */ public ProtobufPublisher publish(PubSubOption... options) { m_inst.addSchema(m_proto); - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.publish( @@ -113,7 +113,7 @@ public ProtobufPublisher publish(PubSubOption... options) { */ public ProtobufPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_proto); - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.publishEx( @@ -144,7 +144,7 @@ public ProtobufPublisher publishEx(String properties, PubSubOption... options * @return entry */ public ProtobufEntry getEntry(T defaultValue, PubSubOption... options) { - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.getEntry( diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java index 4e8a4a0495a..1e6b69ec0fd 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java @@ -177,15 +177,14 @@ private T[] fromRaw(byte[] raw, T[] defaultValue) { @SuppressWarnings("PMD.AvoidCatchingGenericException") private TimestampedObject fromRaw(TimestampedRaw raw, T[] defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject( - raw.timestamp, raw.serverTime, m_buf.readArray(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.readArray(raw.value)); } } catch (RuntimeException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java index 247501bbfa0..557e9ddf4ef 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java @@ -32,7 +32,7 @@ private StructArrayTopic(NetworkTableInstance inst, int handle, Struct struct * @return StructArrayTopic for value class */ public static StructArrayTopic wrap(Topic topic, Struct struct) { - return new StructArrayTopic(topic, struct); + return new StructArrayTopic<>(topic, struct); } /** @@ -47,7 +47,7 @@ public static StructArrayTopic wrap(Topic topic, Struct struct) { */ public static StructArrayTopic wrap( NetworkTableInstance inst, int handle, Struct struct) { - return new StructArrayTopic(inst, handle, struct); + return new StructArrayTopic<>(inst, handle, struct); } /** @@ -63,7 +63,7 @@ public static StructArrayTopic wrap( * @return subscriber */ public StructArraySubscriber subscribe(T[] defaultValue, PubSubOption... options) { - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.subscribe( @@ -87,7 +87,7 @@ public StructArraySubscriber subscribe(T[] defaultValue, PubSubOption... opti */ public StructArrayPublisher publish(PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publish( @@ -113,7 +113,7 @@ public StructArrayPublisher publish(PubSubOption... options) { */ public StructArrayPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publishEx( @@ -144,7 +144,7 @@ public StructArrayPublisher publishEx(String properties, PubSubOption... opti * @return entry */ public StructArrayEntry getEntry(T[] defaultValue, PubSubOption... options) { - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.getEntry( diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java index bd02d27fe5d..5d377657075 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java @@ -188,14 +188,14 @@ private T fromRaw(byte[] raw, T defaultValue) { @SuppressWarnings("PMD.AvoidCatchingGenericException") private TimestampedObject fromRaw(TimestampedRaw raw, T defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); } } catch (RuntimeException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java index b1ff0264f3c..22dbd2d7a17 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java @@ -32,7 +32,7 @@ private StructTopic(NetworkTableInstance inst, int handle, Struct struct) { * @return StructTopic for value class */ public static StructTopic wrap(Topic topic, Struct struct) { - return new StructTopic(topic, struct); + return new StructTopic<>(topic, struct); } /** @@ -46,7 +46,7 @@ public static StructTopic wrap(Topic topic, Struct struct) { * @return StructTopic for value class */ public static StructTopic wrap(NetworkTableInstance inst, int handle, Struct struct) { - return new StructTopic(inst, handle, struct); + return new StructTopic<>(inst, handle, struct); } /** @@ -62,7 +62,7 @@ public static StructTopic wrap(NetworkTableInstance inst, int handle, Str * @return subscriber */ public StructSubscriber subscribe(T defaultValue, PubSubOption... options) { - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.subscribe( @@ -86,7 +86,7 @@ public StructSubscriber subscribe(T defaultValue, PubSubOption... options) { */ public StructPublisher publish(PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publish( @@ -112,7 +112,7 @@ public StructPublisher publish(PubSubOption... options) { */ public StructPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publishEx( @@ -143,7 +143,7 @@ public StructPublisher publishEx(String properties, PubSubOption... options) * @return entry */ public StructEntry getEntry(T defaultValue, PubSubOption... options) { - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.getEntry( diff --git a/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java b/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java index 4c431afbdc9..bca694b9903 100644 --- a/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java +++ b/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; @@ -61,8 +60,8 @@ private static Stream getHierarchyArguments() { return Stream.of( Arguments.of(Collections.singletonList("/"), ""), Arguments.of(Collections.singletonList("/"), "/"), - Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"), - Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/")); + Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"), + Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/")); } @ParameterizedTest diff --git a/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java b/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java index 73d5efb3e7c..293d4437bdd 100644 --- a/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java +++ b/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java @@ -4,11 +4,10 @@ package edu.wpi.first.networktables; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; -import java.util.Arrays; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,9 +30,9 @@ void tearDown() { void testGenericByteArray() { GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw"); entry.setRaw(new byte[] {5}, 10); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5}); entry.setRaw(new byte[] {5, 6, 7}, 1, 2, 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, -1, 2, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, -2, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, 1, 20)); @@ -43,9 +42,9 @@ void testGenericByteArray() { void testRawByteArray() { RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {}); entry.set(new byte[] {5}, 10); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {5}); entry.set(new byte[] {5, 6, 7}, 1, 2, 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, -1, 1, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, -1, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, 1, 20)); @@ -55,15 +54,15 @@ void testRawByteArray() { void testGenericByteBuffer() { GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw"); entry.setRaw(ByteBuffer.wrap(new byte[] {5}), 10); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5}); entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6}); entry.setRaw(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0}); entry.setRaw(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {1, 2})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {1, 2}); assertThrows( IndexOutOfBoundsException.class, () -> entry.setRaw(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30)); @@ -79,15 +78,15 @@ void testGenericByteBuffer() { void testRawByteBuffer() { RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {}); entry.set(ByteBuffer.wrap(new byte[] {5}), 10); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {5}); entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6}); entry.set(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0}); entry.set(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {1, 2})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {1, 2}); assertThrows( IndexOutOfBoundsException.class, () -> entry.set(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30)); @@ -105,13 +104,13 @@ void testGenericNativeByteBuffer() { ByteBuffer bb = ByteBuffer.allocateDirect(3); bb.put(new byte[] {5, 6, 7}); entry.setRaw(bb.position(1), 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); entry.setRaw(bb.limit(2), 16); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6}); bb.clear(); bb.put(new byte[] {8, 9, 0}); entry.setRaw(bb, 1, 2, 20); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0}); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, -1, 1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 1, -1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 2, 2, 25)); @@ -123,13 +122,13 @@ void testRawNativeByteBuffer() { ByteBuffer bb = ByteBuffer.allocateDirect(3); bb.put(new byte[] {5, 6, 7}); entry.set(bb.position(1), 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); entry.set(bb.limit(2), 16); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6}); bb.clear(); bb.put(new byte[] {8, 9, 0}); entry.set(bb, 1, 2, 20); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0}); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, -1, 1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 1, -1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 2, 2, 25)); diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java index c164b08695e..41c969e7f12 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java @@ -683,9 +683,7 @@ public void initSendable(SendableBuilder builder) { null); builder.addIntegerArrayProperty( "Cancel", - () -> { - return new long[] {}; - }, + () -> new long[] {}, toCancel -> { Map ids = new LinkedHashMap<>(); for (Command command : m_scheduledCommands) { diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java index 67524960ca3..dd650c4bac8 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java @@ -153,7 +153,7 @@ void parallelRaceOnlyCallsEndOnceTest() { scheduler.run(); command2Holder.setFinished(true); // at this point the sequential group should be done - assertDoesNotThrow(() -> scheduler.run()); + assertDoesNotThrow(scheduler::run); assertFalse(scheduler.isScheduled(group2)); } } diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java index 5e8fd392e46..a253740c028 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java @@ -288,7 +288,7 @@ void cancelFromEndLoopWhileInRunLoop() { scheduler.schedule(cCancelsD); scheduler.schedule(dCancelsAll); - assertDoesNotThrow(() -> scheduler.run()); + assertDoesNotThrow(scheduler::run); assertEquals(4, counter.get()); assertFalse(scheduler.isScheduled(aCancelsB)); assertFalse(scheduler.isScheduled(bCancelsC)); diff --git a/wpilibc/src/main/native/cpp/I2C.cpp b/wpilibc/src/main/native/cpp/I2C.cpp index da26c0c9cee..232a47f0f12 100644 --- a/wpilibc/src/main/native/cpp/I2C.cpp +++ b/wpilibc/src/main/native/cpp/I2C.cpp @@ -4,6 +4,7 @@ #include "frc/I2C.h" +#include #include #include @@ -96,7 +97,7 @@ bool I2C::VerifySensor(int registerAddress, int count, uint8_t deviceData[4]; for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress += 4) { - int toRead = count - i < 4 ? count - i : 4; + int toRead = std::min(count - i, 4); // Read the chunk of data. Return false if the sensor does not respond. if (Read(curRegisterAddress, toRead, deviceData)) { return false; diff --git a/wpilibc/src/main/native/cpp/PneumaticHub.cpp b/wpilibc/src/main/native/cpp/PneumaticHub.cpp index bcbbd558026..9a0f468ec62 100644 --- a/wpilibc/src/main/native/cpp/PneumaticHub.cpp +++ b/wpilibc/src/main/native/cpp/PneumaticHub.cpp @@ -23,15 +23,15 @@ using namespace frc; /** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */ units::pounds_per_square_inch_t VoltsToPSI(units::volt_t sensorVoltage, units::volt_t supplyVoltage) { - auto pressure = 250 * (sensorVoltage.value() / supplyVoltage.value()) - 25; - return units::pounds_per_square_inch_t{pressure}; + return units::pounds_per_square_inch_t{ + 250 * (sensorVoltage.value() / supplyVoltage.value()) - 25}; } /** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */ units::volt_t PSIToVolts(units::pounds_per_square_inch_t pressure, units::volt_t supplyVoltage) { - auto voltage = supplyVoltage.value() * (0.004 * pressure.value() + 0.1); - return units::volt_t{voltage}; + return units::volt_t{supplyVoltage.value() * + (0.004 * pressure.value() + 0.1)}; } wpi::mutex PneumaticHub::m_handleLock; diff --git a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp index 4d2720f5a6f..d5addb23389 100644 --- a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp @@ -92,26 +92,22 @@ Pose2d DifferentialDrivetrainSim::GetPose() const { } units::ampere_t DifferentialDrivetrainSim::GetLeftCurrentDraw() const { - auto loadIleft = - m_motor.Current( - units::radians_per_second_t{m_x(State::kLeftVelocity) * - m_currentGearing / m_wheelRadius.value()}, - units::volt_t{m_u(0)}) * - wpi::sgn(m_u(0)); - - return loadIleft; + return m_motor.Current(units::radians_per_second_t{m_x(State::kLeftVelocity) * + m_currentGearing / + m_wheelRadius.value()}, + units::volt_t{m_u(0)}) * + wpi::sgn(m_u(0)); } units::ampere_t DifferentialDrivetrainSim::GetRightCurrentDraw() const { - auto loadIRight = - m_motor.Current( - units::radians_per_second_t{m_x(State::kRightVelocity) * - m_currentGearing / m_wheelRadius.value()}, - units::volt_t{m_u(1)}) * - wpi::sgn(m_u(1)); - - return loadIRight; + return m_motor.Current( + units::radians_per_second_t{m_x(State::kRightVelocity) * + m_currentGearing / + m_wheelRadius.value()}, + units::volt_t{m_u(1)}) * + wpi::sgn(m_u(1)); } + units::ampere_t DifferentialDrivetrainSim::GetCurrentDraw() const { return GetLeftCurrentDraw() + GetRightCurrentDraw(); } diff --git a/wpilibc/src/main/native/include/frc/PneumaticHub.h b/wpilibc/src/main/native/include/frc/PneumaticHub.h index b69b3d5cd11..415b042cae7 100644 --- a/wpilibc/src/main/native/include/frc/PneumaticHub.h +++ b/wpilibc/src/main/native/include/frc/PneumaticHub.h @@ -7,6 +7,7 @@ #include #include +#include #include #include diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java index 2eddf64ee6e..301b518cecc 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java @@ -108,9 +108,9 @@ public enum CalibrationTime { _32s(10), _64s(11); - private int value; + private final int value; - private CalibrationTime(int value) { + CalibrationTime(int value) { this.value = value; } } @@ -130,9 +130,9 @@ public enum IMUAxis { private IMUAxis m_yaw_axis; /* Offset data storage */ - private double m_offset_data_gyro_rate_x[]; - private double m_offset_data_gyro_rate_y[]; - private double m_offset_data_gyro_rate_z[]; + private double[] m_offset_data_gyro_rate_x; + private double[] m_offset_data_gyro_rate_y; + private double[] m_offset_data_gyro_rate_z; /* Instant raw output variables */ private double m_gyro_rate_x = 0.0; @@ -199,7 +199,7 @@ public enum IMUAxis { private SimDouble m_simAccelZ; /* CRC-16 Look-Up Table */ - int adiscrc[] = + int[] adiscrc = new int[] { 0x0000, 0x17CE, 0x0FDF, 0x1811, 0x1FBE, 0x0870, 0x1061, 0x07AF, 0x1F3F, 0x08F1, 0x10E0, 0x072E, 0x0081, 0x174F, 0x0F5E, 0x1890, @@ -358,7 +358,7 @@ private static long toULong(int sint) { /** */ private static int toShort(int... buf) { - return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0)); + return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF))); } /** */ @@ -481,7 +481,7 @@ boolean switchToAutoSPI() { } public int configDecRate(int m_decRate) { - int writeValue = m_decRate; + int writeValue; int readbackValue; if (!switchToStandardSPI()) { DriverStation.reportError("Failed to configure/reconfigure standard SPI.", false); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java index 2fad3f34dac..4016cd20206 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java @@ -193,9 +193,9 @@ public enum CalibrationTime { _32s(10), _64s(11); - private int value; + private final int value; - private CalibrationTime(int value) { + CalibrationTime(int value) { this.value = value; } } @@ -396,7 +396,7 @@ private static long toULong(int sint) { * @return */ private static int toShort(int... buf) { - return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0)); + return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF))); } /** @@ -593,7 +593,6 @@ public void calibrate() { if (!switchToAutoSPI()) { DriverStation.reportError("Failed to configure/reconfigure auto SPI.", false); } - ; } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java index e18afe99e7a..1c6e0c8501b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java @@ -239,6 +239,7 @@ public void send(long timestamp) { for (int i = 0; i < count; i++) { if (axes.m_axes[i] != m_prevAxes.m_axes[i]) { needToLog = true; + break; } } } @@ -255,6 +256,7 @@ public void send(long timestamp) { for (int i = 0; i < count; i++) { if (povs.m_povs[i] != m_prevPOVs.m_povs[i]) { needToLog = true; + break; } } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java index 1c37ecf27a2..0d54c4239f0 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java @@ -369,7 +369,7 @@ public boolean verifySensor(int registerAddress, int count, byte[] expected) { byte[] deviceData = new byte[4]; for (int i = 0; i < count; i += 4) { - int toRead = count - i < 4 ? count - i : 4; + int toRead = Math.min(count - i, 4); // Read the chunk of data. Return false if the sensor does not // respond. dataToSend[0] = (byte) (registerAddress + i); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java index c1bf04b8911..6f4062769df 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java @@ -66,7 +66,7 @@ public MotorSafety() { synchronized (m_listMutex) { m_instanceList.add(this); if (m_safetyThread == null) { - m_safetyThread = new Thread(() -> threadMain(), "MotorSafety Thread"); + m_safetyThread = new Thread(MotorSafety::threadMain, "MotorSafety Thread"); m_safetyThread.setDaemon(true); m_safetyThread.start(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java index 7ed61621d5a..8f381a03ffe 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java @@ -113,7 +113,7 @@ public Notifier(Runnable callback) { updateAlarm(); } else { // Need to update the alarm to cause it to wait again - updateAlarm((long) -1); + updateAlarm(-1); } } finally { m_processLock.unlock(); @@ -134,7 +134,7 @@ public Notifier(Runnable callback) { error = cause; } DriverStation.reportError( - "Unhandled exception in Notifier thread: " + error.toString(), error.getStackTrace()); + "Unhandled exception in Notifier thread: " + error, error.getStackTrace()); DriverStation.reportError( "The Runnable for this Notifier (or methods called by it) should have handled " + "the exception above.\n" diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java index b7df47f0f34..32d2ec5aee2 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java @@ -59,8 +59,7 @@ private static class DataStore implements AutoCloseable { output.write(("currentVersion=" + fwVersion).getBytes(StandardCharsets.UTF_8)); } } catch (IOException ex) { - DriverStation.reportError( - "Could not write " + fileName + ": " + ex.toString(), ex.getStackTrace()); + DriverStation.reportError("Could not write " + fileName + ": " + ex, ex.getStackTrace()); } } @@ -115,14 +114,12 @@ private static void freeModule(DataStore store) { /** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */ private static double voltsToPsi(double sensorVoltage, double supplyVoltage) { - double pressure = 250 * (sensorVoltage / supplyVoltage) - 25; - return pressure; + return 250 * (sensorVoltage / supplyVoltage) - 25; } /** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */ private static double psiToVolts(double pressure, double supplyVoltage) { - double voltage = supplyVoltage * (0.004 * pressure + 0.1); - return voltage; + return supplyVoltage * (0.004 * pressure + 0.1); } private final DataStore m_dataStore; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java index a7951e8b5c1..215a1714ca6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java @@ -6,5 +6,5 @@ public enum PneumaticsModuleType { CTREPCM, - REVPH; + REVPH } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java index a0c21042ca9..13954264e48 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java @@ -101,9 +101,7 @@ public double getTemperature() { * @return The current of the channel in Amperes */ public double getCurrent(int channel) { - double current = PowerDistributionJNI.getChannelCurrent(m_handle, channel); - - return current; + return PowerDistributionJNI.getChannelCurrent(m_handle, channel); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java index 2f59a3db7c2..4d22d2a051c 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java @@ -321,8 +321,7 @@ private static void runRobot(Supplier robotSupplier) { robotName = elements[0].getClassName(); } DriverStation.reportError( - "Unhandled exception instantiating robot " + robotName + " " + throwable.toString(), - elements); + "Unhandled exception instantiating robot " + robotName + " " + throwable, elements); DriverStation.reportError( "The robot program quit unexpectedly." + " This is usually due to a code error.\n" @@ -353,8 +352,7 @@ private static void runRobot(Supplier robotSupplier) { output.write(WPILibVersion.Version.getBytes(StandardCharsets.UTF_8)); } } catch (IOException ex) { - DriverStation.reportError( - "Could not write FRC_Lib_Version.ini: " + ex.toString(), ex.getStackTrace()); + DriverStation.reportError("Could not write FRC_Lib_Version.ini: " + ex, ex.getStackTrace()); } } @@ -366,8 +364,7 @@ private static void runRobot(Supplier robotSupplier) { if (cause != null) { throwable = cause; } - DriverStation.reportError( - "Unhandled exception: " + throwable.toString(), throwable.getStackTrace()); + DriverStation.reportError("Unhandled exception: " + throwable, throwable.getStackTrace()); errorOnExit = true; } finally { m_runMutex.lock(); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java index 29bcad87bd0..80d493ed517 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java @@ -33,7 +33,7 @@ public static int getFPGAVersion() { * @return FPGA Revision number. */ public static long getFPGARevision() { - return (long) HALUtil.getFPGARevision(); + return HALUtil.getFPGARevision(); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java index bcedd81fea7..18ee44e9751 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java @@ -59,12 +59,12 @@ public final class SensorUtil { */ public static void checkDigitalChannel(final int channel) { if (!DIOJNI.checkDIOChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested DIO channel is out of range. Minimum: 0, Maximum: ") - .append(kDigitalChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested DIO channel is out of range. Minimum: 0, Maximum: " + + kDigitalChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -76,12 +76,12 @@ public static void checkDigitalChannel(final int channel) { */ public static void checkRelayChannel(final int channel) { if (!RelayJNI.checkRelayChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested relay channel is out of range. Minimum: 0, Maximum: ") - .append(kRelayChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested relay channel is out of range. Minimum: 0, Maximum: " + + kRelayChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -93,12 +93,12 @@ public static void checkRelayChannel(final int channel) { */ public static void checkPWMChannel(final int channel) { if (!PWMJNI.checkPWMChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested PWM channel is out of range. Minimum: 0, Maximum: ") - .append(kPwmChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested PWM channel is out of range. Minimum: 0, Maximum: " + + kPwmChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -110,12 +110,12 @@ public static void checkPWMChannel(final int channel) { */ public static void checkAnalogInputChannel(final int channel) { if (!AnalogJNI.checkAnalogInputChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested analog input channel is out of range. Minimum: 0, Maximum: ") - .append(kAnalogInputChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested analog input channel is out of range. Minimum: 0, Maximum: " + + kAnalogInputChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -127,12 +127,12 @@ public static void checkAnalogInputChannel(final int channel) { */ public static void checkAnalogOutputChannel(final int channel) { if (!AnalogJNI.checkAnalogOutputChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested analog output channel is out of range. Minimum: 0, Maximum: ") - .append(kAnalogOutputChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested analog output channel is out of range. Minimum: 0, Maximum: " + + kAnalogOutputChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java index 1a05c8af4da..ada1839e5d4 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java @@ -216,7 +216,7 @@ public String readString() { */ public String readString(int count) { byte[] out = read(count); - return new String(out, 0, out.length, StandardCharsets.US_ASCII); + return new String(out, StandardCharsets.US_ASCII); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java index 2415079b243..a2252c610b7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java @@ -75,9 +75,7 @@ public void printEpochs(Consumer output) { StringBuilder sb = new StringBuilder(); m_lastEpochsPrintTime = now; m_epochs.forEach( - (key, value) -> { - sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6)); - }); + (key, value) -> sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6))); if (sb.length() > 0) { output.accept(sb.toString()); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java index f7bf85b6347..18d4b6463df 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java @@ -209,7 +209,7 @@ public void suppressTimeoutMessage(boolean suppress) { } private static void updateAlarm() { - if (m_watchdogs.size() == 0) { + if (m_watchdogs.isEmpty()) { NotifierJNI.cancelNotifierAlarm(m_notifier); } else { NotifierJNI.updateNotifierAlarm( @@ -233,7 +233,7 @@ private static void schedulerFunc() { m_queueMutex.lock(); try { - if (m_watchdogs.size() == 0) { + if (m_watchdogs.isEmpty()) { continue; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java index ac8ef1d3569..018c4d2ac24 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java @@ -50,7 +50,7 @@ public void close() { private static Runnable disabledListener; static { - SendableRegistry.setLiveWindowBuilderFactory(() -> new SendableBuilderImpl()); + SendableRegistry.setLiveWindowBuilderFactory(SendableBuilderImpl::new); enabledPub.set(false); } @@ -105,10 +105,7 @@ public static synchronized void setEnabled(boolean enabled) { } else { System.out.println("stopping live window mode."); SendableRegistry.foreachLiveWindow( - dataHandle, - cbdata -> { - ((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode(); - }); + dataHandle, cbdata -> ((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode()); if (disabledListener != null) { disabledListener.run(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java index 5265a8e4ad5..d9bd15264f8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java @@ -17,7 +17,8 @@ * 884 controllers also but if users experience issues such as asymmetric behavior around the * deadband or inability to saturate the controller in either direction, calibration is recommended. * The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics: - * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf + * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf * *
    *
  • 2.027ms = full "forward" diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java index 67133f6e9ca..4798ad34a4a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java @@ -236,12 +236,9 @@ public double getLeftVelocityMetersPerSecond() { * @return the drivetrain's left side current draw, in amps */ public double getLeftCurrentDrawAmps() { - var loadIleft = - m_motor.getCurrent( - getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters, - m_u.get(0, 0)) - * Math.signum(m_u.get(0, 0)); - return loadIleft; + return m_motor.getCurrent( + getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(0, 0)) + * Math.signum(m_u.get(0, 0)); } /** @@ -250,13 +247,9 @@ public double getLeftCurrentDrawAmps() { * @return the drivetrain's right side current draw, in amps */ public double getRightCurrentDrawAmps() { - var loadIright = - m_motor.getCurrent( - getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters, - m_u.get(1, 0)) - * Math.signum(m_u.get(1, 0)); - - return loadIright; + return m_motor.getCurrent( + getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(1, 0)) + * Math.signum(m_u.get(1, 0)); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java index 8a81f53247a..67ceda766e3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java @@ -135,7 +135,7 @@ public void setAxisType(int axis, int type) { */ public boolean getOutput(int outputNumber) { long outputs = getOutputs(); - return (outputs & (1 << (outputNumber - 1))) != 0; + return (outputs & (1L << (outputNumber - 1))) != 0; } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java index 9ffccde047b..0fecbb66918 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java @@ -10,6 +10,7 @@ import edu.wpi.first.math.trajectory.Trajectory; import edu.wpi.first.networktables.DoubleArrayEntry; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** Game field object on a Field2d. */ @@ -70,9 +71,7 @@ public synchronized Pose2d getPose() { */ public synchronized void setPoses(List poses) { m_poses.clear(); - for (Pose2d pose : poses) { - m_poses.add(pose); - } + m_poses.addAll(poses); updateEntry(); } @@ -83,9 +82,7 @@ public synchronized void setPoses(List poses) { */ public synchronized void setPoses(Pose2d... poses) { m_poses.clear(); - for (Pose2d pose : poses) { - m_poses.add(pose); - } + Collections.addAll(m_poses, poses); updateEntry(); } @@ -109,7 +106,7 @@ public synchronized void setTrajectory(Trajectory trajectory) { */ public synchronized List getPoses() { updateFromEntry(); - return new ArrayList(m_poses); + return new ArrayList<>(m_poses); } void updateEntry() { @@ -143,7 +140,7 @@ private synchronized void updateFromEntry() { return; } - double[] arr = m_entry.get((double[]) null); + double[] arr = m_entry.get(null); if (arr != null) { if ((arr.length % 3) != 0) { return; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java index 19a3fc107f8..9d0efa24f28 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java @@ -31,9 +31,9 @@ public void execute(Runnable task) { /** Runs all posted tasks. Called periodically from main thread. */ public void runListenerTasks() { // Locally copy tasks from internal list; minimizes blocking time - Collection tasks = new ArrayList<>(); + Collection tasks; synchronized (m_lock) { - tasks.addAll(m_tasks); + tasks = new ArrayList<>(m_tasks); m_tasks.clear(); } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java index c1c5f3c1286..920fb546e8c 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java @@ -144,11 +144,7 @@ void cleanup() { void disabledModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); @@ -231,11 +227,7 @@ void disabledModeTest() { void autonomousModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -320,11 +312,7 @@ void autonomousModeTest() { void teleopModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -411,11 +399,7 @@ void testModeTest(boolean isLW) { MockRobot robot = new MockRobot(); robot.enableLiveWindowInTest(isLW); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -531,11 +515,7 @@ void testModeTest(boolean isLW) { void modeChangeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); // Start in disabled @@ -655,17 +635,9 @@ void addPeriodicTest() { MockRobot robot = new MockRobot(); final AtomicInteger callbackCount = new AtomicInteger(0); - robot.addPeriodic( - () -> { - callbackCount.addAndGet(1); - }, - kPeriod / 2.0); - - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0); + + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); @@ -704,12 +676,7 @@ void addPeriodicWithOffsetTest() { MockRobot robot = new MockRobot(); final AtomicInteger callbackCount = new AtomicInteger(0); - robot.addPeriodic( - () -> { - callbackCount.addAndGet(1); - }, - kPeriod / 2.0, - kPeriod / 4.0); + robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0, kPeriod / 4.0); // Expirations in this test (ms) // @@ -720,11 +687,7 @@ void addPeriodicWithOffsetTest() { // p | 0.75p // 2p | 1.25p - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java index ee4860deb7f..5cff0d0dc9a 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java @@ -54,22 +54,10 @@ void scheduleTest() { // | RobotPeriodic() | 0 | 2 | // | Callback 1 | 2 | 0.5 | // | Callback 2 | 2.5 | 1 | - robot.schedule( - () -> { - callbackCount1.addAndGet(1); - }, - 0.0005); - robot.schedule( - () -> { - callbackCount2.addAndGet(1); - }, - 0.001); - - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + robot.schedule(() -> callbackCount1.addAndGet(1), 0.0005); + robot.schedule(() -> callbackCount2.addAndGet(1), 0.001); + + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java index c1676e0c36e..5e9e1229418 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java @@ -33,12 +33,7 @@ void cleanup() { void enableDisableTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { // Run 1 watchdog.enable(); SimHooks.stepTiming(0.2); @@ -71,12 +66,7 @@ void enableDisableTest() { void resetTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { watchdog.enable(); SimHooks.stepTiming(0.2); watchdog.reset(); @@ -92,12 +82,7 @@ void resetTest() { void setTimeoutTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 1.0, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(1.0, () -> watchdogCounter.addAndGet(1))) { watchdog.enable(); SimHooks.stepTiming(0.2); watchdog.setTimeout(0.2); @@ -137,12 +122,7 @@ void isExpiredTest() { void epochsTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { // Run 1 watchdog.enable(); watchdog.addEpoch("Epoch 1"); @@ -173,18 +153,8 @@ void multiWatchdogTest() { final AtomicInteger watchdogCounter1 = new AtomicInteger(0); final AtomicInteger watchdogCounter2 = new AtomicInteger(0); - try (Watchdog watchdog1 = - new Watchdog( - 0.2, - () -> { - watchdogCounter1.addAndGet(1); - }); - Watchdog watchdog2 = - new Watchdog( - 0.6, - () -> { - watchdogCounter2.addAndGet(1); - })) { + try (Watchdog watchdog1 = new Watchdog(0.2, () -> watchdogCounter1.addAndGet(1)); + Watchdog watchdog2 = new Watchdog(0.6, () -> watchdogCounter2.addAndGet(1))) { watchdog2.enable(); SimHooks.stepTiming(0.25); assertEquals(0, watchdogCounter1.get(), "Watchdog triggered early"); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java index 6283c68b40a..25b545b9713 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java @@ -136,7 +136,7 @@ void testDuplicateSelectTabs() { try (StringSubscriber subscriber = m_ntInstance .getStringTopic("/Shuffleboard/.metadata/Selected") - .subscribe("", PubSubOption.keepDuplicates(true)); ) { + .subscribe("", PubSubOption.keepDuplicates(true))) { listener = m_ntInstance.addListener( subscriber, diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java index 096f77e4c43..4ddadf1481d 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java @@ -79,7 +79,7 @@ void testSetData() { BufferCallback callback = new BufferCallback(); try (AddressableLED led = new AddressableLED(0); - CallbackStore cb = sim.registerDataCallback(callback); ) { + CallbackStore cb = sim.registerDataCallback(callback)) { assertFalse(sim.getRunning()); assertEquals(1, sim.getLength()); // Defaults to 1 led diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java index fbe3af0a43f..681e6b41c5e 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java @@ -63,7 +63,7 @@ void testPositionFeedbackControl() { try (var motor = new PWMVictorSPX(0); var encoder = new Encoder(0, 1); - var controller = new PIDController(0.04, 0.0, 0.001); ) { + var controller = new PIDController(0.04, 0.0, 0.001)) { var encoderSim = new EncoderSim(encoder); encoderSim.resetData(); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java index 9f29aaccdb4..8a0fc7cad43 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java @@ -25,7 +25,7 @@ void testInitialization() { BooleanCallback initializeCallback = new BooleanCallback(); DoubleCallback dutyCycleCallback = new DoubleCallback(); try (CallbackStore initCb = sim.registerInitializedCallback(initializeCallback, false); - CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false); ) { + CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false)) { final double kTestDutyCycle = 0.191; output.enablePWM(kTestDutyCycle); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java index 3918361fd4b..c7538cc5b5a 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java @@ -58,7 +58,7 @@ void testInitializationForwardOnly() { try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false); CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false); - Relay relay = new Relay(0, Relay.Direction.kForward); ) { + Relay relay = new Relay(0, Relay.Direction.kForward)) { assertTrue(sim.getInitializedForward()); assertFalse(sim.getInitializedReverse()); @@ -84,7 +84,7 @@ void testInitializationReverseOnly() { try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false); CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false); - Relay relay = new Relay(0, Relay.Direction.kReverse); ) { + Relay relay = new Relay(0, Relay.Direction.kReverse)) { assertFalse(sim.getInitializedForward()); assertTrue(sim.getInitializedReverse()); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java index 62a24d1d75a..89b4333e609 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java @@ -41,18 +41,10 @@ void testDeviceCreatedCallback() { SimDevice dev1 = SimDevice.create("testDC1")) { try (CallbackStore callback1 = SimDeviceSim.registerDeviceCreatedCallback( - "testDC", - (name, handle) -> { - callback1Counter.addAndGet(1); - }, - false); + "testDC", (name, handle) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = SimDeviceSim.registerDeviceCreatedCallback( - "testDC", - (name, handle) -> { - callback2Counter.addAndGet(1); - }, - true)) { + "testDC", (name, handle) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, @@ -82,11 +74,7 @@ void testDeviceFreedCallback() { SimDevice dev1 = SimDevice.create("testDF1"); try (CallbackStore callback = SimDeviceSim.registerDeviceFreedCallback( - "testDF", - (name, handle) -> { - counter.addAndGet(1); - }, - false)) { + "testDF", (name, handle) -> counter.addAndGet(1), false)) { assertEquals(0, counter.get(), "Callback called early"); dev1.close(); assertEquals(1, counter.get(), "Callback called either more than once or not at all"); @@ -108,16 +96,10 @@ void testValueCreatedCallback() { SimDeviceSim sim = new SimDeviceSim("testVM1"); try (CallbackStore callback1 = sim.registerValueCreatedCallback( - (name, handle, readonly, value) -> { - callback1Counter.addAndGet(1); - }, - false); + (name, handle, readonly, value) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = sim.registerValueCreatedCallback( - (name, handle, readonly, value) -> { - callback2Counter.addAndGet(1); - }, - true)) { + (name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, @@ -148,18 +130,10 @@ void testValueChangedCallback() { SimValue simVal = sim.getValue("v1"); try (CallbackStore callback1 = sim.registerValueChangedCallback( - simVal, - (name, handle, readonly, value) -> { - callback1Counter.addAndGet(1); - }, - false); + simVal, (name, handle, readonly, value) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = sim.registerValueChangedCallback( - simVal, - (name, handle, readonly, value) -> { - callback2Counter.addAndGet(1); - }, - true)) { + simVal, (name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java index 07f09af3cd2..d97d54c243c 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java @@ -75,7 +75,7 @@ void testChangeListener() { chooser.addOption(String.valueOf(i), i); } AtomicInteger currentVal = new AtomicInteger(); - chooser.onChange(val -> currentVal.set(val)); + chooser.onChange(currentVal::set); SmartDashboard.putData("changeListenerChooser", chooser); SmartDashboard.updateValues(); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java index 5ed9fda3d28..fa55f451d2a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java @@ -22,8 +22,8 @@ public ReplaceMeTrapezoidProfileCommand() { // Use current trajectory state here }, // Goal state - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Current state - () -> new TrapezoidProfile.State()); + TrapezoidProfile.State::new); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java index a73ea0beb56..91230c28674 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java @@ -32,7 +32,7 @@ public class Robot extends TimedRobot { @Override public void robotInit() { - var visionThread = new Thread(() -> apriltagVisionThreadProc()); + var visionThread = new Thread(this::apriltagVisionThreadProc); visionThread.setDaemon(true); visionThread.start(); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java index ab71ff442f3..ba2ed047102 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java @@ -78,7 +78,7 @@ private void configureButtonBindings() { // End at desired position in meters; implicitly starts at 0 () -> new TrapezoidProfile.State(3, 0), // Current position - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Require the drive m_robotDrive) .beforeStarting(m_robotDrive::resetEncoders) diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java index 5c107d23757..951cde30edf 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java @@ -29,7 +29,7 @@ public DriveDistanceProfiled(double meters, DriveSubsystem drive) { // End at desired position in meters; implicitly starts at 0 () -> new TrapezoidProfile.State(meters, 0), // Current position - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Require the drive drive); // Reset drive encoders since we're starting at 0 diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java index 69ec0235430..b51562fca87 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java @@ -50,16 +50,12 @@ private double getPressure() { */ public Command disableCompressorCommand() { return startEnd( - () -> { - // Disable closed-loop mode on the compressor. - m_compressor.disable(); - }, - () -> { - // Enable closed-loop mode based on the digital pressure switch connected to the - // PCM/PH. - // The switch is open when the pressure is over ~120 PSI. - m_compressor.enableDigital(); - }) + // Disable closed-loop mode on the compressor. + m_compressor::disable, + // Enable closed-loop mode based on the digital pressure switch connected to the + // PCM/PH. + // The switch is open when the pressure is over ~120 PSI. + m_compressor::enableDigital) .withName("Compressor Disabled"); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java index d6ae0487114..0b791c5120b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java @@ -53,33 +53,17 @@ public void robotInit() { tab.add("Compressor", m_compressor); // Also publish some raw data - tab.addDouble( - "PH Pressure [PSI]", - () -> { - // Get the pressure (in PSI) from the analog sensor connected to the PH. - // This function is supported only on the PH! - // On a PCM, this function will return 0. - return m_compressor.getPressure(); - }); - tab.addDouble( - "Compressor Current", - () -> { - // Get compressor current draw. - return m_compressor.getCurrent(); - }); - tab.addBoolean( - "Compressor Active", - () -> { - // Get whether the compressor is active. - return m_compressor.isEnabled(); - }); - tab.addBoolean( - "Pressure Switch", - () -> { - // Get the digital pressure switch connected to the PCM/PH. - // The switch is open when the pressure is over ~120 PSI. - return m_compressor.getPressureSwitchValue(); - }); + // Get the pressure (in PSI) from the analog sensor connected to the PH. + // This function is supported only on the PH! + // On a PCM, this function will return 0. + tab.addDouble("PH Pressure [PSI]", m_compressor::getPressure); + // Get compressor current draw. + tab.addDouble("Compressor Current", m_compressor::getCurrent); + // Get whether the compressor is active. + tab.addBoolean("Compressor Active", m_compressor::isEnabled); + // Get the digital pressure switch connected to the PCM/PH. + // The switch is open when the pressure is over ~120 PSI. + tab.addBoolean("Pressure Switch", m_compressor::getPressureSwitchValue); } @SuppressWarnings("PMD.UnconditionalIfStatement") diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java index a51d505a988..e84a6079a6a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java @@ -44,7 +44,7 @@ public boolean isDeployed() { } @Override - public void close() throws Exception { + public void close() { m_piston.close(); m_motor.close(); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java index bdc467578f2..22267b13f82 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java @@ -4,11 +4,11 @@ package edu.wpi.first.wpilibj; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java index e6585e4f8ea..eaf975dce81 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java @@ -7,8 +7,8 @@ import static org.junit.Assert.assertEquals; import edu.wpi.first.wpilibj.test.AbstractComsSetup; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.BeforeClass; import org.junit.Test; @@ -38,7 +38,7 @@ public static void waitASecond() { /** Test with all valid ranges to make sure unpacking is always done correctly. */ @Parameters public static Collection generateData() { - return Arrays.asList( + return List.of( new BuiltInAccelerometer.Range[][] { {BuiltInAccelerometer.Range.k2G}, {BuiltInAccelerometer.Range.k4G}, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java index 72c2c55aade..078ef5aa693 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java @@ -14,8 +14,8 @@ import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -56,7 +56,7 @@ public MotorEncoderTest(MotorEncoderFixture mef) { @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList( + return List.of( new MotorEncoderFixture[][] { {TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()} }); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java index 769fa7fe98a..4ec5a722481 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java @@ -10,8 +10,8 @@ import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.AfterClass; import org.junit.Before; @@ -44,7 +44,7 @@ public MotorInvertingTest(MotorEncoderFixture afixture) { @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList( + return List.of( new MotorEncoderFixture[][] { {TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()} }); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java index f2bc522e388..d668d16d5a0 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java @@ -4,17 +4,17 @@ package edu.wpi.first.wpilibj; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import edu.wpi.first.hal.can.CANMessageNotFoundException; import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -65,7 +65,7 @@ public PDPTest(MotorEncoderFixture mef, Double expectedCurrentDraw) { @Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}") public static Collection generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList(new Object[][] {{TestBench.getTalonPair(), 0.0}}); + return List.of(new Object[][] {{TestBench.getTalonPair(), 0.0}}); } @After diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java index b5e0fc8fd9b..f2cd12fd0ad 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java @@ -16,8 +16,8 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -72,13 +72,13 @@ public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef) { @Parameters public static Collection generateData() { // logger.fine("Loading the MotorList"); - Collection data = new ArrayList(); + Collection data = new ArrayList<>(); double kp = 0.001; double ki = 0.0005; double kd = 0.0; for (int i = 0; i < 1; i++) { data.addAll( - Arrays.asList( + List.of( new Object[][] { {kp, ki, kd, TestBench.getTalonPair()}, {kp, ki, kd, TestBench.getVictorPair()}, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java index 056ff5ff1c7..4a912931bde 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java @@ -31,7 +31,7 @@ public abstract class AbstractComsSetup { // We have no way to stop the MockDS, so its thread is daemon. private static MockDS ds; - /** + /* * This sets up the network communications library to enable the driver station. After starting * network coms, it will loop until the driver station returns that the robot is enabled, to * ensure that tests will be able to run on the hardware. diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java index ff0542c7b2c..b8adb17b4e2 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java @@ -34,15 +34,11 @@ public abstract class AbstractTestSuite { */ protected List> getAnnotatedTestClasses() { SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class); - List> classes = new ArrayList<>(); if (annotation == null) { throw new RuntimeException( String.format("class '%s' must have a SuiteClasses annotation", getClass().getName())); } - for (Class c : annotation.value()) { - classes.add(c); - } - return classes; + return List.of(annotation.value()); } private boolean areAnySuperClassesOfTypeAbstractTestSuite(Class check) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java index 07d0af72f35..31da1036fad 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java @@ -24,9 +24,8 @@ public class AntJunitLauncher { */ public static void main(String... args) { if (args.length == 0) { - String path = + String pathToReports = String.format("%s/%s", System.getProperty("user.dir"), "/testResults/AntReports"); - String pathToReports = path; Project project = new Project(); try { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java index 258d640af99..508c432cbfc 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java @@ -20,7 +20,6 @@ import edu.wpi.first.wpilibj.motorcontrol.Victor; import java.io.PrintStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -59,7 +58,7 @@ public final class TestBench { * The single constructor for the TestBench. This method is private in order to prevent multiple * TestBench objects from being allocated. */ - protected TestBench() {} + private TestBench() {} /** * Constructs a new set of objects representing a connected set of Talon controlled Motors and an @@ -68,7 +67,7 @@ protected TestBench() {} * @return a freshly allocated Talon, Encoder pair */ public static MotorEncoderFixture getTalonPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Talon giveMotorController() { return new Talon(kTalonChannel); @@ -98,7 +97,7 @@ public int getPDPChannel() { * @return a freshly allocated Victor, Encoder pair */ public static MotorEncoderFixture getVictorPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Victor giveMotorController() { return new Victor(kVictorChannel); @@ -128,7 +127,7 @@ public int getPDPChannel() { * @return a freshly allocated Jaguar, Encoder pair */ public static MotorEncoderFixture getJaguarPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Jaguar giveMotorController() { return new Jaguar(kJaguarChannel); @@ -190,9 +189,9 @@ public static DIOCrossConnectFixture getDIOCrossConnectFixture(int inputPort, in /** Gets two lists of possible DIO pairs for the two pairs. */ private static List> getDIOCrossConnect() { - List> pairs = new ArrayList>(); + List> pairs = new ArrayList<>(); List setA = - Arrays.asList( + List.of( new Integer[][] { {DIOCrossConnectA1, DIOCrossConnectA2}, {DIOCrossConnectA2, DIOCrossConnectA1} @@ -200,7 +199,7 @@ private static List> getDIOCrossConnect() { pairs.add(setA); List setB = - Arrays.asList( + List.of( new Integer[][] { {DIOCrossConnectB1, DIOCrossConnectB2}, {DIOCrossConnectB2, DIOCrossConnectB1} @@ -252,7 +251,7 @@ protected DigitalInput giveInputOne() { * @return pairs of DIOCrossConnectFixtures */ public static Collection getDIOCrossConnectCollection() { - Collection pairs = new ArrayList(); + Collection pairs = new ArrayList<>(); for (Collection collection : getDIOCrossConnect()) { pairs.addAll(collection); } @@ -267,7 +266,7 @@ public static Collection getDIOCrossConnectCollection() { */ private static Collection getPairArray( List listA, List listB, boolean flip) { - Collection encoderPortPairs = new ArrayList(); + Collection encoderPortPairs = new ArrayList<>(); for (Integer[] portPairsA : listA) { Integer[] inputs = new Integer[5]; inputs[0] = portPairsA[0]; // InputA @@ -279,7 +278,7 @@ private static Collection getPairArray( inputs[4] = flip ? 0 : 1; // The flip bit } - ArrayList construtorInput = new ArrayList(); + ArrayList construtorInput = new ArrayList<>(); construtorInput.add(inputs); inputs = inputs.clone(); @@ -300,7 +299,7 @@ private static Collection getPairArray( * @return A collection of different input pairs to use for the encoder */ public static Collection getEncoderDIOCrossConnectCollection() { - Collection encoderPortPairs = new ArrayList(); + Collection encoderPortPairs = new ArrayList<>(); assert getDIOCrossConnect().size() == 2; encoderPortPairs.addAll( getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), false)); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java index 880a97c011e..befc0668bbd 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.LogManager; @@ -77,40 +76,36 @@ public TestSuite() {} /** Displays a help message for the user when they use the --help flag at runtime. */ protected static void displayHelp() { - StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); - helpMessage.append( - "\t" + String helpMessage = + "Test Parameters help: \n" + + "\t" + QUICK_TEST_FLAG + " will cause the quick test to be run. Ignores other flags except for " + METHOD_REPEAT_FILTER - + "\n"); - helpMessage.append( - "\t" + + "\n" + + "\t" + CLASS_NAME_FILTER + " will use the supplied regex text to search for suite/test class names " - + "matching the regex and run them.\n"); - helpMessage.append( - "\t" + + "matching the regex and run them.\n" + + "\t" + METHOD_NAME_FILTER + " will use the supplied regex text to search for test methods (excluding methods " + "with the @Ignore annotation) and run only those methods. Can be paired with " + METHOD_REPEAT_FILTER + " to " - + "repeat the selected tests multiple times.\n"); - helpMessage.append( - "\t" + + "repeat the selected tests multiple times.\n" + + "\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either " + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER - + " and run them the given number of times.\n"); - helpMessage.append( - "[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This " + + " and run them the given number of times.\n" + + "[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This " + "documentation can be found at " - + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); - helpMessage.append("\n"); - helpMessage.append("\n"); + + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n" + + "\n" + + "\n"; TestBench.out().println(helpMessage); } @@ -123,7 +118,7 @@ protected static void displayInvalidUsage(String message, String... args) { StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); invalidMessage.append("Params received: "); for (String a : args) { - invalidMessage.append(a + " "); + invalidMessage.append(a).append(" "); } invalidMessage.append("\n"); invalidMessage.append( @@ -145,9 +140,9 @@ protected static void printLoadedTests(final Class... classes) { for (Class c : classes) { if (c.getPackage().equals(packagE)) { packagE = c.getPackage(); - loadedTestsMessage.append(packagE.getName() + "\n"); + loadedTestsMessage.append(packagE.getName()).append("\n"); } - loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); + loadedTestsMessage.append("\t").append(c.getSimpleName()).append("\n"); } TestBench.out().println(loadedTestsMessage); } @@ -193,7 +188,7 @@ protected static Result parseArgsRunAndGetResult(final String[] args) { } } - ArrayList argsParsed = new ArrayList(Arrays.asList(args)); + ArrayList argsParsed = new ArrayList<>(List.of(args)); if (argsParsed.contains(HELP_FLAG)) { // If the user inputs the help flag then return the help message and exit // without running any tests @@ -257,7 +252,7 @@ void addResult(Result result) { // If a specific method has been requested if (methodFilter) { List pairs = (new TestSuite()).getMethodMatching(methodRegex); - if (pairs.size() == 0) { + if (pairs.isEmpty()) { displayInvalidUsage( "None of the arguments passed to the method name filter matched.", args); return null; @@ -292,7 +287,7 @@ void addResult(Result result) { // If a specific class has been requested if (classFilter) { List> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex); - if (testClasses.size() == 0) { + if (testClasses.isEmpty()) { displayInvalidUsage("None of the arguments passed to the filter matched.", args); return null; } diff --git a/wpimath/src/main/java/edu/wpi/first/math/Matrix.java b/wpimath/src/main/java/edu/wpi/first/math/Matrix.java index 8ac8d137e04..80700d40276 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/Matrix.java +++ b/wpimath/src/main/java/edu/wpi/first/math/Matrix.java @@ -288,7 +288,7 @@ public final Matrix plus(Matrix value) { * @return The resultant matrix. */ public Matrix div(int value) { - return new Matrix<>(this.m_storage.divide((double) value)); + return new Matrix<>(this.m_storage.divide(value)); } /** @@ -488,7 +488,7 @@ public final Matrix elementPower(double b) { * @return The element by element power of "this" and b. */ public final Matrix elementPower(int b) { - return new Matrix<>(this.m_storage.elementPower((double) b)); + return new Matrix<>(this.m_storage.elementPower(b)); } /** @@ -545,7 +545,7 @@ public final Matrix block( */ public final Matrix block( int height, int width, int startingRow, int startingCol) { - return new Matrix( + return new Matrix<>( this.m_storage.extractMatrix( startingRow, startingRow + height, startingCol, startingCol + width)); } @@ -607,8 +607,7 @@ public Matrix lltDecompose(boolean lowerTriangular) { return new Matrix<>(new SimpleMatrix(temp.getNumRows(), temp.getNumCols())); } - throw new RuntimeException( - "Cholesky decomposition failed! Input matrix:\n" + m_storage.toString()); + throw new RuntimeException("Cholesky decomposition failed! Input matrix:\n" + m_storage); } return new Matrix<>(SimpleMatrix.wrap(chol.getT(null))); diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java index a2a59448c42..c406203b20f 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java @@ -16,9 +16,8 @@ * Constructs a control-affine plant inversion model-based feedforward from given model dynamics. * *

    If given the vector valued function as f(x, u) where x is the state vector and u is the input - * vector, the B matrix(continuous input matrix) is calculated through a {@link - * edu.wpi.first.math.system.NumericalJacobian}. In this case f has to be control-affine (of the - * form f(x) + Bu). + * vector, the B matrix(continuous input matrix) is calculated through a {@link NumericalJacobian}. + * In this case f has to be control-affine (of the form f(x) + Bu). * *

    The feedforward is calculated as u_ff = B+ (rDot - f(x)), where * B+ is the pseudoinverse of B. @@ -26,8 +25,8 @@ *

    This feedforward does not account for a dynamic B matrix, B is either determined or supplied * when the feedforward is created and remains constant. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class ControlAffinePlantInversionFeedforward { /** The current reference state. */ diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java index 7aa4cfa9133..6fdf1f319fd 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java @@ -17,8 +17,8 @@ * system and makes it behave like some other system. This can be used to make a drivetrain more * controllable during teleop driving by making it behave like a slower or more benign drivetrain. * - *

    For more on the underlying math, read appendix B.3 in - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read appendix B.3 in https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class ImplicitModelFollower { // Computed controller output diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java index fa287831bc0..116513eb7f1 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java @@ -65,8 +65,8 @@ private enum State { /** * Constructs a linear time-varying differential drive controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param plant The differential drive velocity plant. diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java index c4e7358c9f7..c3c54f32129 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java @@ -80,8 +80,8 @@ public LTVUnicycleController(double dt, double maxVelocity) { /** * Constructs a linear time-varying unicycle controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param qelems The maximum desired error tolerance for each state. @@ -95,8 +95,8 @@ public LTVUnicycleController(Vector qelems, Vector relems, double dt) { /** * Constructs a linear time-varying unicycle controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param qelems The maximum desired error tolerance for each state. diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java index b0f23a8dcc7..c6ec51fed1e 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java @@ -17,8 +17,8 @@ *

    The feedforward is calculated as u_ff = B+ (r_k+1 - A r_k) , * where B+ is the pseudoinverse of B. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class LinearPlantInversionFeedforward< States extends Num, Inputs extends Num, Outputs extends Num> { diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java index 658be69317a..e3aa90aa4b7 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java @@ -19,8 +19,8 @@ * Contains the controller coefficients and logic for a linear-quadratic regulator (LQR). LQRs use * the control law u = K(r - x). * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class LinearQuadraticRegulator { /** The current reference state. */ @@ -35,8 +35,8 @@ public class LinearQuadraticRegulatorSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param plant The plant being controlled. @@ -61,8 +61,8 @@ public LinearQuadraticRegulator( /** * Constructs a controller with the given coefficients and plant. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param A Continuous system matrix of the plant being controlled. @@ -107,14 +107,12 @@ public LinearQuadraticRegulator( var discB = discABPair.getSecond(); if (!StateSpaceUtil.isStabilizable(discA, discB)) { - var builder = new StringBuilder("The system passed to the LQR is uncontrollable!\n\nA =\n"); - builder - .append(discA.getStorage().toString()) - .append("\nB =\n") - .append(discB.getStorage().toString()) - .append('\n'); - - var msg = builder.toString(); + var msg = + "The system passed to the LQR is uncontrollable!\n\nA =\n" + + discA.getStorage().toString() + + "\nB =\n" + + discB.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } @@ -258,8 +256,9 @@ public Matrix calculate(Matrix x, Matrix nex * are time-delayed too long, the LQR may be unstable. However, if we know the amount of delay, we * can compute the control based on where the system will be after the time delay. * - *

    See https://file.tavsys.net/control/controls-engineering-in-frc.pdf appendix C.4 for a - * derivation. + *

    See https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * appendix C.4 for a derivation. * * @param plant The plant being controlled. * @param dtSeconds Discretization timestep in seconds. diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java index 59323b21d65..f3c25332edd 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java @@ -30,9 +30,9 @@ * error covariance by linearizing the models around the state estimate, then applying the linear * Kalman filter equations. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". */ public class ExtendedKalmanFilter implements KalmanTypeFilter { @@ -59,8 +59,8 @@ public class ExtendedKalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states a Nat representing the number of states. @@ -97,8 +97,8 @@ public ExtendedKalmanFilter( /** * Constructs an extended Kalman filter. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states a Nat representing the number of states. diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java index 5cf9132cd0e..d74db4e4d99 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java @@ -25,9 +25,9 @@ * amount of the difference between the actual measurements and the measurements predicted by the * model. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". */ public class KalmanFilter implements KalmanTypeFilter { @@ -45,8 +45,8 @@ public class KalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the states of the system. @@ -82,15 +82,12 @@ public KalmanFilter( var C = plant.getC(); if (!StateSpaceUtil.isDetectable(discA, C)) { - var builder = - new StringBuilder("The system passed to the Kalman filter is unobservable!\n\nA =\n"); - builder - .append(discA.getStorage().toString()) - .append("\nC =\n") - .append(C.getStorage().toString()) - .append('\n'); - - var msg = builder.toString(); + var msg = + "The system passed to the Kalman filter is unobservable!\n\nA =\n" + + discA.getStorage().toString() + + "\nC =\n" + + C.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java index 93ca8636636..bf31ae7293b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java @@ -28,9 +28,9 @@ *

    This class assumes predict() and correct() are called in pairs, so the Kalman gain converges * to a steady-state value. If they aren't, use {@link KalmanFilter} instead. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". */ public class SteadyStateKalmanFilter { private final Nat m_states; @@ -46,8 +46,8 @@ public class SteadyStateKalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the states of the system. @@ -81,15 +81,12 @@ public SteadyStateKalmanFilter( var C = plant.getC(); if (!StateSpaceUtil.isDetectable(discA, C)) { - var builder = - new StringBuilder("The system passed to the Kalman filter is unobservable!\n\nA =\n"); - builder - .append(discA.getStorage().toString()) - .append("\nC =\n") - .append(C.getStorage().toString()) - .append('\n'); - - var msg = builder.toString(); + var msg = + "The system passed to the Kalman filter is unobservable!\n\nA =\n" + + discA.getStorage().toString() + + "\nC =\n" + + C.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java index a5de856feb0..2c1e1e6efad 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java @@ -31,12 +31,13 @@ *

    An unscented Kalman filter uses nonlinear state and measurement models. It propagates the * error covariance using sigma points chosen to approximate the true probability distribution. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". * *

    This class implements a square-root-form unscented Kalman filter (SR-UKF). For more - * information about the SR-UKF, see https://www.researchgate.net/publication/3908304. + * information about the SR-UKF, see https://www.researchgate.net/publication/3908304. */ public class UnscentedKalmanFilter implements KalmanTypeFilter { @@ -64,8 +65,8 @@ public class UnscentedKalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the number of states. @@ -104,8 +105,8 @@ public UnscentedKalmanFilter( * custom functions for arithmetic can be useful if you have angles in the state or measurements, * because they allow you to correctly account for the modular nature of angle arithmetic. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the number of states. @@ -206,7 +207,7 @@ Pair, Matrix> squareRootUnscentedTransform( var qrStorage = Sbar.transpose().getStorage(); if (!qr.decompose(qrStorage.getDDRM())) { - throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage.toString()); + throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage); } Matrix newS = new Matrix<>(new SimpleMatrix(qr.getR(null, true))); diff --git a/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java b/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java index 94175a6bdd2..7a568c86134 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java @@ -35,9 +35,13 @@ * PID controller out of this class! * *

    For more on filters, we highly recommend the following articles:
    - * https://en.wikipedia.org/wiki/Linear_filter
    - * https://en.wikipedia.org/wiki/Iir_filter
    - * https://en.wikipedia.org/wiki/Fir_filter
    + * https://en.wikipedia.org/wiki/Linear_filter + *
    + * https://en.wikipedia.org/wiki/Iir_filter + *
    + * https://en.wikipedia.org/wiki/Fir_filter + *
    * *

    Note 1: calculate() should be called by the user on a known, regular period. You can use a * Notifier for this or do it "inline" with code in a periodic function. diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java index b4f93c038f8..25473c0927b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java @@ -117,19 +117,15 @@ public Rotation3d(Matrix rotationMatrix) { // Require that the rotation matrix is special orthogonal. This is true if // the matrix is orthogonal (RRᵀ = I) and normalized (determinant is 1). if (R.times(R.transpose()).minus(Matrix.eye(Nat.N3())).normF() > 1e-9) { - var builder = new StringBuilder("Rotation matrix isn't orthogonal\n\nR =\n"); - builder.append(R.getStorage().toString()).append('\n'); - - var msg = builder.toString(); + var msg = "Rotation matrix isn't orthogonal\n\nR =\n" + R.getStorage().toString() + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } if (Math.abs(R.det() - 1.0) > 1e-9) { - var builder = - new StringBuilder("Rotation matrix is orthogonal but not special orthogonal\n\nR =\n"); - builder.append(R.getStorage().toString()).append('\n'); - - var msg = builder.toString(); + var msg = + "Rotation matrix is orthogonal but not special orthogonal\n\nR =\n" + + R.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } @@ -191,7 +187,6 @@ public Rotation3d(Vector initial, Vector last) { // If the dot product is 1, the two vectors point in the same direction so // there's no rotation. The default initialization of m_q will work. m_q = new Quaternion(); - return; } else if (dotNorm < -1.0 + 1E-9) { // If the dot product is -1, the two vectors point in opposite directions // so a 180 degree rotation is required. Any orthogonal vector can be used diff --git a/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java b/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java index 7eea7024a95..1b885fb7cfb 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java +++ b/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java @@ -87,7 +87,7 @@ public Pose2d[] solve(Pose2d[] poses, int iterations) { * array. */ private Vector neighbor(Vector state) { - var proposedState = new Vector(state); + var proposedState = new Vector<>(state); int rangeStart = (int) (Math.random() * (state.getNumRows() - 1)); int rangeEnd = (int) (Math.random() * (state.getNumRows() - 1)); diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java index 02b1da0aef2..255732415b4 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java @@ -25,8 +25,8 @@ * of the controller (U is an output because that's what goes to the motors and Y is an input * because that's what comes back from the sensors). * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class LinearSystemLoop { private final LinearQuadraticRegulator m_controller; diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java index cc0087c6dbb..1f2c9cfb597 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java @@ -38,7 +38,7 @@ MinMax getMinMaxAccelerationMetersPerSecondSq( /** Represents a minimum and maximum acceleration. */ class MinMax { public double minAccelerationMetersPerSecondSq = -Double.MAX_VALUE; - public double maxAccelerationMetersPerSecondSq = +Double.MAX_VALUE; + public double maxAccelerationMetersPerSecondSq = Double.MAX_VALUE; /** * Constructs a MinMax. diff --git a/wpimath/src/test/java/edu/wpi/first/math/DARETest.java b/wpimath/src/test/java/edu/wpi/first/math/DARETest.java index 0d697bdd27d..50ff38a940b 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/DARETest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/DARETest.java @@ -42,8 +42,7 @@ void assertDARESolution( .times((B.transpose().times(X).times(B).plus(R)).inv()) .times(B.transpose().times(X).times(A))) .plus(Q); - assertMatrixEqual( - new Matrix(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y); + assertMatrixEqual(new Matrix<>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y); } void assertDARESolution( @@ -63,8 +62,7 @@ void assertDARESolution( .times((B.transpose().times(X).times(B).plus(R)).inv()) .times(B.transpose().times(X).times(A).plus(N.transpose()))) .plus(Q); - assertMatrixEqual( - new Matrix(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y); + assertMatrixEqual(new Matrix<>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y); } @Test diff --git a/wpimath/src/test/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforwardTest.java b/wpimath/src/test/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforwardTest.java index 60300fb838b..b5e808a5ef2 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforwardTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforwardTest.java @@ -18,8 +18,7 @@ class ControlAffinePlantInversionFeedforwardTest { @Test void testCalculate() { ControlAffinePlantInversionFeedforward feedforward = - new ControlAffinePlantInversionFeedforward( - Nat.N2(), Nat.N1(), this::getDynamics, 0.02); + new ControlAffinePlantInversionFeedforward<>(Nat.N2(), Nat.N1(), this::getDynamics, 0.02); assertEquals( 48.0, feedforward.calculate(VecBuilder.fill(2, 2), VecBuilder.fill(3, 3)).get(0, 0), 1e-6); @@ -28,8 +27,7 @@ void testCalculate() { @Test void testCalculateState() { ControlAffinePlantInversionFeedforward feedforward = - new ControlAffinePlantInversionFeedforward( - Nat.N2(), Nat.N1(), this::getDynamics, 0.02); + new ControlAffinePlantInversionFeedforward<>(Nat.N2(), Nat.N1(), this::getDynamics, 0.02); assertEquals( 48.0, feedforward.calculate(VecBuilder.fill(2, 2), VecBuilder.fill(3, 3)).get(0, 0), 1e-6); diff --git a/wpimath/src/test/java/edu/wpi/first/math/controller/ImplicitModelFollowerTest.java b/wpimath/src/test/java/edu/wpi/first/math/controller/ImplicitModelFollowerTest.java index cfcc71d1ee2..90f21275592 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/controller/ImplicitModelFollowerTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/controller/ImplicitModelFollowerTest.java @@ -21,7 +21,7 @@ void testSameModel() { var plant = LinearSystemId.identifyDrivetrainSystem(1.0, 1.0, 1.0, 1.0); - var imf = new ImplicitModelFollower(plant, plant); + var imf = new ImplicitModelFollower<>(plant, plant); Matrix x = VecBuilder.fill(0.0, 0.0); Matrix xImf = VecBuilder.fill(0.0, 0.0); @@ -66,7 +66,7 @@ void testSlowerRefModel() { // Linear acceleration is slower, but angular acceleration is the same var plantRef = LinearSystemId.identifyDrivetrainSystem(1.0, 2.0, 1.0, 1.0); - var imf = new ImplicitModelFollower(plant, plantRef); + var imf = new ImplicitModelFollower<>(plant, plantRef); Matrix x = VecBuilder.fill(0.0, 0.0); Matrix xImf = VecBuilder.fill(0.0, 0.0); diff --git a/wpimath/src/test/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforwardTest.java b/wpimath/src/test/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforwardTest.java index eb8d36a503b..8901330d138 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforwardTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforwardTest.java @@ -21,7 +21,7 @@ void testCalculate() { Matrix B = VecBuilder.fill(0, 1); LinearPlantInversionFeedforward feedforward = - new LinearPlantInversionFeedforward(A, B, 0.02); + new LinearPlantInversionFeedforward<>(A, B, 0.02); assertEquals( 47.502599, diff --git a/wpimath/src/test/java/edu/wpi/first/math/estimator/DifferentialDrivePoseEstimatorTest.java b/wpimath/src/test/java/edu/wpi/first/math/estimator/DifferentialDrivePoseEstimatorTest.java index e0e202f98c3..08c5a156cf1 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/estimator/DifferentialDrivePoseEstimatorTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/estimator/DifferentialDrivePoseEstimatorTest.java @@ -5,6 +5,7 @@ package edu.wpi.first.math.estimator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.geometry.Pose2d; @@ -254,7 +255,7 @@ void testSimultaneousVisionMeasurements() { "Estimator converged to one vision measurement: " + estimator.getEstimatedPosition().toString() + " -> " - + measurement.toString(); + + measurement; var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX()); var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY()); @@ -263,7 +264,7 @@ void testSimultaneousVisionMeasurements() { measurement.getRotation().getDegrees() - estimator.getEstimatedPosition().getRotation().getDegrees()); - assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog); + assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog); } } diff --git a/wpimath/src/test/java/edu/wpi/first/math/estimator/ExtendedKalmanFilterTest.java b/wpimath/src/test/java/edu/wpi/first/math/estimator/ExtendedKalmanFilterTest.java index 112ef902154..8204fec0844 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/estimator/ExtendedKalmanFilterTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/estimator/ExtendedKalmanFilterTest.java @@ -22,7 +22,6 @@ import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.trajectory.TrajectoryConfig; import edu.wpi.first.math.trajectory.TrajectoryGenerator; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -114,7 +113,7 @@ void testConvergence() { dtSeconds); List waypoints = - Arrays.asList( + List.of( new Pose2d(2.75, 22.521, new Rotation2d()), new Pose2d(24.73, 19.68, Rotation2d.fromDegrees(5.846))); var trajectory = diff --git a/wpimath/src/test/java/edu/wpi/first/math/estimator/MecanumDrivePoseEstimatorTest.java b/wpimath/src/test/java/edu/wpi/first/math/estimator/MecanumDrivePoseEstimatorTest.java index d844c5d86ae..ea08a5f1d90 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/estimator/MecanumDrivePoseEstimatorTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/estimator/MecanumDrivePoseEstimatorTest.java @@ -5,6 +5,7 @@ package edu.wpi.first.math.estimator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.geometry.Pose2d; @@ -267,7 +268,7 @@ void testSimultaneousVisionMeasurements() { "Estimator converged to one vision measurement: " + estimator.getEstimatedPosition().toString() + " -> " - + measurement.toString(); + + measurement; var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX()); var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY()); @@ -276,7 +277,7 @@ void testSimultaneousVisionMeasurements() { measurement.getRotation().getDegrees() - estimator.getEstimatedPosition().getRotation().getDegrees()); - assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog); + assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog); } } diff --git a/wpimath/src/test/java/edu/wpi/first/math/estimator/SwerveDrivePoseEstimatorTest.java b/wpimath/src/test/java/edu/wpi/first/math/estimator/SwerveDrivePoseEstimatorTest.java index 9fcd8525db8..f827a102527 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/estimator/SwerveDrivePoseEstimatorTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/estimator/SwerveDrivePoseEstimatorTest.java @@ -5,6 +5,7 @@ package edu.wpi.first.math.estimator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.geometry.Pose2d; @@ -288,7 +289,7 @@ void testSimultaneousVisionMeasurements() { "Estimator converged to one vision measurement: " + estimator.getEstimatedPosition().toString() + " -> " - + measurement.toString(); + + measurement; var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX()); var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY()); @@ -297,7 +298,7 @@ void testSimultaneousVisionMeasurements() { measurement.getRotation().getDegrees() - estimator.getEstimatedPosition().getRotation().getDegrees()); - assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog); + assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog); } } diff --git a/wpimath/src/test/java/edu/wpi/first/math/estimator/UnscentedKalmanFilterTest.java b/wpimath/src/test/java/edu/wpi/first/math/estimator/UnscentedKalmanFilterTest.java index 7faa82a3ead..bcc33aec678 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/estimator/UnscentedKalmanFilterTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/estimator/UnscentedKalmanFilterTest.java @@ -26,7 +26,6 @@ import edu.wpi.first.math.system.plant.LinearSystemId; import edu.wpi.first.math.trajectory.TrajectoryConfig; import edu.wpi.first.math.trajectory.TrajectoryGenerator; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -137,7 +136,7 @@ void testConvergence() { dtSeconds); List waypoints = - Arrays.asList( + List.of( new Pose2d(2.75, 22.521, new Rotation2d()), new Pose2d(24.73, 19.68, Rotation2d.fromDegrees(5.846))); var trajectory = diff --git a/wpimath/src/test/java/edu/wpi/first/math/filter/LinearFilterTest.java b/wpimath/src/test/java/edu/wpi/first/math/filter/LinearFilterTest.java index ec43cd578ae..72ea1743f14 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/filter/LinearFilterTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/filter/LinearFilterTest.java @@ -129,9 +129,9 @@ void centralFiniteDifferenceTest() { 1, 3, // f(x) = sin(x) - (double x) -> Math.sin(x), + Math::sin, // df/dx = cos(x) - (double x) -> Math.cos(x), + Math::cos, h, -20.0, 20.0); @@ -140,7 +140,7 @@ void centralFiniteDifferenceTest() { 1, 3, // f(x) = ln(x) - (double x) -> Math.log(x), + Math::log, // df/dx = 1/x (double x) -> 1.0 / x, h, @@ -162,7 +162,7 @@ void centralFiniteDifferenceTest() { 2, 5, // f(x) = sin(x) - (double x) -> Math.sin(x), + Math::sin, // d²f/dx² = -sin(x) (double x) -> -Math.sin(x), h, @@ -173,7 +173,7 @@ void centralFiniteDifferenceTest() { 2, 5, // f(x) = ln(x) - (double x) -> Math.log(x), + Math::log, // d²f/dx² = -1/x² (double x) -> -1.0 / (x * x), h, @@ -201,9 +201,9 @@ void backwardFiniteDifferenceTest() { 1, 2, // f(x) = sin(x) - (double x) -> Math.sin(x), + Math::sin, // df/dx = cos(x) - (double x) -> Math.cos(x), + Math::cos, h, -20.0, 20.0); @@ -212,7 +212,7 @@ void backwardFiniteDifferenceTest() { 1, 2, // f(x) = ln(x) - (double x) -> Math.log(x), + Math::log, // df/dx = 1/x (double x) -> 1.0 / x, h, @@ -234,7 +234,7 @@ void backwardFiniteDifferenceTest() { 2, 4, // f(x) = sin(x) - (double x) -> Math.sin(x), + Math::sin, // d²f/dx² = -sin(x) (double x) -> -Math.sin(x), h, @@ -245,7 +245,7 @@ void backwardFiniteDifferenceTest() { 2, 4, // f(x) = ln(x) - (double x) -> Math.log(x), + Math::log, // d²f/dx² = -1/x² (double x) -> -1.0 / (x * x), h, diff --git a/wpimath/src/test/java/edu/wpi/first/math/geometry/Pose3dTest.java b/wpimath/src/test/java/edu/wpi/first/math/geometry/Pose3dTest.java index ee1d98c8c19..3ef8a483563 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/geometry/Pose3dTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/geometry/Pose3dTest.java @@ -11,7 +11,7 @@ import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.util.Units; -import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; class Pose3dTest { @@ -194,7 +194,7 @@ void testToPose2d() { @Test void testComplexTwists() { var initial_poses = - Arrays.asList( + List.of( new Pose3d( new Translation3d(0.698303, -0.959096, 0.271076), new Rotation3d(new Quaternion(0.86403, -0.076866, 0.147234, 0.475254))), @@ -212,7 +212,7 @@ void testComplexTwists() { new Rotation3d(new Quaternion(0.807886, 0.029298, 0.257788, 0.529157)))); var final_poses = - Arrays.asList( + List.of( new Pose3d( new Translation3d(-0.230448, -0.511957, 0.198406), new Rotation3d(new Quaternion(0.753984, 0.347016, 0.409105, 0.379106))), @@ -267,7 +267,7 @@ void testComplexTwists() { @Test void testTwistNaN() { var initial_poses = - Arrays.asList( + List.of( new Pose3d( new Translation3d(6.32, 4.12, 0.00), new Rotation3d( @@ -277,7 +277,7 @@ void testTwistNaN() { new Rotation3d( new Quaternion(0.9999999999999793, 0.0, 0.0, 2.0352360299846772E-7)))); var final_poses = - Arrays.asList( + List.of( new Pose3d( new Translation3d(6.33, 4.15, 0.00), new Rotation3d( diff --git a/wpimath/src/test/java/edu/wpi/first/math/optimization/SimulatedAnnealingTest.java b/wpimath/src/test/java/edu/wpi/first/math/optimization/SimulatedAnnealingTest.java index d051b4328d0..baf9275dbb0 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/optimization/SimulatedAnnealingTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/optimization/SimulatedAnnealingTest.java @@ -21,7 +21,7 @@ void testDoubleFunctionOptimizationHeartBeat() { new SimulatedAnnealing( 2.0, x -> MathUtil.clamp(x + (Math.random() - 0.5) * stepSize, -3, 3), - x -> function.applyAsDouble(x)); + function::applyAsDouble); double solution = simulatedAnnealing.solve(-1.0, 5000); @@ -38,7 +38,7 @@ void testDoubleFunctionOptimizationMultimodal() { new SimulatedAnnealing( 2.0, x -> MathUtil.clamp(x + (Math.random() - 0.5) * stepSize, 0, 7), - x -> function.applyAsDouble(x)); + function::applyAsDouble); double solution = simulatedAnnealing.solve(-1.0, 5000); diff --git a/wpimath/src/test/java/edu/wpi/first/math/spline/CubicHermiteSplineTest.java b/wpimath/src/test/java/edu/wpi/first/math/spline/CubicHermiteSplineTest.java index 8e3d02b62d3..ecff3339199 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/spline/CubicHermiteSplineTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/spline/CubicHermiteSplineTest.java @@ -14,7 +14,6 @@ import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.spline.SplineParameterizer.MalformedSplineException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -151,7 +150,7 @@ void testMalformed() { () -> run( new Pose2d(10, 10, Rotation2d.fromDegrees(90)), - Arrays.asList(new Translation2d(10, 10.5)), + List.of(new Translation2d(10, 10.5)), new Pose2d(10, 11, Rotation2d.fromDegrees(-90)))); } } diff --git a/wpimath/src/test/java/edu/wpi/first/math/system/NumericalIntegrationTest.java b/wpimath/src/test/java/edu/wpi/first/math/system/NumericalIntegrationTest.java index 9b47148bf90..a0c7689cb03 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/system/NumericalIntegrationTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/system/NumericalIntegrationTest.java @@ -34,12 +34,7 @@ void testExponential() { void testZeroRKDP() { var y1 = NumericalIntegration.rkdp( - (x, u) -> { - return VecBuilder.fill(0); - }, - VecBuilder.fill(0), - VecBuilder.fill(0), - 0.1); + (x, u) -> VecBuilder.fill(0), VecBuilder.fill(0), VecBuilder.fill(0), 0.1); assertEquals(0.0, y1.get(0, 0), 1e-3); } diff --git a/wpimath/src/test/java/edu/wpi/first/math/system/RungeKuttaTimeVaryingTest.java b/wpimath/src/test/java/edu/wpi/first/math/system/RungeKuttaTimeVaryingTest.java index e0757eafe8b..bb28b73a9aa 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/system/RungeKuttaTimeVaryingTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/system/RungeKuttaTimeVaryingTest.java @@ -31,10 +31,9 @@ void rungeKuttaTimeVaryingTest() { final var y1 = RungeKuttaTimeVarying.rungeKuttaTimeVarying( - (Double t, Matrix x) -> { - return MatBuilder.fill( - Nat.N1(), Nat.N1(), x.get(0, 0) * (2.0 / (Math.exp(t) + 1.0) - 1.0)); - }, + (Double t, Matrix x) -> + MatBuilder.fill( + Nat.N1(), Nat.N1(), x.get(0, 0) * (2.0 / (Math.exp(t) + 1.0) - 1.0)), 5.0, y0, 1.0); diff --git a/wpimath/src/test/java/edu/wpi/first/math/trajectory/DifferentialDriveVoltageConstraintTest.java b/wpimath/src/test/java/edu/wpi/first/math/trajectory/DifferentialDriveVoltageConstraintTest.java index 917edb45fa8..58ee8305b16 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/trajectory/DifferentialDriveVoltageConstraintTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/trajectory/DifferentialDriveVoltageConstraintTest.java @@ -11,7 +11,6 @@ import edu.wpi.first.math.controller.SimpleMotorFeedforward; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; import edu.wpi.first.math.trajectory.constraint.DifferentialDriveVoltageConstraint; @@ -89,7 +88,7 @@ void testEndpointHighCurvature() { () -> TrajectoryGenerator.generateTrajectory( new Pose2d(1, 0, Rotation2d.fromDegrees(90)), - new ArrayList(), + new ArrayList<>(), new Pose2d(0, 1, Rotation2d.fromDegrees(180)), config)); @@ -97,7 +96,7 @@ void testEndpointHighCurvature() { () -> TrajectoryGenerator.generateTrajectory( new Pose2d(0, 1, Rotation2d.fromDegrees(180)), - new ArrayList(), + new ArrayList<>(), new Pose2d(1, 0, Rotation2d.fromDegrees(90)), config.setReversed(true))); } diff --git a/wpimath/src/test/java/edu/wpi/first/math/trajectory/TrajectoryGeneratorTest.java b/wpimath/src/test/java/edu/wpi/first/math/trajectory/TrajectoryGeneratorTest.java index 7e76c894aa4..4b0f3fc158c 100644 --- a/wpimath/src/test/java/edu/wpi/first/math/trajectory/TrajectoryGeneratorTest.java +++ b/wpimath/src/test/java/edu/wpi/first/math/trajectory/TrajectoryGeneratorTest.java @@ -16,7 +16,6 @@ import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.trajectory.constraint.TrajectoryConstraint; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -73,7 +72,7 @@ void testGenerationAndConstraints() { void testMalformedTrajectory() { var traj = TrajectoryGenerator.generateTrajectory( - Arrays.asList( + List.of( new Pose2d(0, 0, Rotation2d.fromDegrees(0)), new Pose2d(1, 0, Rotation2d.fromDegrees(180))), new TrajectoryConfig(feetToMeters(12), feetToMeters(12))); @@ -86,7 +85,7 @@ void testMalformedTrajectory() { void testQuinticCurvatureOptimization() { Trajectory t = TrajectoryGenerator.generateTrajectory( - Arrays.asList( + List.of( new Pose2d(1, 0, Rotation2d.fromDegrees(90)), new Pose2d(0, 1, Rotation2d.fromDegrees(180)), new Pose2d(-1, 0, Rotation2d.fromDegrees(270)), diff --git a/wpiutil/src/main/java/edu/wpi/first/util/CombinedRuntimeLoader.java b/wpiutil/src/main/java/edu/wpi/first/util/CombinedRuntimeLoader.java index 09e739da943..23149bd3817 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/CombinedRuntimeLoader.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/CombinedRuntimeLoader.java @@ -59,8 +59,7 @@ private static String getLoadErrorMessage(String libraryName, UnsatisfiedLinkErr @SuppressWarnings("unchecked") public static List extractLibraries(Class clazz, String resourceName) throws IOException { - TypeReference> typeRef = - new TypeReference>() {}; + TypeReference> typeRef = new TypeReference<>() {}; ObjectMapper mapper = new ObjectMapper(); Map map; try (var stream = clazz.getResourceAsStream(resourceName)) { diff --git a/wpiutil/src/main/java/edu/wpi/first/util/cleanup/CleanupPool.java b/wpiutil/src/main/java/edu/wpi/first/util/cleanup/CleanupPool.java index fab83166267..0ae5200e8c4 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/cleanup/CleanupPool.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/cleanup/CleanupPool.java @@ -14,7 +14,7 @@ public class CleanupPool implements AutoCloseable { // Use a Deque instead of a Stack, as Stack's iterators go the wrong way, and docs // state ArrayDeque is faster anyway. - private final Deque m_closers = new ArrayDeque(); + private final Deque m_closers = new ArrayDeque<>(); /** * Registers an object in the object stack for cleanup. diff --git a/wpiutil/src/main/java/edu/wpi/first/util/datalog/ProtobufLogEntry.java b/wpiutil/src/main/java/edu/wpi/first/util/datalog/ProtobufLogEntry.java index 1db2647b58f..9e7fa43b344 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/datalog/ProtobufLogEntry.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/datalog/ProtobufLogEntry.java @@ -37,7 +37,7 @@ private ProtobufLogEntry( */ public static > ProtobufLogEntry create( DataLog log, String name, Protobuf proto, String metadata, long timestamp) { - return new ProtobufLogEntry(log, name, proto, metadata, timestamp); + return new ProtobufLogEntry<>(log, name, proto, metadata, timestamp); } /** diff --git a/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructArrayLogEntry.java b/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructArrayLogEntry.java index 0f6cb2e7d03..b3a31c9a52e 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructArrayLogEntry.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructArrayLogEntry.java @@ -35,7 +35,7 @@ private StructArrayLogEntry( */ public static StructArrayLogEntry create( DataLog log, String name, Struct struct, String metadata, long timestamp) { - return new StructArrayLogEntry(log, name, struct, metadata, timestamp); + return new StructArrayLogEntry<>(log, name, struct, metadata, timestamp); } /** diff --git a/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructLogEntry.java b/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructLogEntry.java index a227c32d8bc..0d09182315e 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructLogEntry.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/datalog/StructLogEntry.java @@ -34,7 +34,7 @@ private StructLogEntry( */ public static StructLogEntry create( DataLog log, String name, Struct struct, String metadata, long timestamp) { - return new StructLogEntry(log, name, struct, metadata, timestamp); + return new StructLogEntry<>(log, name, struct, metadata, timestamp); } /** diff --git a/wpiutil/src/main/java/edu/wpi/first/util/protobuf/ProtobufBuffer.java b/wpiutil/src/main/java/edu/wpi/first/util/protobuf/ProtobufBuffer.java index 334cb161c9c..ae03c633002 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/protobuf/ProtobufBuffer.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/protobuf/ProtobufBuffer.java @@ -28,7 +28,7 @@ private ProtobufBuffer(Protobuf proto) { public static > ProtobufBuffer create( Protobuf proto) { - return new ProtobufBuffer(proto); + return new ProtobufBuffer<>(proto); } /** diff --git a/wpiutil/src/main/java/edu/wpi/first/util/struct/StructBuffer.java b/wpiutil/src/main/java/edu/wpi/first/util/struct/StructBuffer.java index 0e8aa187d25..8bd5768f09e 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/struct/StructBuffer.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/struct/StructBuffer.java @@ -22,7 +22,7 @@ private StructBuffer(Struct struct) { } public static StructBuffer create(Struct struct) { - return new StructBuffer(struct); + return new StructBuffer<>(struct); } /** diff --git a/wpiutil/src/main/java/edu/wpi/first/util/struct/StructDescriptorDatabase.java b/wpiutil/src/main/java/edu/wpi/first/util/struct/StructDescriptorDatabase.java index be7343fcfea..1eb58c9baf0 100644 --- a/wpiutil/src/main/java/edu/wpi/first/util/struct/StructDescriptorDatabase.java +++ b/wpiutil/src/main/java/edu/wpi/first/util/struct/StructDescriptorDatabase.java @@ -33,7 +33,7 @@ public StructDescriptor add(String name, String schema) throws BadSchemaExceptio } // turn parsed schema into descriptors - StructDescriptor theStruct = m_structs.computeIfAbsent(name, k -> new StructDescriptor(k)); + StructDescriptor theStruct = m_structs.computeIfAbsent(name, StructDescriptor::new); theStruct.m_schema = schema; theStruct.m_fields.clear(); boolean isValid = true; @@ -76,7 +76,7 @@ public StructDescriptor add(String name, String schema) throws BadSchemaExceptio // cross-reference struct, creating a placeholder if necessary StructDescriptor aStruct = - m_structs.computeIfAbsent(decl.typeString, k -> new StructDescriptor(k)); + m_structs.computeIfAbsent(decl.typeString, StructDescriptor::new); // if the struct isn't valid, we can't be valid either if (aStruct.isValid()) { diff --git a/wpiutil/src/printlog/java/printlog/PrintLog.java b/wpiutil/src/printlog/java/printlog/PrintLog.java index e9339b68aad..b3d972b47ae 100644 --- a/wpiutil/src/printlog/java/printlog/PrintLog.java +++ b/wpiutil/src/printlog/java/printlog/PrintLog.java @@ -10,9 +10,9 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; +import java.util.List; import java.util.Map; public final class PrintLog { @@ -133,11 +133,11 @@ public static void main(String[] args) { } else if ("boolean".equals(entry.type)) { System.out.println(" " + record.getBoolean()); } else if ("double[]".equals(entry.type)) { - System.out.println(" " + Arrays.asList(record.getDoubleArray())); + System.out.println(" " + List.of(record.getDoubleArray())); } else if ("int64[]".equals(entry.type)) { - System.out.println(" " + Arrays.asList(record.getIntegerArray())); + System.out.println(" " + List.of(record.getIntegerArray())); } else if ("string[]".equals(entry.type)) { - System.out.println(" " + Arrays.asList(record.getStringArray())); + System.out.println(" " + List.of(record.getStringArray())); } } catch (InputMismatchException ex) { System.out.println(" invalid"); diff --git a/wpiutil/src/test/java/edu/wpi/first/util/struct/parser/ParserTest.java b/wpiutil/src/test/java/edu/wpi/first/util/struct/parser/ParserTest.java index 52ba8dafcff..b985b2ae2bc 100644 --- a/wpiutil/src/test/java/edu/wpi/first/util/struct/parser/ParserTest.java +++ b/wpiutil/src/test/java/edu/wpi/first/util/struct/parser/ParserTest.java @@ -15,21 +15,21 @@ class ParserTest { @Test void testEmpty() { Parser p = new Parser(""); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertTrue(schema.declarations.isEmpty()); } @Test void testEmptySemicolon() { Parser p = new Parser(";"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertTrue(schema.declarations.isEmpty()); } @Test void testSimple() { Parser p = new Parser("int32 a"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -40,14 +40,14 @@ void testSimple() { @Test void testSimpleTrailingSemi() { Parser p = new Parser("int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); } @Test void testArray() { Parser p = new Parser("int32 a[2]"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -58,14 +58,14 @@ void testArray() { @Test void testArrayTrailingSemi() { Parser p = new Parser("int32 a[2];"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); } @Test void testBitfield() { Parser p = new Parser("int32 a:2"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -76,14 +76,14 @@ void testBitfield() { @Test void testBitfieldTrailingSemi() { Parser p = new Parser("int32 a:2;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); } @Test void testEnumKeyword() { Parser p = new Parser("enum {x=1} int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -95,7 +95,7 @@ void testEnumKeyword() { @Test void testEnumNoKeyword() { Parser p = new Parser("{x=1} int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -107,7 +107,7 @@ void testEnumNoKeyword() { @Test void testEnumNoValues() { Parser p = new Parser("{} int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -118,7 +118,7 @@ void testEnumNoValues() { @Test void testEnumMultipleValues() { Parser p = new Parser("{x=1,y=-2} int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -131,7 +131,7 @@ void testEnumMultipleValues() { @Test void testEnumTrailingComma() { Parser p = new Parser("{x=1,y=2,} int32 a;"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 1); var decl = schema.declarations.get(0); assertEquals(decl.typeString, "int32"); @@ -144,7 +144,7 @@ void testEnumTrailingComma() { @Test void testMultipleNoTrailingSemi() { Parser p = new Parser("int32 a; int16 b"); - ParsedSchema schema = assertDoesNotThrow(() -> p.parse()); + ParsedSchema schema = assertDoesNotThrow(p::parse); assertEquals(schema.declarations.size(), 2); assertEquals(schema.declarations.get(0).typeString, "int32"); assertEquals(schema.declarations.get(0).name, "a"); @@ -155,58 +155,55 @@ void testMultipleNoTrailingSemi() { @Test void testErrBitfieldArray() { Parser p = new Parser("int32 a[1]:2"); - assertThrows(ParseException.class, () -> p.parse(), "10: expected ';', got ':'"); + assertThrows(ParseException.class, p::parse, "10: expected ';', got ':'"); } @Test void testErrNoArrayValue() { Parser p = new Parser("int32 a[]"); - assertThrows(ParseException.class, () -> p.parse(), "8: expected integer, got ']'"); + assertThrows(ParseException.class, p::parse, "8: expected integer, got ']'"); } @Test void testErrNoBitfieldValue() { Parser p = new Parser("int32 a:"); - assertThrows(ParseException.class, () -> p.parse(), "8: expected integer, got ''"); + assertThrows(ParseException.class, p::parse, "8: expected integer, got ''"); } @Test void testErrNoNameArray() { Parser p = new Parser("int32 [2]"); - assertThrows(ParseException.class, () -> p.parse(), "6: expected identifier, got '['"); + assertThrows(ParseException.class, p::parse, "6: expected identifier, got '['"); } @Test void testErrNoNameBitField() { Parser p = new Parser("int32 :2"); - assertThrows(ParseException.class, () -> p.parse(), "6: expected identifier, got ':'"); + assertThrows(ParseException.class, p::parse, "6: expected identifier, got ':'"); } @Test void testNegativeBitField() { Parser p = new Parser("int32 a:-1"); assertThrows( - ParseException.class, () -> p.parse(), "8: bitfield width '-1' is not a positive integer"); + ParseException.class, p::parse, "8: bitfield width '-1' is not a positive integer"); } @Test void testNegativeArraySize() { Parser p = new Parser("int32 a[-1]"); - assertThrows( - ParseException.class, () -> p.parse(), "8: array size '-1' is not a positive integer"); + assertThrows(ParseException.class, p::parse, "8: array size '-1' is not a positive integer"); } @Test void testZeroBitField() { Parser p = new Parser("int32 a:0"); - assertThrows( - ParseException.class, () -> p.parse(), "8: bitfield width '0' is not a positive integer"); + assertThrows(ParseException.class, p::parse, "8: bitfield width '0' is not a positive integer"); } @Test void testZeroArraySize() { Parser p = new Parser("int32 a[0]"); - assertThrows( - ParseException.class, () -> p.parse(), "8: array size '0' is not a positive integer"); + assertThrows(ParseException.class, p::parse, "8: array size '0' is not a positive integer"); } }