From 625fd7624ef30ad6d96d965ad6422a24e0acbea7 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Fri, 5 Apr 2024 15:42:41 +0200 Subject: [PATCH 01/84] add test to avoid NullPointerException Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/commons/parameters/Parameter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java b/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java index 5cf23ebb126..8a860111ef4 100644 --- a/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java +++ b/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java @@ -32,7 +32,7 @@ public class Parameter { private final List possibleValues; - private ParameterScope scope; + private final ParameterScope scope; public Parameter(String name, ParameterType type, String description, Object defaultValue, List possibleValues, ParameterScope scope) { @@ -180,7 +180,7 @@ private static T read(Properties parameters, Parameter configuredParameter, } } // if none, use configured parameters - if (isPresent.test(value)) { + if (isPresent.test(value) && value != null) { return value; } return defaultValue; From 5c8d2332b039ba5d7730e77e7c536326621c5644 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Fri, 5 Apr 2024 15:59:13 +0200 Subject: [PATCH 02/84] fix return statement in MergedBus Signed-off-by: Nicolas Rol --- .../powsybl/iidm/network/impl/MergedBus.java | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MergedBus.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MergedBus.java index af218c65cbc..c3690f5aedd 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MergedBus.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MergedBus.java @@ -11,10 +11,7 @@ import com.powsybl.commons.PowsyblException; import com.powsybl.iidm.network.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Stream; /** @@ -42,18 +39,14 @@ private void checkValidity() { @Override public boolean isInMainConnectedComponent() { - for (ConfiguredBus bus : buses) { - return bus.isInMainConnectedComponent(); - } - return false; + Optional bus = buses.stream().findFirst(); + return bus.isPresent() && bus.get().isInMainConnectedComponent(); } @Override public boolean isInMainSynchronousComponent() { - for (ConfiguredBus bus : buses) { - return bus.isInMainSynchronousComponent(); - } - return false; + Optional bus = buses.stream().findFirst(); + return bus.isPresent() && bus.get().isInMainSynchronousComponent(); } @Override From 6f77f25bbf6b399da6465a54f32c8a3284f2f8c8 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Fri, 5 Apr 2024 16:14:26 +0200 Subject: [PATCH 03/84] add test to avoid potential ArrayIndexOutOfBoundsException Signed-off-by: Nicolas Rol --- .../java/com/powsybl/powerfactory/dgs/DgsParser.java | 4 ++++ .../com/powsybl/powerfactory/dgs/DgsDataTest.java | 12 ++++++++---- .../src/test/resources/ascii_missing_element.dgs | 2 ++ 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 powerfactory/powerfactory-dgs/src/test/resources/ascii_missing_element.dgs diff --git a/powerfactory/powerfactory-dgs/src/main/java/com/powsybl/powerfactory/dgs/DgsParser.java b/powerfactory/powerfactory-dgs/src/main/java/com/powsybl/powerfactory/dgs/DgsParser.java index e3b5a3fc784..ed98b5050aa 100644 --- a/powerfactory/powerfactory-dgs/src/main/java/com/powsybl/powerfactory/dgs/DgsParser.java +++ b/powerfactory/powerfactory-dgs/src/main/java/com/powsybl/powerfactory/dgs/DgsParser.java @@ -7,6 +7,7 @@ */ package com.powsybl.powerfactory.dgs; +import com.powsybl.commons.PowsyblException; import com.powsybl.powerfactory.model.DataAttributeType; import com.powsybl.powerfactory.model.PowerFactoryException; import org.apache.commons.lang3.ArrayUtils; @@ -274,6 +275,9 @@ public void read(Reader reader, DgsHandler handler) { private static void readGeneralTableRow(String trimmedLine, DgsHandler handler, ParsingContext context) { String[] fields = splitConsideringQuotedText(trimmedLine); + if (fields.length < 3) { + throw new PowsyblException(String.format("Not enough fields in the line: '%s'", trimmedLine)); + } String descr = fields[1]; String val = fields[2]; if (descr.equals(VERSION)) { diff --git a/powerfactory/powerfactory-dgs/src/test/java/com/powsybl/powerfactory/dgs/DgsDataTest.java b/powerfactory/powerfactory-dgs/src/test/java/com/powsybl/powerfactory/dgs/DgsDataTest.java index e2dc775949e..6915deafbdf 100644 --- a/powerfactory/powerfactory-dgs/src/test/java/com/powsybl/powerfactory/dgs/DgsDataTest.java +++ b/powerfactory/powerfactory-dgs/src/test/java/com/powsybl/powerfactory/dgs/DgsDataTest.java @@ -9,6 +9,7 @@ import com.google.common.io.ByteStreams; import com.google.common.io.Files; +import com.powsybl.commons.PowsyblException; import com.powsybl.commons.test.AbstractSerDeTest; import com.powsybl.commons.test.TestUtil; import com.powsybl.powerfactory.model.PowerFactoryException; @@ -19,10 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.Objects; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Luma ZamarreƱo {@literal } @@ -85,6 +83,12 @@ void v7ErrorTest() { assertThrows(PowerFactoryException.class, () -> loadCase("/ascii_v7.dgs")); } + @Test + void missingElementInLineTest() { + PowsyblException exception = assertThrows(PowsyblException.class, () -> loadCase("/ascii_missing_element.dgs")); + assertEquals("Not enough fields in the line: '1;Version'", exception.getMessage()); + } + private boolean test(String dgs, String json) throws IOException { StudyCase studyCase = loadCase(dgs); String expectedJson = loadReference(json); diff --git a/powerfactory/powerfactory-dgs/src/test/resources/ascii_missing_element.dgs b/powerfactory/powerfactory-dgs/src/test/resources/ascii_missing_element.dgs new file mode 100644 index 00000000000..75d4e00c7b0 --- /dev/null +++ b/powerfactory/powerfactory-dgs/src/test/resources/ascii_missing_element.dgs @@ -0,0 +1,2 @@ +$$General;FID(a:40);Descr(a:40);Val(a:40) + 1;Version From 624c3379ea221425d97109bef8e5ed96384b1375 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Fri, 5 Apr 2024 16:52:37 +0200 Subject: [PATCH 04/84] BREAKING CHANGE - Change JsonTypeInfo to avoid unsafe Jackson deserialization https://rules.sonarsource.com/java/RSPEC-4544/ Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/iidm/network/BusRef.java | 4 +++- .../src/main/java/com/powsybl/iidm/network/IdBasedBusRef.java | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/BusRef.java b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/BusRef.java index 6d5e6f34a27..0c1124506dc 100644 --- a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/BusRef.java +++ b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/BusRef.java @@ -15,7 +15,9 @@ @JsonSubTypes({ @JsonSubTypes.Type(value = IdBasedBusRef.class) }) -@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS) +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + property = "@c") public interface BusRef { /** diff --git a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/IdBasedBusRef.java b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/IdBasedBusRef.java index 48adb3b104d..44cef352a9f 100644 --- a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/IdBasedBusRef.java +++ b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/IdBasedBusRef.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; import com.powsybl.commons.PowsyblException; import java.util.Objects; @@ -23,6 +24,7 @@ * @author Yichen TANG {@literal } */ @JsonInclude(JsonInclude.Include.NON_NULL) +@JsonTypeName(".IdBasedBusRef") public class IdBasedBusRef extends AbstractBusRef { private final String id; From aa523f1bcea78e303a61bd72a968b1b15a9e3d70 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Fri, 5 Apr 2024 17:12:41 +0200 Subject: [PATCH 05/84] fix GeneratorModificationActionTest Signed-off-by: Nicolas Rol --- .../dsl/GeneratorModificationActionTest.java | 72 ++++++++----------- 1 file changed, 29 insertions(+), 43 deletions(-) diff --git a/action-ial/action-ial-dsl/src/test/java/com/powsybl/action/ial/dsl/GeneratorModificationActionTest.java b/action-ial/action-ial-dsl/src/test/java/com/powsybl/action/ial/dsl/GeneratorModificationActionTest.java index c438a14c461..39af3072cb9 100644 --- a/action-ial/action-ial-dsl/src/test/java/com/powsybl/action/ial/dsl/GeneratorModificationActionTest.java +++ b/action-ial/action-ial-dsl/src/test/java/com/powsybl/action/ial/dsl/GeneratorModificationActionTest.java @@ -16,6 +16,12 @@ import groovy.lang.GroovyCodeSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Objects; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @@ -36,7 +42,7 @@ void setUp() { @Test void testExceptionOnWrongGeneratorId() { ActionDb actionDb = new ActionDslLoader( - new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("unknown generator"); NetworkModification genModif = action.getModifications().get(0); // should throw with ThrowException = true @@ -48,7 +54,7 @@ void testExceptionOnWrongGeneratorId() { @Test void testTargetVAndQWithVoltageRegulatorOff() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("targetV and targetQ with voltageRegulator OFF"); action.run(network); assertEquals(20., g.getMinP(), 0.1); @@ -61,7 +67,7 @@ void testTargetVAndQWithVoltageRegulatorOff() { @Test void testTargetVAndQWithVoltageRegulatorOn() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("targetV and targetQ with voltageRegulator ON"); action.run(network); assertEquals(10, g.getTargetV(), 0.1); @@ -69,55 +75,35 @@ void testTargetVAndQWithVoltageRegulatorOn() { assertTrue(g.isVoltageRegulatorOn()); } - @Test - void testDeltaTargetPInBoundaries() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); - Action action = actionDb.getAction("deltaTargetP within boundaries"); - action.run(network); - assertEquals(606., g.getTargetP(), 0.1); - } - - @Test - void testDeltaTargetPLowerBoundaryOverflow() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); - Action action = actionDb.getAction("deltaTargetP lower boundary overflow"); - action.run(network); - assertEquals(-9999.99, g.getTargetP(), 0.1); - } - - @Test - void testDeltaTargetPUpperBoundaryOverflow() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); - Action action = actionDb.getAction("deltaTargetP upper boundary overflow"); - action.run(network); - assertEquals(9999.99, g.getTargetP(), 0.1); - } - - @Test - void testTargetPLowerBoundaryOverflow() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); - Action action = actionDb.getAction("targetP lower boundary overflow"); - action.run(network); - assertEquals(-9999.99, g.getTargetP(), 0.1); + static Stream getArguments() { + return Stream.of( + Arguments.of("deltaTargetP within boundaries", 606.), + Arguments.of("deltaTargetP upper boundary overflow", 9999.99), + Arguments.of("deltaTargetP lower boundary overflow", -9999.99), + Arguments.of("targetP upper boundary overflow", 9999.99), + Arguments.of("targetP lower boundary overflow", -9999.99) + ); } - @Test - void testTargetPUpperBoundaryOverflow() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); - Action action = actionDb.getAction("targetP upper boundary overflow"); + @ParameterizedTest + @MethodSource("getArguments") + void testActionsFromDb(String actionName, double expectedValue) { + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); + Action action = actionDb.getAction(actionName); action.run(network); - assertEquals(9999.99, g.getTargetP(), 0.1); + assertEquals(expectedValue, g.getTargetP(), 0.1); } @Test void testBothTargetpAndDeltaTargetP() { - PowsyblException e = assertThrows(PowsyblException.class, () -> new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/exception-generator-modification-action.groovy"))).load(network)); + ActionDslLoader actionDslLoader = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/exception-generator-modification-action.groovy")))); + PowsyblException e = assertThrows(PowsyblException.class, () -> actionDslLoader.load(network)); assertTrue(e.getMessage().contains("targetP/deltaTargetP actions are both found in generatorModification on 'GEN'")); } @Test void testConnectionOnOff() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("disconnect"); action.run(network); assertFalse(g.getTerminal().isConnected()); @@ -128,7 +114,7 @@ void testConnectionOnOff() { @Test void testConnectionOnOffWithTargetPChange() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("disconnect with targetP change"); action.run(network); assertFalse(g.getTerminal().isConnected()); @@ -141,7 +127,7 @@ void testConnectionOnOffWithTargetPChange() { @Test void testAlreadyAtTheConnectionStateAsked() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("connect"); action.run(network); assertTrue(g.getTerminal().isConnected()); @@ -154,7 +140,7 @@ void testAlreadyAtTheConnectionStateAsked() { @Test void testConnectionOnOffWithTargetVChange() { - ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); + ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(Objects.requireNonNull(getClass().getResource("/generator-modification-action.groovy")))).load(network); Action action = actionDb.getAction("disconnect"); action.run(network); assertFalse(g.getTerminal().isConnected()); From 489d5ff2767c6953725491034bf32447352be578 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 10:35:23 +0200 Subject: [PATCH 06/84] remove peek usage Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/cgmes/conversion/Conversion.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cgmes/cgmes-conversion/src/main/java/com/powsybl/cgmes/conversion/Conversion.java b/cgmes/cgmes-conversion/src/main/java/com/powsybl/cgmes/conversion/Conversion.java index 31c3edb82fe..8a2e7ec74bc 100644 --- a/cgmes/cgmes-conversion/src/main/java/com/powsybl/cgmes/conversion/Conversion.java +++ b/cgmes/cgmes-conversion/src/main/java/com/powsybl/cgmes/conversion/Conversion.java @@ -810,9 +810,10 @@ private void voltageAngles(PropertyBags nodes, Context context) { private void clearUnattachedHvdcConverterStations(Network network, Context context) { network.getHvdcConverterStationStream() .filter(converter -> converter.getHvdcLine() == null) - .peek(converter -> context.ignored("HVDC Converter Station " + converter.getId(), "No correct linked HVDC line found.")) - .toList() - .forEach(Connectable::remove); + .forEach(converter -> { + context.ignored("HVDC Converter Station " + converter.getId(), "No correct linked HVDC line found."); + converter.remove(); + }); } private void debugTopology(Context context) { From c5d232c1ab89c3ee53d064d28f19fffe8160257b Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 10:45:41 +0200 Subject: [PATCH 07/84] remove duplicated tests Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 32 ++++++------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index e311321ff44..fba87618e68 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -201,8 +201,16 @@ void microGridBaseCaseBExfmr2Ratio0X() throws IOException { assertTrue(ok); } - @Test - void microGridBaseCaseBExfmr3ShuntDefault() throws IOException { + /** + * Default test for: + *
    + *
  • microGridBaseCaseBExfmr3Shunt
+ *
  • microGridBaseCaseBExfmr3RatioPhase + *
  • microGridBaseCaseBExfmr3Ratio0 + * + */ + @Test + void microGridBaseCaseDefault() throws IOException { Conversion.Config config = new Conversion.Config(); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -245,16 +253,6 @@ void microGridBaseCaseBExfmr3ShuntSplit() throws IOException { assertTrue(ok); } - @Test - void microGridBaseCaseBExfmr3RatioPhaseDefault() throws IOException { - Conversion.Config config = new Conversion.Config(); - Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); - - // RatioTapChanger - boolean ok = t3xCompareFlow(n, "_84ed55f4-61f5-4d9d-8755-bba7b877a246", 99.227288, 2.747147, -216.195867, -85.490493, 117.988318, 92.500849); - assertTrue(ok); - } - @Test void microGridBaseCaseBExfmr3RatioPhaseNetworkSide() throws IOException { Conversion.Config config = new Conversion.Config(); @@ -277,16 +275,6 @@ void microGridBaseCaseBExfmr3RatioPhaseStarBusSide() throws IOException { assertTrue(ok); } - @Test - void microGridBaseCaseBExfmr3Ratio0Default() throws IOException { - Conversion.Config config = new Conversion.Config(); - Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); - - // RatioTapChanger - boolean ok = t3xCompareFlow(n, "_84ed55f4-61f5-4d9d-8755-bba7b877a246", 99.227288, 2.747147, -216.195867, -85.490493, 117.988318, 92.500849); - assertTrue(ok); - } - @Test void microGridBaseCaseBExfmr3Ratio0StarBusSide() throws IOException { Conversion.Config config = new Conversion.Config(); From 05de80b92eff8c07a459986ac87b0f92d8d21a04 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 10:49:07 +0200 Subject: [PATCH 08/84] remove exceptions not thrown Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 61 +++++++++---------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index fba87618e68..dbfbc77a026 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -25,7 +25,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -40,7 +39,7 @@ class TransformerConversionTest { @Test - void microGridBaseCaseBExfmr2ShuntDefault() throws IOException { + void microGridBaseCaseBExfmr2ShuntDefault() { Conversion.Config config = new Conversion.Config(); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); boolean ok = t2xCompareFlow(n, "_e482b89a-fa84-4ea9-8e70-a83d44790957", -93.855301, -15.285520, 94.158074, 20.388478); @@ -48,7 +47,7 @@ void microGridBaseCaseBExfmr2ShuntDefault() throws IOException { } @Test - void microGridBaseCaseBExfmr2ShuntEnd1() throws IOException { + void microGridBaseCaseBExfmr2ShuntEnd1() { Conversion.Config config = new Conversion.Config(); config.setXfmr2Shunt(Xfmr2ShuntInterpretationAlternative.END1); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -57,7 +56,7 @@ void microGridBaseCaseBExfmr2ShuntEnd1() throws IOException { } @Test - void microGridBaseCaseBExfmr2ShuntEnd2() throws IOException { + void microGridBaseCaseBExfmr2ShuntEnd2() { Conversion.Config config = new Conversion.Config(); config.setXfmr2Shunt(Xfmr2ShuntInterpretationAlternative.END2); // Same result as End1, IIDM model and LoadFlowParameters does not allow this configuration @@ -67,7 +66,7 @@ void microGridBaseCaseBExfmr2ShuntEnd2() throws IOException { } @Test - void microGridBaseCaseBExfmr2ShuntEnd1End2() throws IOException { + void microGridBaseCaseBExfmr2ShuntEnd1End2() { Conversion.Config config = new Conversion.Config(); config.setXfmr2Shunt(Xfmr2ShuntInterpretationAlternative.END1_END2); // Same result as End1, IIDM model and LoadFlowParameters does not allow this configuration @@ -77,7 +76,7 @@ void microGridBaseCaseBExfmr2ShuntEnd1End2() throws IOException { } @Test - void microGridBaseCaseBExfmr2ShuntSplit() throws IOException { + void microGridBaseCaseBExfmr2ShuntSplit() { Conversion.Config config = new Conversion.Config(); config.setXfmr2Shunt(Xfmr2ShuntInterpretationAlternative.SPLIT); config.setXfmr3Shunt(Xfmr3ShuntInterpretationAlternative.SPLIT); @@ -87,7 +86,7 @@ void microGridBaseCaseBExfmr2ShuntSplit() throws IOException { } @Test - void microGridBaseCaseBExfmr2RatioPhaseDefault() throws IOException { + void microGridBaseCaseBExfmr2RatioPhaseDefault() { Conversion.Config config = new Conversion.Config(); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); // RatioTapChanger @@ -99,7 +98,7 @@ void microGridBaseCaseBExfmr2RatioPhaseDefault() throws IOException { } @Test - void microGridBaseCaseBExfmr2RatioPhaseEnd1() throws IOException { + void microGridBaseCaseBExfmr2RatioPhaseEnd1() { Conversion.Config config = new Conversion.Config(); config.setXfmr2RatioPhase(Xfmr2RatioPhaseInterpretationAlternative.END1); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -112,7 +111,7 @@ void microGridBaseCaseBExfmr2RatioPhaseEnd1() throws IOException { } @Test - void microGridBaseCaseBExfmr2RatioPhaseEnd2() throws IOException { + void microGridBaseCaseBExfmr2RatioPhaseEnd2() { Conversion.Config config = new Conversion.Config(); config.setXfmr2RatioPhase(Xfmr2RatioPhaseInterpretationAlternative.END2); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -125,7 +124,7 @@ void microGridBaseCaseBExfmr2RatioPhaseEnd2() throws IOException { } @Test - void microGridBaseCaseBExfmr2RatioPhaseEnd1End2() throws IOException { + void microGridBaseCaseBExfmr2RatioPhaseEnd1End2() { Conversion.Config config = new Conversion.Config(); config.setXfmr2RatioPhase(Xfmr2RatioPhaseInterpretationAlternative.END1_END2); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -138,7 +137,7 @@ void microGridBaseCaseBExfmr2RatioPhaseEnd1End2() throws IOException { } @Test - void microGridBaseCaseBExfmr2RatioPhaseX() throws IOException { + void microGridBaseCaseBExfmr2RatioPhaseX() { Conversion.Config config = new Conversion.Config(); config.setXfmr2RatioPhase(Xfmr2RatioPhaseInterpretationAlternative.X); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -151,7 +150,7 @@ void microGridBaseCaseBExfmr2RatioPhaseX() throws IOException { } @Test - void microGridBaseCaseBExfmr2Ratio0Default() throws IOException { + void microGridBaseCaseBExfmr2Ratio0Default() { Conversion.Config config = new Conversion.Config(); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); // RatioTapChanger @@ -163,7 +162,7 @@ void microGridBaseCaseBExfmr2Ratio0Default() throws IOException { } @Test - void microGridBaseCaseBExfmr2Ratio0End1() throws IOException { + void microGridBaseCaseBExfmr2Ratio0End1() { Conversion.Config config = new Conversion.Config(); config.setXfmr2StructuralRatio(Xfmr2StructuralRatioInterpretationAlternative.END1); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -176,7 +175,7 @@ void microGridBaseCaseBExfmr2Ratio0End1() throws IOException { } @Test - void microGridBaseCaseBExfmr2Ratio0End2() throws IOException { + void microGridBaseCaseBExfmr2Ratio0End2() { Conversion.Config config = new Conversion.Config(); config.setXfmr2StructuralRatio(Xfmr2StructuralRatioInterpretationAlternative.END2); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -189,7 +188,7 @@ void microGridBaseCaseBExfmr2Ratio0End2() throws IOException { } @Test - void microGridBaseCaseBExfmr2Ratio0X() throws IOException { + void microGridBaseCaseBExfmr2Ratio0X() { Conversion.Config config = new Conversion.Config(); config.setXfmr2StructuralRatio(Xfmr2StructuralRatioInterpretationAlternative.X); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -210,7 +209,7 @@ void microGridBaseCaseBExfmr2Ratio0X() throws IOException { * */ @Test - void microGridBaseCaseDefault() throws IOException { + void microGridBaseCaseDefault() { Conversion.Config config = new Conversion.Config(); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -220,7 +219,7 @@ void microGridBaseCaseDefault() throws IOException { } @Test - void microGridBaseCaseBExfmr3ShuntNetworkSide() throws IOException { + void microGridBaseCaseBExfmr3ShuntNetworkSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3Shunt(Xfmr3ShuntInterpretationAlternative.NETWORK_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -231,7 +230,7 @@ void microGridBaseCaseBExfmr3ShuntNetworkSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3ShuntStarBusSide() throws IOException { + void microGridBaseCaseBExfmr3ShuntStarBusSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3Shunt(Xfmr3ShuntInterpretationAlternative.STAR_BUS_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -242,7 +241,7 @@ void microGridBaseCaseBExfmr3ShuntStarBusSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3ShuntSplit() throws IOException { + void microGridBaseCaseBExfmr3ShuntSplit() { Conversion.Config config = new Conversion.Config(); config.setXfmr2Shunt(Xfmr2ShuntInterpretationAlternative.SPLIT); config.setXfmr3Shunt(Xfmr3ShuntInterpretationAlternative.SPLIT); @@ -254,7 +253,7 @@ void microGridBaseCaseBExfmr3ShuntSplit() throws IOException { } @Test - void microGridBaseCaseBExfmr3RatioPhaseNetworkSide() throws IOException { + void microGridBaseCaseBExfmr3RatioPhaseNetworkSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3RatioPhase(Xfmr3RatioPhaseInterpretationAlternative.NETWORK_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -265,7 +264,7 @@ void microGridBaseCaseBExfmr3RatioPhaseNetworkSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3RatioPhaseStarBusSide() throws IOException { + void microGridBaseCaseBExfmr3RatioPhaseStarBusSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3RatioPhase(Xfmr3RatioPhaseInterpretationAlternative.STAR_BUS_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -276,7 +275,7 @@ void microGridBaseCaseBExfmr3RatioPhaseStarBusSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3Ratio0StarBusSide() throws IOException { + void microGridBaseCaseBExfmr3Ratio0StarBusSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3StructuralRatio(Xfmr3StructuralRatioInterpretationAlternative.STAR_BUS_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -287,7 +286,7 @@ void microGridBaseCaseBExfmr3Ratio0StarBusSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3Ratio0NetworkSide() throws IOException { + void microGridBaseCaseBExfmr3Ratio0NetworkSide() { Conversion.Config config = new Conversion.Config(); config.setXfmr3StructuralRatio(Xfmr3StructuralRatioInterpretationAlternative.NETWORK_SIDE); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -298,7 +297,7 @@ void microGridBaseCaseBExfmr3Ratio0NetworkSide() throws IOException { } @Test - void microGridBaseCaseBExfmr3Ratio0End1() throws IOException { + void microGridBaseCaseBExfmr3Ratio0End1() { Conversion.Config config = new Conversion.Config(); config.setXfmr3StructuralRatio(Xfmr3StructuralRatioInterpretationAlternative.END1); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -309,7 +308,7 @@ void microGridBaseCaseBExfmr3Ratio0End1() throws IOException { } @Test - void microGridBaseCaseBExfmr3Ratio0End2() throws IOException { + void microGridBaseCaseBExfmr3Ratio0End2() { Conversion.Config config = new Conversion.Config(); config.setXfmr3StructuralRatio(Xfmr3StructuralRatioInterpretationAlternative.END2); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -320,7 +319,7 @@ void microGridBaseCaseBExfmr3Ratio0End2() throws IOException { } @Test - void microGridBaseCaseBExfmr3Ratio0End3() throws IOException { + void microGridBaseCaseBExfmr3Ratio0End3() { Conversion.Config config = new Conversion.Config(); config.setXfmr3StructuralRatio(Xfmr3StructuralRatioInterpretationAlternative.END3); Network n = networkModel(CgmesConformity1Catalog.microGridBaseCaseBE(), config); @@ -331,7 +330,7 @@ void microGridBaseCaseBExfmr3Ratio0End3() throws IOException { } @Test - void miniBusBranchPhaseAngleClock() throws IOException { + void miniBusBranchPhaseAngleClock() { Conversion.Config config = new Conversion.Config(); List postProcessors = new ArrayList<>(); postProcessors.add(new PhaseAngleClock()); @@ -345,7 +344,7 @@ void miniBusBranchPhaseAngleClock() throws IOException { } @Test - void miniBusBranchPhaseAngleClockZero() throws IOException { + void miniBusBranchPhaseAngleClockZero() { Conversion.Config config = new Conversion.Config(); List postProcessors = new ArrayList<>(); postProcessors.add(new PhaseAngleClock()); @@ -359,7 +358,7 @@ void miniBusBranchPhaseAngleClockZero() throws IOException { } @Test - void miniBusBranchT2xPhaseAngleClock1NonZero() throws IOException { + void miniBusBranchT2xPhaseAngleClock1NonZero() { Conversion.Config config = new Conversion.Config(); List postProcessors = new ArrayList<>(); postProcessors.add(new PhaseAngleClock()); @@ -371,7 +370,7 @@ void miniBusBranchT2xPhaseAngleClock1NonZero() throws IOException { } @Test - void miniBusBranchT3xAllPhaseAngleClockNonZero() throws IOException { + void miniBusBranchT3xAllPhaseAngleClockNonZero() { Conversion.Config config = new Conversion.Config(); List postProcessors = new ArrayList<>(); postProcessors.add(new PhaseAngleClock()); @@ -383,7 +382,7 @@ void miniBusBranchT3xAllPhaseAngleClockNonZero() throws IOException { } @Test - void microGridBaseCaseBEPhaseTapChangerXMin() throws IOException { + void microGridBaseCaseBEPhaseTapChangerXMin() { Network n = networkModel(Cgmes3ModifiedCatalog.microGridBaseCasePhaseTapChangerXMin(), new Conversion.Config()); TwoWindingsTransformer twt1 = n.getTwoWindingsTransformer("a708c3bc-465d-4fe7-b6ef-6fa6408a62b0"); From 7f239104300a6318c6fe36096de64f5077b6aa8d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 10:55:06 +0200 Subject: [PATCH 09/84] if simplifications Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 40 ++++++++----------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index dbfbc77a026..f9d07884de3 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -38,6 +38,8 @@ */ class TransformerConversionTest { + private static final String EQUALS_LINE = "======================"; + @Test void microGridBaseCaseBExfmr2ShuntDefault() { Conversion.Config config = new Conversion.Config(); @@ -412,7 +414,7 @@ private boolean t2xCompareFlow(Network n, String id, double p1, double q1, doubl LOG.error(String.format("TransformerConversionTest: TwoWindingsTransformer id %s ===", id)); LOG.error(String.format("Expected P1 %12.6f Q1 %12.6f P2 %12.6f Q2 %12.6f", expected.p1, expected.q1, expected.p2, expected.q2)); LOG.error(String.format("Actual P1 %12.6f Q1 %12.6f P2 %12.6f Q2 %12.6f", actual.p1, actual.q1, actual.p2, actual.q2)); - LOG.error(String.format("======================", id)); + LOG.error(EQUALS_LINE); } return ok; } @@ -432,7 +434,7 @@ private boolean t3xCompareFlow(Network n, String id, double p1, double q1, doubl expected.q1, expected.p2, expected.q2, expected.p3, expected.q3)); LOG.error(String.format("Actual P1 %12.6f Q1 %12.6f P2 %12.6f Q2 %12.6f P3 %12.6f Q3 %12.6f", actual.p1, actual.q1, actual.p2, actual.q2, actual.p3, actual.q3)); - LOG.error(String.format("======================", id)); + LOG.error(EQUALS_LINE); } return ok; } @@ -508,26 +510,20 @@ private static T3xFlow threeWindingsTransformerFlow(ThreeWindingsTransformer twt private boolean sameFlow(T2xFlow expected, T2xFlow actual) { double tol = 0.00001; - if (Math.abs(expected.p1 - actual.p1) > tol || - Math.abs(expected.q1 - actual.q1) > tol || - Math.abs(expected.p2 - actual.p2) > tol || - Math.abs(expected.q2 - actual.q2) > tol) { - return false; - } - return true; + return !(Math.abs(expected.p1 - actual.p1) > tol) && + !(Math.abs(expected.q1 - actual.q1) > tol) && + !(Math.abs(expected.p2 - actual.p2) > tol) && + !(Math.abs(expected.q2 - actual.q2) > tol); } private boolean sameFlow(T3xFlow expected, T3xFlow actual) { double tol = 0.00001; - if (Math.abs(expected.p1 - actual.p1) > tol || - Math.abs(expected.q1 - actual.q1) > tol || - Math.abs(expected.p2 - actual.p2) > tol || - Math.abs(expected.q2 - actual.q2) > tol || - Math.abs(expected.p3 - actual.p3) > tol || - Math.abs(expected.q3 - actual.q3) > tol) { - return false; - } - return true; + return !(Math.abs(expected.p1 - actual.p1) > tol) && + !(Math.abs(expected.q1 - actual.q1) > tol) && + !(Math.abs(expected.p2 - actual.p2) > tol) && + !(Math.abs(expected.q2 - actual.q2) > tol) && + !(Math.abs(expected.p3 - actual.p3) > tol) && + !(Math.abs(expected.q3 - actual.q3) > tol); } private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowParameters, Conversion.Config config) { @@ -553,13 +549,11 @@ private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowP t3wtSplitShuntAdmittance = true; } boolean twtSplitShuntAdmittance = false; - if (!t2wtSplitShuntAdmittance && !t3wtSplitShuntAdmittance) { - twtSplitShuntAdmittance = false; - } else if (t2wtSplitShuntAdmittance && t3wtSplitShuntAdmittance) { - twtSplitShuntAdmittance = true; - } else { + if (t2wtSplitShuntAdmittance != t3wtSplitShuntAdmittance) { throw new PowsyblException(String.format("Unexpected SplitShuntAdmittance configuration %s %s", t2wtSplitShuntAdmittance, t3wtSplitShuntAdmittance)); + } else if (t2wtSplitShuntAdmittance) { + twtSplitShuntAdmittance = true; } copyLoadFlowParameters.setTwtSplitShuntAdmittance(twtSplitShuntAdmittance); From bcd721f4ddf835a9fb3c85607259e3cc251cfb2a Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:09:04 +0200 Subject: [PATCH 10/84] removed unused methods Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 77 +------------------ 1 file changed, 4 insertions(+), 73 deletions(-) diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index f9d07884de3..d3ef0fa506d 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -17,8 +17,10 @@ import com.powsybl.cgmes.conversion.PhaseAngleClock; import com.powsybl.cgmes.model.GridModelReference; import com.powsybl.commons.PowsyblException; -import com.powsybl.iidm.network.*; -import com.powsybl.iidm.network.ThreeWindingsTransformer.Leg; +import com.powsybl.iidm.network.Network; +import com.powsybl.iidm.network.Terminal; +import com.powsybl.iidm.network.ThreeWindingsTransformer; +import com.powsybl.iidm.network.TwoWindingsTransformer; import com.powsybl.loadflow.LoadFlowParameters; import com.powsybl.loadflow.validation.ValidationConfig; import org.junit.jupiter.api.Test; @@ -577,76 +579,5 @@ static class T3xFlow { double q3 = Double.NaN; } - private static void logAllTwoWindingsTransformer(Network n) { - n.getTwoWindingsTransformerStream().forEach(TransformerConversionTest::logTwoWindingsTransformerAttributes); - } - - private static void logTwoWindingsTransformerAttributes(TwoWindingsTransformer twt) { - LOG.info("TwoWindingsTransformer {} ============", twt.getId()); - LOG.info("G {}", twt.getG()); - LOG.info("B {}", twt.getB()); - RatioTapChanger rtc = twt.getRatioTapChanger(); - logRatioTapChangerAttributes(rtc); - PhaseTapChanger ptc = twt.getPhaseTapChanger(); - logPhaseTapChangerAttributes(ptc); - } - - private static void logAllThreeWindingsTransformer(Network n) { - n.getThreeWindingsTransformerStream().forEach(TransformerConversionTest::logThreeWindingsTransformerAttributes); - } - - private static void logThreeWindingsTransformerAttributes(ThreeWindingsTransformer twt) { - LOG.info("ThreeWindingsTransformer {} ============", twt.getId()); - LOG.info("RatedU0 {}", twt.getRatedU0()); - LOG.info("Leg1 ------"); - logLegAttributes(twt.getLeg1()); - LOG.info("Leg2 ------"); - logLegAttributes(twt.getLeg2()); - LOG.info("Leg3 ------"); - logLegAttributes(twt.getLeg3()); - } - - private static void logLegAttributes(Leg leg) { - LOG.info("G {}", leg.getG()); - LOG.info("B {}", leg.getB()); - RatioTapChanger rtc = leg.getRatioTapChanger(); - logRatioTapChangerAttributes(rtc); - PhaseTapChanger ptc = leg.getPhaseTapChanger(); - logPhaseTapChangerAttributes(ptc); - } - - private static void logRatioTapChangerAttributes(RatioTapChanger rtc) { - if (rtc == null) { - LOG.info("RatioTapChanger: null"); - return; - } - - int tapPosition = rtc.getTapPosition(); - RatioTapChangerStep step = rtc.getStep(tapPosition); - LOG.info("RatioTapChanger: TapPosition {}", tapPosition); - LOG.info("RatioTapChanger: Step Ratio {}", 1 / step.getRho()); - LOG.info("RatioTapChanger: Step R {}", step.getR()); - LOG.info("RatioTapChanger: Step X {}", step.getX()); - LOG.info("RatioTapChanger: Step G {}", step.getG()); - LOG.info("RatioTapChanger: Step B {}", step.getB()); - } - - private static void logPhaseTapChangerAttributes(PhaseTapChanger ptc) { - if (ptc == null) { - LOG.info("PhaseTapChanger: null"); - return; - } - - int tapPosition = ptc.getTapPosition(); - PhaseTapChangerStep step = ptc.getStep(tapPosition); - LOG.info("PhaseTapChanger: TapPosition {}", tapPosition); - LOG.info("PhaseTapChanger: Step Ratio {}", 1 / step.getRho()); - LOG.info("PhaseTapChanger: Step Angle {}", -step.getAlpha()); - LOG.info("PhaseTapChanger: Step R {}", step.getR()); - LOG.info("PhaseTapChanger: Step X {}", step.getX()); - LOG.info("PhaseTapChanger: Step G {}", step.getG()); - LOG.info("PhaseTapChanger: Step B {}", step.getB()); - } - private static final Logger LOG = LoggerFactory.getLogger(TransformerConversionTest.class); } From 21da610f06155b2f3b3aa4fcdef1cdbd4d8207e9 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:11:48 +0200 Subject: [PATCH 11/84] use Supplier from java instead if guava Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/cgmes/model/FullModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java index e3248e72ba0..52b8b6c5971 100644 --- a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java +++ b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java @@ -7,7 +7,6 @@ */ package com.powsybl.cgmes.model; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.PowsyblException; import com.powsybl.commons.exceptions.UncheckedXmlStreamException; @@ -20,6 +19,7 @@ import java.io.Reader; import java.time.ZonedDateTime; import java.util.*; +import java.util.function.Supplier; /** * From b3ce26c8f8f2d14f9d8f8401a9dea4b9b2b4fb0d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:13:29 +0200 Subject: [PATCH 12/84] use Supplier from java instead if guava Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/cgmes/model/NamespaceReader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/NamespaceReader.java b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/NamespaceReader.java index c26af3a353e..373eccc68a6 100644 --- a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/NamespaceReader.java +++ b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/NamespaceReader.java @@ -8,7 +8,6 @@ package com.powsybl.cgmes.model; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.xml.XmlUtil; @@ -19,6 +18,7 @@ import java.io.InputStream; import java.util.HashSet; import java.util.Set; +import java.util.function.Supplier; /** * @author Luma ZamarreƱo {@literal } From 9867b6dbfc385974269a52128ff26783a069bafa Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:13:53 +0200 Subject: [PATCH 13/84] ParsingContext declared final Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/cgmes/model/FullModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java index 52b8b6c5971..cd37c9cacd5 100644 --- a/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java +++ b/cgmes/cgmes-model/src/main/java/com/powsybl/cgmes/model/FullModel.java @@ -119,7 +119,7 @@ public String toString() { ')'; } - private static class ParsingContext { + private static final class ParsingContext { private String id; From 67923635327dde9b05cea9b91f0a98d10d6a67b3 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:18:37 +0200 Subject: [PATCH 14/84] XmlStaxContext declared final Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/cim/CimAnonymizer.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java b/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java index 5b1fd5a804c..cddfe098409 100644 --- a/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java +++ b/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java @@ -7,7 +7,6 @@ */ package com.powsybl.cim; -import com.google.common.collect.ImmutableSet; import com.powsybl.commons.PowsyblException; import com.powsybl.commons.exceptions.UncheckedXmlStreamException; import com.powsybl.commons.util.StringAnonymizer; @@ -52,9 +51,9 @@ public void logSkipped(Set skipped) { } } - private static final Set NAMES_TO_EXCLUDE = ImmutableSet.of("PATL", "TATL"); + private static final Set NAMES_TO_EXCLUDE = Set.of("PATL", "TATL"); - private static final Set DESCRIPTIONS_TO_EXCLUDE = ImmutableSet.of(); + private static final Set DESCRIPTIONS_TO_EXCLUDE = Set.of(); private static final String RDF_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; @@ -64,7 +63,7 @@ public void logSkipped(Set skipped) { private static final QName RDF_RESOURCE = new QName(RDF_URI, "resource"); private static final QName RDF_ABOUT = new QName(RDF_URI, "about"); - private static class XmlStaxContext { + private static final class XmlStaxContext { private final XMLInputFactory inputFactory = XMLInputFactory.newFactory(); private final XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); private final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); From 266e3379fd1f13f77628ec1b99305287f36c73b2 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:21:51 +0200 Subject: [PATCH 15/84] replaced deprecated method for ZipFile with SeekableByteChannel Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/cim/CimAnonymizer.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java b/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java index cddfe098409..47a595ea13b 100644 --- a/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java +++ b/cim-anonymiser/src/main/java/com/powsybl/cim/CimAnonymizer.java @@ -292,7 +292,9 @@ public void anonymizeZip(Path cimZipFile, Path anonymizedCimFileDir, Path dictio StringAnonymizer dictionary = loadDic(dictionaryFile); // anonymize each file of the archive - try (ZipFile zipFileData = new ZipFile(Files.newByteChannel(cimZipFile))) { + try (ZipFile zipFileData = ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(cimZipFile)) + .get()) { Set rdfIdValues = skipExternalRef ? getRdfIdValues(zipFileData) : null; From 1a38ad61a43efb4a92baf36b0eb55884d878a72a Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:31:46 +0200 Subject: [PATCH 16/84] swapped from deprecated org.apache.commons.compress.utils.IOUtils to org.apache.commons.io.IOUtils Signed-off-by: Nicolas Rol --- .../powsybl/commons/compress/ZipPackager.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/compress/ZipPackager.java b/commons/src/main/java/com/powsybl/commons/compress/ZipPackager.java index 60fb7e8b124..64ed6b2e3d8 100644 --- a/commons/src/main/java/com/powsybl/commons/compress/ZipPackager.java +++ b/commons/src/main/java/com/powsybl/commons/compress/ZipPackager.java @@ -9,7 +9,7 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.io.IOUtils; import javax.annotation.Nullable; import java.io.*; @@ -75,7 +75,7 @@ public ZipPackager addPaths(Path baseDir, List filenames) { } /** - * @param baseDir the base directory of all files + * @param root the base directory of all files * @param filenames all files to add in zip bytes * @return a reference to this object */ @@ -85,8 +85,8 @@ public ZipPackager addPaths(Path root, String... filenames) { /** * Key as zip entry name. Both key and content must not be null. - * @param key - * @param content + * @param key entry name + * @param content entry content * @return a reference to this object */ public ZipPackager addString(String key, String content) { @@ -95,8 +95,8 @@ public ZipPackager addString(String key, String content) { /** * Key as zip entry name. Both key and content must not be null. - * @param key - * @param content + * @param key entry name + * @param content entry content * @param charset be used to encode content * @return a reference to this object */ @@ -109,8 +109,8 @@ public ZipPackager addString(String key, String content, Charset charset) { /** * Key as zip entry name. Both key and bytes must not be null. - * @param key - * @param bytes + * @param key entry name + * @param bytes entry content * @return a reference to this object */ public ZipPackager addBytes(String key, byte[] bytes) { From 0afcfbcaba9a5666db55fe5dbfc084049dfed9af Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:36:48 +0200 Subject: [PATCH 17/84] removed deprecated .newInstance method call Signed-off-by: Nicolas Rol --- .../powsybl/commons/config/ComponentDefaultConfig.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java b/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java index 889976c1cb9..48bd2bb5698 100644 --- a/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java +++ b/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java @@ -11,6 +11,7 @@ import com.powsybl.commons.exceptions.UncheckedIllegalAccessException; import com.powsybl.commons.exceptions.UncheckedInstantiationException; +import java.lang.reflect.InvocationTargetException; import java.util.Objects; /** @@ -69,22 +70,26 @@ public Class findFactoryImplClass(Class factory @Override public T newFactoryImpl(Class factoryBaseClass) { try { - return findFactoryImplClass(factoryBaseClass).newInstance(); + return findFactoryImplClass(factoryBaseClass).getDeclaredConstructor().newInstance(); } catch (IllegalAccessException e) { throw new UncheckedIllegalAccessException(e); } catch (InstantiationException e) { throw new UncheckedInstantiationException(e); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new PowsyblException(e); } } @Override public T newFactoryImpl(Class factoryBaseClass, Class defaultFactoryImplClass) { try { - return findFactoryImplClass(factoryBaseClass, defaultFactoryImplClass).newInstance(); + return findFactoryImplClass(factoryBaseClass, defaultFactoryImplClass).getDeclaredConstructor().newInstance(); } catch (IllegalAccessException e) { throw new UncheckedIllegalAccessException(e); } catch (InstantiationException e) { throw new UncheckedInstantiationException(e); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new PowsyblException(e); } } } From e81dc90b15fb3cf74cd00cd999e5043be4a9edfa Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 11:40:16 +0200 Subject: [PATCH 18/84] EmptyModuleConfigRepository declared final Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/commons/config/PlatformConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java b/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java index 6db26116ed6..26aafeebf38 100644 --- a/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java +++ b/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java @@ -120,7 +120,7 @@ public Optional getOptionalModuleConfig(String name) { return getRepository().getModuleConfig(name); } - private static class EmptyModuleConfigRepository implements ModuleConfigRepository { + private static final class EmptyModuleConfigRepository implements ModuleConfigRepository { @Override public Optional getModuleConfig(String name) { return Optional.empty(); From 8541b773a3f639a7a129247d2f12370561f8cfc5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 12:52:59 +0200 Subject: [PATCH 19/84] removed old deprecated methods + replaced guava supplier by java supplier Signed-off-by: Nicolas Rol --- .../commons/config/PlatformConfig.java | 29 ++----------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java b/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java index 26aafeebf38..98f6dd460a2 100644 --- a/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java +++ b/commons/src/main/java/com/powsybl/commons/config/PlatformConfig.java @@ -7,7 +7,6 @@ */ package com.powsybl.commons.config; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.powsybl.commons.PowsyblException; @@ -20,6 +19,7 @@ import java.util.Objects; import java.util.Optional; import java.util.ServiceLoader; +import java.util.function.Supplier; /** * @@ -35,14 +35,6 @@ public class PlatformConfig { protected final Supplier repositorySupplier; - /** - * @deprecated Directly pass PlatformConfig instance to the code you want to test. - */ - @Deprecated(since = "2.2.0") - public static synchronized void setDefaultConfig(PlatformConfig defaultConfig) { - PlatformConfig.defaultConfig = defaultConfig; - } - /** * Loads a {@link ModuleConfigRepository} from a single directory. * Reads from yaml file if it exists, else from xml file, else from properties file. @@ -88,7 +80,8 @@ public PlatformConfig(ModuleConfigRepository repository, Path configDir) { } protected PlatformConfig(Supplier repositorySupplier, Path configDir) { - this.repositorySupplier = Suppliers.memoize(Objects.requireNonNull(repositorySupplier)); + Objects.requireNonNull(repositorySupplier); + this.repositorySupplier = Suppliers.memoize(repositorySupplier::get); this.configDir = configDir; } @@ -100,22 +93,6 @@ protected ModuleConfigRepository getRepository() { return Objects.requireNonNull(repositorySupplier.get()); } - /** - * @deprecated Use the Optional returned by {@link #getOptionalModuleConfig(String)} - */ - @Deprecated(since = "4.9.0") - public boolean moduleExists(String name) { - return getOptionalModuleConfig(name).isPresent(); - } - - /** - * @deprecated Use {@link #getOptionalModuleConfig(String)} instead - */ - @Deprecated(since = "4.9.0") - public ModuleConfig getModuleConfig(String name) { - return getRepository().getModuleConfig(name).orElseThrow(() -> new PowsyblException("Module " + name + " not found")); - } - public Optional getOptionalModuleConfig(String name) { return getRepository().getModuleConfig(name); } From d836935b3c6d658addec89d02fabdcce29e08a3b Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 12:55:31 +0200 Subject: [PATCH 20/84] replaced deprecated Zipfile constructor by builder Signed-off-by: Nicolas Rol --- .../commons/datasource/ZipFileDataSource.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/datasource/ZipFileDataSource.java b/commons/src/main/java/com/powsybl/commons/datasource/ZipFileDataSource.java index 69587c56a96..a5e01f9b2e7 100644 --- a/commons/src/main/java/com/powsybl/commons/datasource/ZipFileDataSource.java +++ b/commons/src/main/java/com/powsybl/commons/datasource/ZipFileDataSource.java @@ -79,7 +79,9 @@ public boolean exists(String suffix, String ext) throws IOException { private static boolean entryExists(Path zipFilePath, String fileName) { if (Files.exists(zipFilePath)) { - try (ZipFile zipFile = new ZipFile(Files.newByteChannel(zipFilePath))) { + try (ZipFile zipFile = ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(zipFilePath)) + .get()) { return zipFile.getEntry(fileName) != null; } catch (IOException e) { return false; @@ -122,7 +124,9 @@ public InputStream newInputStream(String fileName) throws IOException { Objects.requireNonNull(fileName); Path zipFilePath = getZipFilePath(); if (entryExists(zipFilePath, fileName)) { - InputStream is = new ZipEntryInputStream(new ZipFile(Files.newByteChannel(zipFilePath)), fileName); + InputStream is = new ZipEntryInputStream(ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(zipFilePath)) + .get(), fileName); return observer != null ? new ObservableInputStream(is, zipFilePath + ":" + fileName, observer) : is; } return null; @@ -158,7 +162,9 @@ public void close() throws IOException { // copy existing entries if (Files.exists(zipFilePath)) { - try (ZipFile zipFile = new ZipFile(Files.newByteChannel(zipFilePath))) { + try (ZipFile zipFile = ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(zipFilePath)) + .get()) { Enumeration e = zipFile.getEntries(); while (e.hasMoreElements()) { ZipArchiveEntry zipEntry = e.nextElement(); @@ -207,7 +213,9 @@ public Set listNames(String regex) throws IOException { Pattern p = Pattern.compile(regex); Set names = new HashSet<>(); Path zipFilePath = getZipFilePath(); - try (ZipFile zipFile = new ZipFile(Files.newByteChannel(zipFilePath))) { + try (ZipFile zipFile = ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(zipFilePath)) + .get()) { Enumeration e = zipFile.getEntries(); while (e.hasMoreElements()) { ZipArchiveEntry zipEntry = e.nextElement(); From 59fd06eb67b162ffe9696d86da196dd1755fa490 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:08:10 +0200 Subject: [PATCH 21/84] replaced supplier Signed-off-by: Nicolas Rol --- .../com/powsybl/commons/json/JsonUtil.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java index 2604dacebe9..a0b6450e668 100644 --- a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java +++ b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java @@ -7,13 +7,12 @@ */ package com.powsybl.commons.json; -import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.json.JsonMapper; import com.google.common.base.Strings; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.PowsyblException; import com.powsybl.commons.extensions.Extendable; @@ -27,7 +26,9 @@ import java.nio.file.Path; import java.util.*; import java.util.function.Consumer; -import java.util.function.Function; +import java.util.function.Supplier; + +import static com.fasterxml.jackson.core.JsonToken.*; /** * @author Mathieu Bague {@literal } @@ -348,11 +349,11 @@ public static List> updateExtensions(JsonPar Objects.requireNonNull(supplier); List> extensions = new ArrayList<>(); - if (parser.currentToken() != JsonToken.START_OBJECT) { + if (parser.currentToken() != com.fasterxml.jackson.core.JsonToken.START_OBJECT) { throw new PowsyblException("Error updating extensions, \"extensions\" field expected START_OBJECT, got " + parser.currentToken()); } - while (parser.nextToken() != JsonToken.END_OBJECT) { + while (parser.nextToken() != END_OBJECT) { Extension extension = updateExtension(parser, context, supplier, extensionsNotFound, extendable); if (extension != null) { extensions.add(extension); @@ -396,11 +397,11 @@ public static List> readExtensions(JsonParse Objects.requireNonNull(context); Objects.requireNonNull(supplier); List> extensions = new ArrayList<>(); - if (parser.currentToken() != JsonToken.START_OBJECT) { + if (parser.currentToken() != START_OBJECT) { throw new PowsyblException("Error reading extensions, \"extensions\" field expected START_OBJECT, got " + parser.currentToken()); } - while (parser.nextToken() != JsonToken.END_OBJECT) { + while (parser.nextToken() != END_OBJECT) { Extension extension = readExtension(parser, context, supplier, extensionsNotFound); if (extension != null) { extensions.add(extension); @@ -508,13 +509,13 @@ public static void parseObject(JsonParser parser, boolean polymorphic, FieldHand token = parser.nextToken(); } while (token != null) { - if (token == JsonToken.FIELD_NAME) { + if (token == FIELD_NAME) { String fieldName = parser.getCurrentName(); boolean found = fieldHandler.onField(fieldName); if (!found) { throw new PowsyblException("Unexpected field " + fieldName); } - } else if (token == JsonToken.END_OBJECT) { + } else if (token == END_OBJECT) { break; } else { throw new PowsyblException(UNEXPECTED_TOKEN + token); From d7a666211e10ab2e1037368cabc2ca39b755d3d5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:13:45 +0200 Subject: [PATCH 22/84] fix Signed-off-by: Nicolas Rol --- .../java/com/powsybl/commons/json/JsonUtil.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java index a0b6450e668..4a62f48422e 100644 --- a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java +++ b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java @@ -7,7 +7,7 @@ */ package com.powsybl.commons.json; -import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.databind.*; @@ -26,10 +26,9 @@ import java.nio.file.Path; import java.util.*; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Supplier; -import static com.fasterxml.jackson.core.JsonToken.*; - /** * @author Mathieu Bague {@literal } */ @@ -353,7 +352,7 @@ public static List> updateExtensions(JsonPar throw new PowsyblException("Error updating extensions, \"extensions\" field expected START_OBJECT, got " + parser.currentToken()); } - while (parser.nextToken() != END_OBJECT) { + while (parser.nextToken() != JsonToken.END_OBJECT) { Extension extension = updateExtension(parser, context, supplier, extensionsNotFound, extendable); if (extension != null) { extensions.add(extension); @@ -397,11 +396,11 @@ public static List> readExtensions(JsonParse Objects.requireNonNull(context); Objects.requireNonNull(supplier); List> extensions = new ArrayList<>(); - if (parser.currentToken() != START_OBJECT) { + if (parser.currentToken() != JsonToken.START_OBJECT) { throw new PowsyblException("Error reading extensions, \"extensions\" field expected START_OBJECT, got " + parser.currentToken()); } - while (parser.nextToken() != END_OBJECT) { + while (parser.nextToken() != JsonToken.END_OBJECT) { Extension extension = readExtension(parser, context, supplier, extensionsNotFound); if (extension != null) { extensions.add(extension); @@ -501,7 +500,7 @@ public static void parseObject(JsonParser parser, boolean polymorphic, FieldHand Objects.requireNonNull(parser); Objects.requireNonNull(fieldHandler); try { - JsonToken token = parser.currentToken(); + com.fasterxml.jackson.core.JsonToken token = parser.currentToken(); if (!polymorphic && token != JsonToken.START_OBJECT) { throw new PowsyblException("Start object token was expected instead got: " + token); } @@ -509,13 +508,13 @@ public static void parseObject(JsonParser parser, boolean polymorphic, FieldHand token = parser.nextToken(); } while (token != null) { - if (token == FIELD_NAME) { + if (token == JsonToken.FIELD_NAME) { String fieldName = parser.getCurrentName(); boolean found = fieldHandler.onField(fieldName); if (!found) { throw new PowsyblException("Unexpected field " + fieldName); } - } else if (token == END_OBJECT) { + } else if (token == JsonToken.END_OBJECT) { break; } else { throw new PowsyblException(UNEXPECTED_TOKEN + token); From 06cbf2c1e987ff267de0521bd1bbfbc019561440 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:14:16 +0200 Subject: [PATCH 23/84] fix Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/commons/json/JsonUtil.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java index 4a62f48422e..7ca6119cfe6 100644 --- a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java +++ b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java @@ -7,7 +7,11 @@ */ package com.powsybl.commons.json; -import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonFactoryBuilder; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.databind.*; From 0e3d1b712be869c0743b2017ba3661b8bf8456bb Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:15:18 +0200 Subject: [PATCH 24/84] fix StandardCharsets.UTF_8 Signed-off-by: Nicolas Rol --- .../java/com/powsybl/commons/util/StringToIntMapper.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java index fd67efc8e6c..7fc187736ce 100644 --- a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java +++ b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.EnumMap; @@ -112,7 +113,7 @@ public synchronized void dump(Writer writer) throws IOException { } public void dump(Path file) throws IOException { - try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("UTF-8"))) { + try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { dump(writer); } } @@ -136,7 +137,7 @@ public synchronized void load(BufferedReader reader) throws IOException { } public void load(Path file) throws IOException { - try (BufferedReader reader = Files.newBufferedReader(file, Charset.forName("UTF-8"))) { + try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { load(reader); } } From 4e1cf4a5bcb062bd7ba5abe949d2cf25d70a4afa Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:15:59 +0200 Subject: [PATCH 25/84] fix Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/commons/util/StringToIntMapper.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java index 7fc187736ce..d8840a6c633 100644 --- a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java +++ b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java @@ -16,7 +16,6 @@ import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -146,7 +145,7 @@ public synchronized void reset(S subset) { if (subset == null) { throw new IllegalArgumentException("subset is null"); } - id2num.put(subset, HashBiMap.create()); + id2num.put(subset, HashBiMap.create()); counter.put(subset, subset.getInitialValue()); } From 7a8c0ebe29a7f656ad480f7006da085d9adab358 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:16:30 +0200 Subject: [PATCH 26/84] fix Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/commons/util/StringToIntMapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java index d8840a6c633..57555a3f1ed 100644 --- a/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java +++ b/commons/src/main/java/com/powsybl/commons/util/StringToIntMapper.java @@ -41,7 +41,7 @@ public StringToIntMapper(Class clazz) { id2num = new EnumMap<>(clazz); counter = new EnumMap<>(clazz); for (S s : clazz.getEnumConstants()) { - id2num.put(s, HashBiMap.create()); + id2num.put(s, HashBiMap.create()); counter.put(s, s.getInitialValue()); } } From af70c7f5b433344586bddd1502e555c540cc72be Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:17:42 +0200 Subject: [PATCH 27/84] replace supplier Signed-off-by: Nicolas Rol --- commons/src/main/java/com/powsybl/commons/xml/XmlReader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commons/src/main/java/com/powsybl/commons/xml/XmlReader.java b/commons/src/main/java/com/powsybl/commons/xml/XmlReader.java index bb84ff06e69..5a67d594e79 100644 --- a/commons/src/main/java/com/powsybl/commons/xml/XmlReader.java +++ b/commons/src/main/java/com/powsybl/commons/xml/XmlReader.java @@ -7,7 +7,6 @@ */ package com.powsybl.commons.xml; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.PowsyblException; import com.powsybl.commons.exceptions.UncheckedXmlStreamException; @@ -20,6 +19,7 @@ import javax.xml.stream.XMLStreamReader; import java.io.InputStream; import java.util.*; +import java.util.function.Supplier; /** * @author Geoffroy Jamgotchian {@literal } From 05235c009eb0d77a653884b22aadc425c02ed6ac Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:19:44 +0200 Subject: [PATCH 28/84] replace ZipFile by builder Signed-off-by: Nicolas Rol --- .../powsybl/computation/local/LocalComputationManager.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/computation-local/src/main/java/com/powsybl/computation/local/LocalComputationManager.java b/computation-local/src/main/java/com/powsybl/computation/local/LocalComputationManager.java index 5881d622bb4..5e9606747ac 100644 --- a/computation-local/src/main/java/com/powsybl/computation/local/LocalComputationManager.java +++ b/computation-local/src/main/java/com/powsybl/computation/local/LocalComputationManager.java @@ -218,7 +218,9 @@ private void preProcess(Path workingDir, Command command, int executionIndex) th break; case ARCHIVE_UNZIP: // extract the archive - try (ZipFile zipFile = new ZipFile(Files.newByteChannel(path))) { + try (ZipFile zipFile = ZipFile.builder() + .setSeekableByteChannel(Files.newByteChannel(path)) + .get()) { for (ZipArchiveEntry ze : Collections.list(zipFile.getEntries())) { Files.copy(zipFile.getInputStream(zipFile.getEntry(ze.getName())), workingDir.resolve(ze.getName()), REPLACE_EXISTING); } From afe04ce65ee9475954dc44b4e616e2277ed61641 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:39:02 +0200 Subject: [PATCH 29/84] catch Exception instead of Throwable Signed-off-by: Nicolas Rol --- .../java/com/powsybl/computation/CompletableFutureTask.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/computation/src/main/java/com/powsybl/computation/CompletableFutureTask.java b/computation/src/main/java/com/powsybl/computation/CompletableFutureTask.java index 5a58fdd5e2e..806edd34f79 100644 --- a/computation/src/main/java/com/powsybl/computation/CompletableFutureTask.java +++ b/computation/src/main/java/com/powsybl/computation/CompletableFutureTask.java @@ -45,13 +45,11 @@ public void run() { future.run(); try { complete(future.get()); - } catch (ExecutionException exc) { - completeExceptionally(exc.getCause()); } catch (InterruptedException exc) { Thread.currentThread().interrupt(); completeExceptionally(exc); - } catch (Throwable exc) { - completeExceptionally(exc); + } catch (Exception exc) { + completeExceptionally(exc.getCause()); } } From f5ef925feaecaed9d4b85e552ae1ff812dd3a082 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:55:39 +0200 Subject: [PATCH 30/84] group logic in createComputationManager for shortTime and longTime computationManager Signed-off-by: Nicolas Rol --- .../DefaultComputationManagerConfig.java | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java b/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java index 2242fd79755..20f1845b641 100644 --- a/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java +++ b/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java @@ -7,13 +7,16 @@ */ package com.powsybl.computation; +import com.powsybl.commons.PowsyblException; import com.powsybl.commons.config.PlatformConfig; +import com.powsybl.commons.exceptions.UncheckedClassCastExceptionException; import com.powsybl.commons.exceptions.UncheckedClassNotFoundException; import com.powsybl.commons.exceptions.UncheckedIllegalAccessException; import com.powsybl.commons.exceptions.UncheckedInstantiationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.lang.reflect.InvocationTargetException; import java.util.Objects; /** @@ -44,6 +47,7 @@ public static DefaultComputationManagerConfig load() { return load(PlatformConfig.defaultConfig()); } + @SuppressWarnings("unchecked") public static DefaultComputationManagerConfig load(PlatformConfig platformConfig) { Objects.requireNonNull(platformConfig); DefaultComputationManagerConfig config = platformConfig.getOptionalModuleConfig("default-computation-manager") @@ -58,6 +62,8 @@ public static DefaultComputationManagerConfig load(PlatformConfig platformConfig shortTimeExecutionComputationManagerFactoryClass = (Class) Class.forName(DEFAULT_SHORT_TIME_EXECUTION_COMPUTATION_MANAGER_FACTORY_CLASS); } catch (ClassNotFoundException e) { throw new UncheckedClassNotFoundException(e); + } catch (ClassCastException e) { + throw new UncheckedClassCastExceptionException(e); } return new DefaultComputationManagerConfig(shortTimeExecutionComputationManagerFactoryClass, null); }); @@ -67,39 +73,33 @@ public static DefaultComputationManagerConfig load(PlatformConfig platformConfig return config; } - public ComputationManager createShortTimeExecutionComputationManager() { + private ComputationManager createComputationManager(Class computationManagerFactoryClass) { try { - return new LazyCreatedComputationManager(shortTimeExecutionComputationManagerFactoryClass.newInstance()); + return new LazyCreatedComputationManager(computationManagerFactoryClass.getDeclaredConstructor().newInstance()); } catch (InstantiationException e) { throw new UncheckedInstantiationException(e); } catch (IllegalAccessException e) { throw new UncheckedIllegalAccessException(e); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new PowsyblException(e); } } + public ComputationManager createShortTimeExecutionComputationManager() { + return createComputationManager(shortTimeExecutionComputationManagerFactoryClass); + } + public ComputationManager createLongTimeExecutionComputationManager() { - if (longTimeExecutionComputationManagerFactoryClass != null) { - try { - return new LazyCreatedComputationManager(longTimeExecutionComputationManagerFactoryClass.newInstance()); - } catch (InstantiationException e) { - throw new UncheckedInstantiationException(e); - } catch (IllegalAccessException e) { - throw new UncheckedIllegalAccessException(e); - } - } else { - return createShortTimeExecutionComputationManager(); - } + return longTimeExecutionComputationManagerFactoryClass == null ? + createShortTimeExecutionComputationManager() : + createComputationManager(longTimeExecutionComputationManagerFactoryClass); } @Override public String toString() { String str = "DefaultComputationManagerConfig(shortTimeExecutionComputationManagerFactoryClass=" + shortTimeExecutionComputationManagerFactoryClass.getName() + ", longTimeExecutionComputationManagerFactoryClass="; - if (longTimeExecutionComputationManagerFactoryClass != null) { - str += longTimeExecutionComputationManagerFactoryClass.getName(); - } else { - str += shortTimeExecutionComputationManagerFactoryClass.getName(); - } + str += Objects.requireNonNullElse(longTimeExecutionComputationManagerFactoryClass, shortTimeExecutionComputationManagerFactoryClass).getName(); str += ")"; return str; } From 64af21174bbb7d737938215f6435aaabe26b7296 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 13:56:37 +0200 Subject: [PATCH 31/84] replace supplier Signed-off-by: Nicolas Rol --- .../com/powsybl/contingency/json/ContingencyDeserializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contingency/contingency-api/src/main/java/com/powsybl/contingency/json/ContingencyDeserializer.java b/contingency/contingency-api/src/main/java/com/powsybl/contingency/json/ContingencyDeserializer.java index 0ff70601261..9c2720a0ec2 100644 --- a/contingency/contingency-api/src/main/java/com/powsybl/contingency/json/ContingencyDeserializer.java +++ b/contingency/contingency-api/src/main/java/com/powsybl/contingency/json/ContingencyDeserializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.Extension; import com.powsybl.commons.extensions.ExtensionJsonSerializer; @@ -23,6 +22,7 @@ import java.io.IOException; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; /** * From b66d0475dca3f567c2bb2eff4b6d80ffb74f3a22 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 14:40:16 +0200 Subject: [PATCH 32/84] remove deprecated methods in PlatformConfigNamedProvider Signed-off-by: Nicolas Rol --- .../config/PlatformConfigNamedProvider.java | 50 ++----------------- .../dynamicsimulation/DynamicSimulation.java | 2 +- .../java/com/powsybl/loadflow/LoadFlow.java | 2 +- 3 files changed, 7 insertions(+), 47 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/config/PlatformConfigNamedProvider.java b/commons/src/main/java/com/powsybl/commons/config/PlatformConfigNamedProvider.java index acf59ae8a11..9931515b3be 100644 --- a/commons/src/main/java/com/powsybl/commons/config/PlatformConfigNamedProvider.java +++ b/commons/src/main/java/com/powsybl/commons/config/PlatformConfigNamedProvider.java @@ -10,12 +10,7 @@ import com.google.common.collect.Lists; import com.powsybl.commons.PowsyblException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.ServiceLoader; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @@ -54,13 +49,12 @@ default String getPlatformConfigName() { * @author Jon harper {@literal } * @author Geoffroy Jamgotchian {@literal } */ - static final class Finder { + final class Finder { private Finder() { } private static final String DEFAULT_SERVICE_IMPL_NAME_PROPERTY = "default-impl-name"; - private static final String LEGACY_SERVICE_IMPL_NAME_PROPERTY = "default"; private static final Map, List> PROVIDERS = new ConcurrentHashMap<>(); @@ -74,7 +68,7 @@ private Finder() { public static T findDefault(String moduleName, Class clazz, PlatformConfig platformConfig) { return find(null, moduleName, - Arrays.asList(DEFAULT_SERVICE_IMPL_NAME_PROPERTY), clazz, + List.of(DEFAULT_SERVICE_IMPL_NAME_PROPERTY), clazz, platformConfig); } @@ -87,44 +81,10 @@ public static T findDefault(String modul public static T find(String name, String moduleName, Class clazz, PlatformConfig platformConfig) { return find(name, moduleName, - Arrays.asList(DEFAULT_SERVICE_IMPL_NAME_PROPERTY), clazz, + List.of(DEFAULT_SERVICE_IMPL_NAME_PROPERTY), clazz, platformConfig); } - /** - * Find the default provider configured in the standard field or the legacy - * field of {@code moduleName} in {@code platformConfig} among the - * {@code providers} arguments based on its name. - * - * @deprecated Use {@link #findDefault} instead - * - * @return the provider - */ - @Deprecated(since = "3.2.0") - public static T findDefaultBackwardsCompatible( - String moduleName, Class clazz, PlatformConfig platformConfig) { - return find(null, moduleName, - Arrays.asList(DEFAULT_SERVICE_IMPL_NAME_PROPERTY, - LEGACY_SERVICE_IMPL_NAME_PROPERTY), clazz, platformConfig); - } - - /** - * Find the provider among the {@code providers} based on its {@code name}, or - * if {@code name} is null find the default provider like @{link - * findDefaultBackwardsCompatible} - * - * @deprecated Use {@link #find} instead - * - * @return the provider - */ - @Deprecated(since = "3.2.0") - public static T findBackwardsCompatible(String name, - String moduleName, Class clazz, PlatformConfig platformConfig) { - return find(name, moduleName, - Arrays.asList(DEFAULT_SERVICE_IMPL_NAME_PROPERTY, LEGACY_SERVICE_IMPL_NAME_PROPERTY), - clazz, platformConfig); - } - private static Optional getOptionalFirstProperty(ModuleConfig moduleConfig, List propertyNames) { return propertyNames.stream() @@ -173,7 +133,7 @@ static T find(String name, T provider; if (providers.size() == 1 && finalName == null) { // no information to select the implementation but only one provider, so we can - // use it by default (that is be the most common use case) + // use it by default (that is the most common use case) provider = providers.get(0); } else { if (providers.size() > 1 && finalName == null) { diff --git a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulation.java b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulation.java index 3e106d4d231..fc542eb4e61 100644 --- a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulation.java +++ b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulation.java @@ -131,7 +131,7 @@ public String getVersion() { } public static Runner find(String name) { - return new Runner(PlatformConfigNamedProvider.Finder.findBackwardsCompatible(name, + return new Runner(PlatformConfigNamedProvider.Finder.find(name, "dynamic-simulation", DynamicSimulationProvider.class, PlatformConfig.defaultConfig())); } diff --git a/loadflow/loadflow-api/src/main/java/com/powsybl/loadflow/LoadFlow.java b/loadflow/loadflow-api/src/main/java/com/powsybl/loadflow/LoadFlow.java index 7fc36742b9e..c73b697ccb5 100644 --- a/loadflow/loadflow-api/src/main/java/com/powsybl/loadflow/LoadFlow.java +++ b/loadflow/loadflow-api/src/main/java/com/powsybl/loadflow/LoadFlow.java @@ -108,7 +108,7 @@ public String getVersion() { */ public static Runner find(String name) { return new Runner(PlatformConfigNamedProvider.Finder - .findBackwardsCompatible(name, "load-flow", LoadFlowProvider.class, + .find(name, "load-flow", LoadFlowProvider.class, PlatformConfig.defaultConfig())); } From e7d471b085e1c2dd30581d86b906e860f5cf0c2e Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 14:44:35 +0200 Subject: [PATCH 33/84] clean DynamicSimulationParameters Signed-off-by: Nicolas Rol --- .../dynamicsimulation/DynamicSimulationParameters.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java index cb3d6420aa5..c5bd9826355 100644 --- a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java +++ b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java @@ -9,10 +9,9 @@ import java.util.Map; import java.util.Objects; +import java.util.function.Supplier; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; import com.powsybl.commons.config.PlatformConfig; import com.powsybl.commons.extensions.AbstractExtendable; import com.powsybl.commons.extensions.Extension; @@ -110,7 +109,6 @@ public int getStartTime() { * * @param startTime instant of time at which the dynamic simulation begins, in * seconds - * @return */ public DynamicSimulationParameters setStartTime(int startTime) { if (startTime < 0) { @@ -128,7 +126,6 @@ public int getStopTime() { * * @param stopTime instant of time at which the dynamic simulation ends, in * seconds - * @return */ public DynamicSimulationParameters setStopTime(int stopTime) { if (stopTime <= startTime) { @@ -139,7 +136,7 @@ public DynamicSimulationParameters setStopTime(int stopTime) { } protected Map toMap() { - return ImmutableMap.of("startTime", startTime, + return Map.of("startTime", startTime, "stopTime", stopTime); } @@ -152,6 +149,7 @@ public String toString() { return toMap().toString(); } + @SuppressWarnings("unchecked") private void loadExtensions(PlatformConfig platformConfig) { for (ExtensionConfigLoader provider : SUPPLIER.get().getProviders()) { addExtension(provider.getExtensionClass(), provider.load(platformConfig)); From 5398858cd19bd795c9d823bf24ce56d09db68e70 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 14:45:39 +0200 Subject: [PATCH 34/84] replace supplier Signed-off-by: Nicolas Rol --- .../dynamicsimulation/json/JsonDynamicSimulationParameters.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/json/JsonDynamicSimulationParameters.java b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/json/JsonDynamicSimulationParameters.java index 9d4ea181edf..d6ea1a63354 100644 --- a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/json/JsonDynamicSimulationParameters.java +++ b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/json/JsonDynamicSimulationParameters.java @@ -14,6 +14,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; +import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -21,7 +22,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializerProvider; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.Extension; import com.powsybl.commons.extensions.ExtensionJsonSerializer; From 57d9ba1d0303a9a0f9e2b4d227084f57af5b7dc5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 14:58:58 +0200 Subject: [PATCH 35/84] clean Networks Signed-off-by: Nicolas Rol --- .../powsybl/iidm/network/util/Networks.java | 61 +++++++++---------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java index aff117d51c6..7fb39d275a2 100644 --- a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java +++ b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java @@ -8,7 +8,6 @@ */ package com.powsybl.iidm.network.util; -import com.google.common.collect.ImmutableMap; import com.powsybl.commons.io.table.AbstractTableFormatter; import com.powsybl.commons.io.table.AsciiTableFormatter; import com.powsybl.commons.io.table.Column; @@ -41,7 +40,7 @@ public static boolean isBusValid(int feederCount) { } public static Map getExecutionTags(Network network) { - return ImmutableMap.of("variant", network.getVariantManager().getWorkingVariantId()); + return Map.of("variant", network.getVariantManager().getWorkingVariantId()); } public static void dumpVariantId(Path workingDir, String variantId) throws IOException { @@ -58,8 +57,8 @@ public static void dumpVariantId(Path workingDir, Network network) throws IOExce static class ConnectedPower { private int busCount = 0; - private List connectedLoads = new ArrayList<>(); - private List disconnectedLoads = new ArrayList<>(); + private final List connectedLoads = new ArrayList<>(); + private final List disconnectedLoads = new ArrayList<>(); private double connectedLoadVolume = 0.0; private double disconnectedLoadVolume = 0.0; @@ -67,11 +66,11 @@ static class ConnectedPower { private double disconnectedMaxGeneration = 0.0; private double connectedGeneration = 0.0; private double disconnectedGeneration = 0.0; - private List connectedGenerators = new ArrayList<>(); - private List disconnectedGenerators = new ArrayList<>(); + private final List connectedGenerators = new ArrayList<>(); + private final List disconnectedGenerators = new ArrayList<>(); - private List connectedShunts = new ArrayList<>(); - private List disconnectedShunts = new ArrayList<>(); + private final List connectedShunts = new ArrayList<>(); + private final List disconnectedShunts = new ArrayList<>(); private double connectedShuntPositiveVolume = 0.0; private double disconnectedShuntPositiveVolume = 0.0; private double connectedShuntNegativeVolume = 0.0; @@ -266,18 +265,18 @@ private static String writeInTable(ConnectedPower balanceMainCC, ConnectedPower .writeCell(Double.toString(balanceOtherCC.connectedGeneration)) .writeCell(Double.toString(balanceOtherCC.disconnectedGeneration)); formatter.writeCell("Shunt at nom V (MVar)") - .writeCell(Double.toString(balanceMainCC.connectedShuntPositiveVolume) + " " + - Double.toString(balanceMainCC.connectedShuntNegativeVolume) + - " (" + Integer.toString(balanceMainCC.connectedShunts.size()) + ")") - .writeCell(Double.toString(balanceMainCC.disconnectedShuntPositiveVolume) + " " + - Double.toString(balanceMainCC.disconnectedShuntNegativeVolume) + - " (" + Integer.toString(balanceMainCC.disconnectedShunts.size()) + ")") - .writeCell(Double.toString(balanceOtherCC.connectedShuntPositiveVolume) + " " + - Double.toString(balanceOtherCC.connectedShuntNegativeVolume) + - " (" + Integer.toString(balanceOtherCC.connectedShunts.size()) + ")") - .writeCell(Double.toString(balanceOtherCC.disconnectedShuntPositiveVolume) + " " + - Double.toString(balanceOtherCC.disconnectedShuntNegativeVolume) + - " (" + Integer.toString(balanceOtherCC.disconnectedShunts.size()) + ")"); + .writeCell(balanceMainCC.connectedShuntPositiveVolume + " " + + balanceMainCC.connectedShuntNegativeVolume + + " (" + balanceMainCC.connectedShunts.size() + ")") + .writeCell(balanceMainCC.disconnectedShuntPositiveVolume + " " + + balanceMainCC.disconnectedShuntNegativeVolume + + " (" + balanceMainCC.disconnectedShunts.size() + ")") + .writeCell(balanceOtherCC.connectedShuntPositiveVolume + " " + + balanceOtherCC.connectedShuntNegativeVolume + + " (" + balanceOtherCC.connectedShunts.size() + ")") + .writeCell(balanceOtherCC.disconnectedShuntPositiveVolume + " " + + balanceOtherCC.disconnectedShuntNegativeVolume + + " (" + balanceOtherCC.disconnectedShunts.size() + ")"); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -322,7 +321,7 @@ public static void printGeneratorsSetpointDiff(Network network, Logger logger) { * Return the list of nodes (N/B topology) for each bus of a the Bus view * If a node is not associated to a bus, it is not included in any list. * @param voltageLevel The voltage level to traverse - * @return the list of nodes (N/B topology) for each bus of a Bus view + * @return a map with the list of nodes (N/B topology) for each bus of a Bus view */ public static Map> getNodesByBus(VoltageLevel voltageLevel) { checkNodeBreakerVoltageLevel(voltageLevel); @@ -351,26 +350,24 @@ public static Map> getNodesByBus(VoltageLevel voltageLevel) return nodesByBus; } + private static void addBusFromTerminal(String busId, Terminal terminal, Function getBusFromTerminal, Set nodes, int node) { + Bus bus = getBusFromTerminal.apply(terminal); + if (bus != null && bus.getId().equals(busId)) { + nodes.add(node); + } + } + public static IntStream getNodes(String busId, VoltageLevel voltageLevel, Function getBusFromTerminal) { checkNodeBreakerVoltageLevel(voltageLevel); Set nodes = new TreeSet<>(); for (int i : voltageLevel.getNodeBreakerView().getNodes()) { Terminal terminal = voltageLevel.getNodeBreakerView().getTerminal(i); if (terminal != null) { - Bus bus = getBusFromTerminal.apply(terminal); - if (bus != null && bus.getId().equals(busId)) { - nodes.add(i); - } + addBusFromTerminal(busId, terminal, getBusFromTerminal, nodes, i); } else { // If there is no terminal for the current node, we try to find one traversing the topology Terminal equivalentTerminal = Networks.getEquivalentTerminal(voltageLevel, i); - - if (equivalentTerminal != null) { - Bus bus = getBusFromTerminal.apply(equivalentTerminal); - if (bus != null && bus.getId().equals(busId)) { - nodes.add(i); - } - } + addBusFromTerminal(busId, equivalentTerminal, getBusFromTerminal, nodes, i); } } return nodes.stream().mapToInt(Integer::intValue); From 6c1b6b7913a7a041204025324079cc261ca7f281 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:01:13 +0200 Subject: [PATCH 36/84] remove old deprecated methods in StandbyAutomaton Signed-off-by: Nicolas Rol --- .../network/extensions/StandbyAutomaton.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java index e35499f84d4..9c7b4e6da5d 100644 --- a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java +++ b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java @@ -46,27 +46,11 @@ default String getName() { */ double getHighVoltageSetpoint(); - /** - * @deprecated Use {@link #getHighVoltageSetpoint()} instead. - */ - @Deprecated(since = "4.11.0") - default float getHighVoltageSetPoint() { - return (float) getHighVoltageSetpoint(); - } - /** * Set the voltage setpoint (in kV) used when the high voltage threshold is reached. */ StandbyAutomaton setHighVoltageSetpoint(double highVoltageSetpoint); - /** - * @deprecated Use {@link #setHighVoltageSetpoint(double)} instead. - */ - @Deprecated(since = "4.11.0") - default StandbyAutomaton setHighVoltageSetPoint(float highVoltageSetpoint) { - return setHighVoltageSetpoint(highVoltageSetpoint); - } - /** * Get the high voltage threshold (in kV). Above this value, the static var compensator controls voltage at high voltage setpoint. */ From 85c9d4151df1b3e9de3e206ca56d8c9065c6a90f Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:02:02 +0200 Subject: [PATCH 37/84] remove old deprecated methods in StandbyAutomaton Signed-off-by: Nicolas Rol --- .../network/extensions/StandbyAutomaton.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java index 9c7b4e6da5d..04b471a8ad7 100644 --- a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java +++ b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomaton.java @@ -66,27 +66,11 @@ default String getName() { */ double getLowVoltageSetpoint(); - /** - * @deprecated Use {@link #getLowVoltageSetpoint()} instead. - */ - @Deprecated(since = "4.11.0") - default float getLowVoltageSetPoint() { - return (float) getLowVoltageSetpoint(); - } - /** * Set the voltage setpoint (in kV) used when the low voltage threshold is reached. */ StandbyAutomaton setLowVoltageSetpoint(double lowVoltageSetpoint); - /** - * @deprecated Use {@link #setLowVoltageSetpoint(double)} instead. - */ - @Deprecated(since = "4.11.0") - default StandbyAutomaton setLowVoltageSetPoint(float lowVoltageSetpoint) { - return setLowVoltageSetpoint(lowVoltageSetpoint); - } - /** * Get the low voltage threshold (in kV). Under this value, the static var compensator controls voltage at low voltage setpoint. */ From d7bfc1d57fcd4985f9c13a09417e265c771f392d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:04:11 +0200 Subject: [PATCH 38/84] remove old deprecated methods in StandbyAutomatonAdder Signed-off-by: Nicolas Rol --- .../extensions/StandbyAutomatonAdder.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomatonAdder.java b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomatonAdder.java index b647a34b142..b1c2ea2ef40 100644 --- a/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomatonAdder.java +++ b/iidm/iidm-extensions/src/main/java/com/powsybl/iidm/network/extensions/StandbyAutomatonAdder.java @@ -36,14 +36,6 @@ default Class getExtensionClass() { */ StandbyAutomatonAdder withHighVoltageSetpoint(double highVoltageSetpoint); - /** - * @deprecated Use {@link #withHighVoltageSetpoint(double)} instead. - */ - @Deprecated(since = "4.11.0") - default StandbyAutomatonAdder withHighVoltageSetPoint(float highVoltageSetpoint) { - return withHighVoltageSetpoint(highVoltageSetpoint); - } - /** * Define the high voltage threshold (in kV). Above this value, the static var compensator controls voltage at high voltage setpoint. */ @@ -54,14 +46,6 @@ default StandbyAutomatonAdder withHighVoltageSetPoint(float highVoltageSetpoint) */ StandbyAutomatonAdder withLowVoltageSetpoint(double lowVoltageSetpoint); - /** - * @deprecated Use {@link #withLowVoltageSetpoint(double)} instead. - */ - @Deprecated(since = "4.11.0") - default StandbyAutomatonAdder withLowVoltageSetPoint(float lowVoltageSetpoint) { - return withLowVoltageSetpoint(lowVoltageSetpoint); - } - /** * Define the low voltage threshold (in kV). Under this value, the static var compensator controls voltage at low voltage setpoint. */ From cb18318561b294e190cbdfd8fce6adad5b5ab554 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:05:52 +0200 Subject: [PATCH 39/84] Renamed "RL" to match the regular expression '^[A-Z][0-9]?$'. Signed-off-by: Nicolas Rol --- .../main/java/com/powsybl/iidm/network/impl/GeneratorImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorImpl.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorImpl.java index 696793ba7a9..26a85312c06 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorImpl.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorImpl.java @@ -235,7 +235,7 @@ public void setReactiveLimits(ReactiveLimits reactiveLimits) { } @Override - public RL getReactiveLimits(Class type) { + public R getReactiveLimits(Class type) { return reactiveLimits.getReactiveLimits(type); } From 920a3a1f239cbb138cb07cae4466a94684ab2b2c Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:07:51 +0200 Subject: [PATCH 40/84] Renamed "OWNER" to match the regular expression '^[A-Z][0-9]?$'. Signed-off-by: Nicolas Rol --- .../iidm/network/impl/MinMaxReactiveLimitsAdderImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MinMaxReactiveLimitsAdderImpl.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MinMaxReactiveLimitsAdderImpl.java index fff1b9afb52..2e0bff88a17 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MinMaxReactiveLimitsAdderImpl.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/MinMaxReactiveLimitsAdderImpl.java @@ -16,15 +16,15 @@ * @author Geoffroy Jamgotchian {@literal } * @author Mathieu Bague {@literal } */ -class MinMaxReactiveLimitsAdderImpl implements MinMaxReactiveLimitsAdder { +class MinMaxReactiveLimitsAdderImpl implements MinMaxReactiveLimitsAdder { - private final OWNER owner; + private final O owner; private double minQ = Double.NaN; private double maxQ = Double.NaN; - MinMaxReactiveLimitsAdderImpl(OWNER owner) { + MinMaxReactiveLimitsAdderImpl(O owner) { this.owner = owner; } From 2ee50553e9cba1eb0f6806667292cf614b9650a0 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:08:14 +0200 Subject: [PATCH 41/84] Renamed "OWNER" to match the regular expression '^[A-Z][0-9]?$'. Signed-off-by: Nicolas Rol --- .../iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java index 63c7ed1c6db..8936e14dedf 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java @@ -23,11 +23,11 @@ * @author Geoffroy Jamgotchian {@literal } * @author Mathieu Bague {@literal } */ -class ReactiveCapabilityCurveAdderImpl implements ReactiveCapabilityCurveAdder { +class ReactiveCapabilityCurveAdderImpl implements ReactiveCapabilityCurveAdder { private static final Logger LOGGER = LoggerFactory.getLogger(ReactiveCapabilityCurveAdderImpl.class); - private final OWNER owner; + private final O owner; private final TreeMap points = new TreeMap<>(); @@ -95,7 +95,7 @@ public ReactiveCapabilityCurveAdder endPoint() { } - ReactiveCapabilityCurveAdderImpl(OWNER owner) { + ReactiveCapabilityCurveAdderImpl(O owner) { this.owner = owner; } From 44955f578cff7455d9af95abac16df5c5c3921a8 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:11:07 +0200 Subject: [PATCH 42/84] fix ReactiveCapabilityCurveAdderImpl Signed-off-by: Nicolas Rol --- .../iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java index 8936e14dedf..05c71b9ee27 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/ReactiveCapabilityCurveAdderImpl.java @@ -31,7 +31,7 @@ class ReactiveCapabilityCurveAdderImpl points = new TreeMap<>(); - private class PointAdderImpl implements PointAdder { + private final class PointAdderImpl implements PointAdder { private double p = Double.NaN; @@ -100,7 +100,7 @@ public ReactiveCapabilityCurveAdder endPoint() { } @Override - public PointAdderImpl beginPoint() { + public PointAdder beginPoint() { return new PointAdderImpl(); } From 3f346eff0d959bce8036f556cd0359f115241e93 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:44:18 +0200 Subject: [PATCH 43/84] Rename "RL" to match the regular expression '^[A-Z][0-9]?$'. Signed-off-by: Nicolas Rol --- .../com/powsybl/iidm/network/impl/VscConverterStationImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/VscConverterStationImpl.java b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/VscConverterStationImpl.java index 3d8555cb28c..1c180baf985 100644 --- a/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/VscConverterStationImpl.java +++ b/iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/VscConverterStationImpl.java @@ -124,7 +124,7 @@ public ReactiveLimits getReactiveLimits() { } @Override - public RL getReactiveLimits(Class type) { + public L getReactiveLimits(Class type) { return reactiveLimits.getReactiveLimits(type); } From c58e61a4a1952d81c6bcef3d0b2dfad0fd7e6578 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 15:48:09 +0200 Subject: [PATCH 44/84] changed supplier Signed-off-by: Nicolas Rol --- .../java/com/powsybl/iidm/serde/AbstractTreeDataImporter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/AbstractTreeDataImporter.java b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/AbstractTreeDataImporter.java index 16307062650..621c93a5a43 100644 --- a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/AbstractTreeDataImporter.java +++ b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/AbstractTreeDataImporter.java @@ -8,7 +8,6 @@ package com.powsybl.iidm.serde; import com.google.common.base.Joiner; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.io.ByteStreams; import com.powsybl.commons.PowsyblException; @@ -36,6 +35,7 @@ import java.util.List; import java.util.Objects; import java.util.Properties; +import java.util.function.Supplier; import java.util.stream.Collectors; /** From d761eee213e58ac1dd05e59208842c73db61d9d6 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:00:19 +0200 Subject: [PATCH 45/84] extract closeAndUseGarbageCollector in XMLImporter Signed-off-by: Nicolas Rol --- .../com/powsybl/iidm/serde/XMLImporter.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/XMLImporter.java b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/XMLImporter.java index 2367c92525e..136814308bb 100644 --- a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/XMLImporter.java +++ b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/XMLImporter.java @@ -8,7 +8,6 @@ package com.powsybl.iidm.serde; import com.google.auto.service.AutoService; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.config.PlatformConfig; import com.powsybl.commons.datasource.ReadOnlyDataSource; @@ -23,6 +22,7 @@ import javax.xml.stream.XMLStreamReader; import java.io.IOException; import java.io.InputStream; +import java.util.function.Supplier; import java.util.stream.Stream; import static com.powsybl.iidm.serde.IidmSerDeConstants.CURRENT_IIDM_VERSION; @@ -79,12 +79,7 @@ protected boolean exists(ReadOnlyDataSource dataSource, String ext) throws IOExc } } } finally { - try { - xmlsr.close(); - XmlUtil.gcXmlInputFactory(XML_INPUT_FACTORY_SUPPLIER.get()); - } catch (XMLStreamException e) { - LOGGER.error(e.toString(), e); - } + closeAndUseGarbageCollector(xmlsr); } } } @@ -94,4 +89,13 @@ protected boolean exists(ReadOnlyDataSource dataSource, String ext) throws IOExc return false; } } + + private void closeAndUseGarbageCollector(XMLStreamReader xmlStreamReader) { + try { + xmlStreamReader.close(); + XmlUtil.gcXmlInputFactory(XML_INPUT_FACTORY_SUPPLIER.get()); + } catch (XMLStreamException e) { + LOGGER.error(e.toString(), e); + } + } } From aa5618b4f485c062c9b2110a78c440a8eb962c52 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:07:40 +0200 Subject: [PATCH 46/84] fix Networks Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/iidm/network/util/Networks.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java index 7fb39d275a2..7bfd0772d85 100644 --- a/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java +++ b/iidm/iidm-api/src/main/java/com/powsybl/iidm/network/util/Networks.java @@ -367,7 +367,9 @@ public static IntStream getNodes(String busId, VoltageLevel voltageLevel, Functi } else { // If there is no terminal for the current node, we try to find one traversing the topology Terminal equivalentTerminal = Networks.getEquivalentTerminal(voltageLevel, i); - addBusFromTerminal(busId, equivalentTerminal, getBusFromTerminal, nodes, i); + if (equivalentTerminal != null) { + addBusFromTerminal(busId, equivalentTerminal, getBusFromTerminal, nodes, i); + } } } return nodes.stream().mapToInt(Integer::intValue); From 4bb71e7a66cc82ff708bd334b94818d67feef468 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:09:18 +0200 Subject: [PATCH 47/84] use List.of Signed-off-by: Nicolas Rol --- .../com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java index 0f89cb95a57..6ba2b2f70f8 100644 --- a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java +++ b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java @@ -64,7 +64,7 @@ public InputStream getXsdAsStream() { @Override public List getXsdAsStreamList() { - return ImmutableList.of(getClass().getResourceAsStream("/xsd/slackTerminal_V1_0.xsd"), + return List.of(getClass().getResourceAsStream("/xsd/slackTerminal_V1_0.xsd"), getClass().getResourceAsStream("/xsd/slackTerminal_V1_1.xsd"), getClass().getResourceAsStream("/xsd/slackTerminal_V1_2.xsd"), getClass().getResourceAsStream("/xsd/slackTerminal_V1_3.xsd"), From a663970c26b3582f530d1d12391f226185085f9b Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:10:24 +0200 Subject: [PATCH 48/84] remove import Signed-off-by: Nicolas Rol --- .../com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java | 1 - 1 file changed, 1 deletion(-) diff --git a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java index 6ba2b2f70f8..979a3c592c1 100644 --- a/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java +++ b/iidm/iidm-serde/src/main/java/com/powsybl/iidm/serde/extensions/SlackTerminalSerDe.java @@ -8,7 +8,6 @@ package com.powsybl.iidm.serde.extensions; import com.google.auto.service.AutoService; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.powsybl.commons.extensions.ExtensionSerDe; From 60683291fc51a3efeddf514992142967dce0be14 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:14:58 +0200 Subject: [PATCH 49/84] concat duplicated test in one parametrized Signed-off-by: Nicolas Rol --- .../json/JsonLoadFlowParametersTest.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java b/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java index 1ca542cd74f..da7c4a33169 100644 --- a/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java +++ b/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java @@ -23,10 +23,14 @@ import com.powsybl.iidm.network.Country; import com.powsybl.loadflow.LoadFlowParameters; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOError; import java.io.IOException; import java.io.InputStream; +import java.util.stream.Stream; import static com.powsybl.loadflow.LoadFlowParameters.VoltageInitMode.PREVIOUS_VALUES; import static org.junit.jupiter.api.Assertions.*; @@ -68,24 +72,19 @@ void readError() throws IOException { } } - @Test - void readJsonVersion10() { - LoadFlowParameters parameters = JsonLoadFlowParameters - .read(getClass().getResourceAsStream("/LoadFlowParametersVersion10.json")); - assertTrue(parameters.isTwtSplitShuntAdmittance()); + private static Stream provideArguments() { + return Stream.of( + Arguments.of("/LoadFlowParametersVersion10.json"), + Arguments.of("/LoadFlowParametersVersion11.json"), + Arguments.of("/LoadFlowParametersVersion12.json") + ); } - @Test - void readJsonVersion11() { - LoadFlowParameters parameters = JsonLoadFlowParameters - .read(getClass().getResourceAsStream("/LoadFlowParametersVersion11.json")); - assertTrue(parameters.isTwtSplitShuntAdmittance()); - } - - @Test - void readJsonVersion12() { + @ParameterizedTest + @MethodSource("provideArguments") + void readJsonSpecificVersions(String json) { LoadFlowParameters parameters = JsonLoadFlowParameters - .read(getClass().getResourceAsStream("/LoadFlowParametersVersion12.json")); + .read(getClass().getResourceAsStream(json)); assertTrue(parameters.isTwtSplitShuntAdmittance()); } From 39979499ada67d548a6ce5ba0e55d7883e282826 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:18:33 +0200 Subject: [PATCH 50/84] use Map.of Signed-off-by: Nicolas Rol --- .../LoadFlowResultsCompletionParameters.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java index 7c2dac110c5..36a910ef322 100644 --- a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java +++ b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java @@ -66,9 +66,9 @@ public double getZ0ThresholdDiffVoltageAngle() { } protected Map toMap() { - return ImmutableMap.of("epsilonX", epsilonX, - "applyReactanceCorrection", applyReactanceCorrection, - "z0ThresholdDiffVoltageAngle", z0ThresholdDiffVoltageAngle); + return Map.of("epsilonX", epsilonX, + "applyReactanceCorrection", applyReactanceCorrection, + "z0ThresholdDiffVoltageAngle", z0ThresholdDiffVoltageAngle); } @Override From e3ffea3bf635a2e43e88335286ebfec045feb11f Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:18:48 +0200 Subject: [PATCH 51/84] streams in try with resources Signed-off-by: Nicolas Rol --- .../json/JsonLoadFlowParametersTest.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java b/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java index da7c4a33169..c6d34f79764 100644 --- a/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java +++ b/loadflow/loadflow-api/src/test/java/com/powsybl/loadflow/json/JsonLoadFlowParametersTest.java @@ -146,21 +146,24 @@ void readJsonVersion19() { } @Test - void readJsonVersion10Exception() { - InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion10Exception.json"); - assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: t2wtSplitShuntAdmittance is not valid for version 1.0. Version should be > 1.0"); + void readJsonVersion10Exception() throws IOException { + try (InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion10Exception.json")) { + assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: t2wtSplitShuntAdmittance is not valid for version 1.0. Version should be > 1.0"); + } } @Test - void readJsonVersion11Exception() { - InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion11Exception.json"); - assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: specificCompatibility is not valid for version 1.1. Version should be <= 1.0"); + void readJsonVersion11Exception() throws IOException { + try (InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion11Exception.json")) { + assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: specificCompatibility is not valid for version 1.1. Version should be <= 1.0"); + } } @Test - void readJsonVersion12Exception() { - InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion12Exception.json"); - assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: t2wtSplitShuntAdmittance is not valid for version 1.2. Version should be <= 1.1"); + void readJsonVersion12Exception() throws IOException { + try (InputStream inputStream = getClass().getResourceAsStream("/LoadFlowParametersVersion12Exception.json")) { + assertThrows(PowsyblException.class, () -> JsonLoadFlowParameters.read(inputStream), "LoadFlowParameters. Tag: t2wtSplitShuntAdmittance is not valid for version 1.2. Version should be <= 1.1"); + } } public static class DummyExtension extends AbstractExtension { From f64f4d449019dabcefe22dff16108649c66b8a7f Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:18:59 +0200 Subject: [PATCH 52/84] remove import Signed-off-by: Nicolas Rol --- .../resultscompletion/LoadFlowResultsCompletionParameters.java | 1 - 1 file changed, 1 deletion(-) diff --git a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java index 36a910ef322..be0a32a3a1c 100644 --- a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java +++ b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java @@ -7,7 +7,6 @@ */ package com.powsybl.loadflow.resultscompletion; -import com.google.common.collect.ImmutableMap; import com.powsybl.commons.config.PlatformConfig; import java.util.Map; From 0f92791330a99cac2a3ac79a6c5a80227e1132d8 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:20:55 +0200 Subject: [PATCH 53/84] changed supplier + Stream.toList() Signed-off-by: Nicolas Rol --- .../powsybl/loadflow/validation/CandidateComputations.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/CandidateComputations.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/CandidateComputations.java index e5bea8803a1..39d1470d78f 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/CandidateComputations.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/CandidateComputations.java @@ -7,14 +7,13 @@ */ package com.powsybl.loadflow.validation; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import java.util.ServiceLoader; -import java.util.stream.Collectors; +import java.util.function.Supplier; /** * Provides access to the list of known candidate computations. @@ -41,7 +40,7 @@ public static List getComputations() { * Get the list of all known candidate computations names. */ public static List getComputationsNames() { - return getComputations().stream().map(CandidateComputation::getName).collect(Collectors.toList()); + return getComputations().stream().map(CandidateComputation::getName).toList(); } /** From 3af20d21a15a8ee7c65d5bafcad37bc27cc2239f Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:22:46 +0200 Subject: [PATCH 54/84] fix logger class Signed-off-by: Nicolas Rol --- .../loadflow/validation/ShuntCompensatorsValidation.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ShuntCompensatorsValidation.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ShuntCompensatorsValidation.java index 6307db72a0f..c66e4e72824 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ShuntCompensatorsValidation.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ShuntCompensatorsValidation.java @@ -29,7 +29,7 @@ */ public final class ShuntCompensatorsValidation { - private static final Logger LOGGER = LoggerFactory.getLogger(StaticVarCompensatorsValidation.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ShuntCompensatorsValidation.class); public static final ShuntCompensatorsValidation INSTANCE = new ShuntCompensatorsValidation(); From 4e4273aeb1efafe7122003849fde9c2c45e470c7 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:24:15 +0200 Subject: [PATCH 55/84] fix ValidationUtils Signed-off-by: Nicolas Rol --- .../com/powsybl/loadflow/validation/ValidationUtils.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java index ec3d74337da..0c518c3462d 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java @@ -8,8 +8,10 @@ package com.powsybl.loadflow.validation; import java.io.Writer; +import java.lang.reflect.InvocationTargetException; import java.util.Objects; +import com.powsybl.commons.PowsyblException; import com.powsybl.commons.config.ConfigurationException; import com.powsybl.loadflow.validation.io.ValidationWriter; import com.powsybl.loadflow.validation.io.ValidationWriterFactory; @@ -32,10 +34,12 @@ public static ValidationWriter createValidationWriter(String id, ValidationConfi Objects.requireNonNull(writer); Objects.requireNonNull(validationType); try { - ValidationWriterFactory factory = config.getValidationOutputWriter().getValidationWriterFactory().newInstance(); + ValidationWriterFactory factory = config.getValidationOutputWriter().getValidationWriterFactory().getDeclaredConstructor().newInstance(); return factory.create(id, config.getTableFormatterFactory(), writer, config.isVerbose(), validationType, config.isCompareResults()); } catch (InstantiationException | IllegalAccessException e) { throw new ConfigurationException(e); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new PowsyblException(e); } } @@ -85,7 +89,7 @@ public static boolean boundedWithin(double lowerBound, double upperBound, double public static boolean isMainComponent(ValidationConfig config, boolean mainComponent) { Objects.requireNonNull(config); - return config.isCheckMainComponentOnly() ? mainComponent : true; + return !config.isCheckMainComponentOnly() || mainComponent; } } From 79f771e8fd92fd0b23fd819e0df7a424d2e476f9 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:31:55 +0200 Subject: [PATCH 56/84] make inner classes static in AbstractValidationFormatterWriter Signed-off-by: Nicolas Rol --- .../io/AbstractValidationFormatterWriter.java | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java index ae72deb92db..1a3e09ee772 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java @@ -9,10 +9,12 @@ import java.io.IOException; import java.io.Writer; +import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import com.powsybl.commons.PowsyblException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -72,10 +74,12 @@ public abstract class AbstractValidationFormatterWriter implements ValidationWri protected TableFormatter createTableFormatter(String id, Class formatterFactoryClass, TableFormatterConfig formatterConfig, Writer writer, ValidationType validationType) { try { - TableFormatterFactory factory = formatterFactoryClass.newInstance(); + TableFormatterFactory factory = formatterFactoryClass.getDeclaredConstructor().newInstance(); return factory.create(writer, id + " " + validationType + " check", formatterConfig, getColumns()); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException(e); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new PowsyblException(e); } } @@ -92,8 +96,8 @@ public void write(String branchId, double p1, double p1Calc, double q1, double q boolean mainComponent1, boolean mainComponent2, boolean validated) throws IOException { Objects.requireNonNull(branchId); FlowData emptyFlowData = new FlowData(branchId, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, 0, false, false, false, false, false); + Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, + Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, 0, false, false, false, false, false); if (compareResults) { if (preLoadflowValidationCompleted) { boolean found = flowsData.containsKey(branchId); @@ -103,7 +107,7 @@ public void write(String branchId, double p1, double p1Calc, double q1, double q flowsData.remove(branchId); } else { flowsData.put(branchId, new FlowData(branchId, p1, p1Calc, q1, q1Calc, p2, p2Calc, q2, q2Calc, r, x, g1, g2, b1, b2, rho1, rho2, alpha1, alpha2, - u1, u2, theta1, theta2, z, y, ksi, phaseAngleClock, connected1, connected2, mainComponent1, mainComponent2, validated)); + u1, u2, theta1, theta2, z, y, ksi, phaseAngleClock, connected1, connected2, mainComponent1, mainComponent2, validated)); } } else { write(branchId, p1, p1Calc, q1, q1Calc, p2, p2Calc, q2, q2Calc, r, x, g1, g2, b1, b2, rho1, rho2, alpha1, alpha2, u1, u2, @@ -121,7 +125,7 @@ public void write(String generatorId, double p, double q, double v, double targe boolean voltageRegulatorOn, double minP, double maxP, double minQ, double maxQ, boolean mainComponent, boolean validated) throws IOException { Objects.requireNonNull(generatorId); GeneratorData emptyGeneratorData = new GeneratorData(generatorId, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, false, false, Double.NaN, Double.NaN, Double.NaN, Double.NaN, false, false); + Double.NaN, false, false, Double.NaN, Double.NaN, Double.NaN, Double.NaN, false, false); if (compareResults) { if (preLoadflowValidationCompleted) { boolean found = generatorsData.containsKey(generatorId); @@ -131,7 +135,7 @@ public void write(String generatorId, double p, double q, double v, double targe generatorsData.remove(generatorId); } else { generatorsData.put(generatorId, new GeneratorData(generatorId, p, q, v, targetP, targetQ, targetV, expectedP, connected, - voltageRegulatorOn, minP, maxP, minQ, maxQ, mainComponent, validated)); + voltageRegulatorOn, minP, maxP, minQ, maxQ, mainComponent, validated)); } } else { write(generatorId, p, q, v, targetP, targetQ, targetV, expectedP, connected, voltageRegulatorOn, @@ -150,8 +154,8 @@ public void write(String busId, double incomingP, double incomingQ, double loadP boolean validated) throws IOException { Objects.requireNonNull(busId); BusData emptyBusData = new BusData(busId, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, Double.NaN, false, false); + Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, + Double.NaN, Double.NaN, false, false); if (compareResults) { if (preLoadflowValidationCompleted) { boolean found = busesData.containsKey(busId); @@ -161,7 +165,7 @@ public void write(String busId, double incomingP, double incomingQ, double loadP busesData.remove(busId); } else { busesData.put(busId, new BusData(busId, incomingP, incomingQ, loadP, loadQ, genP, genQ, batP, batQ, shuntP, shuntQ, svcP, svcQ, vscCSP, vscCSQ, - lineP, lineQ, danglingLineP, danglingLineQ, twtP, twtQ, tltP, tltQ, mainComponent, validated)); + lineP, lineQ, danglingLineP, danglingLineQ, twtP, twtQ, tltP, tltQ, mainComponent, validated)); } } else { write(busId, incomingP, incomingQ, loadP, loadQ, genP, genQ, batP, batQ, shuntP, shuntQ, svcP, svcQ, vscCSP, vscCSQ, lineP, lineQ, @@ -211,7 +215,7 @@ public void write(String shuntId, double q, double expectedQ, double p, int curr shuntsData.remove(shuntId); } else { shuntsData.put(shuntId, new ShuntData(shuntId, q, expectedQ, p, currentSectionCount, maximumSectionCount, - bPerSection, v, connected, qMax, nominalV, mainComponent, validated)); + bPerSection, v, connected, qMax, nominalV, mainComponent, validated)); } } else { write(shuntId, q, expectedQ, p, currentSectionCount, maximumSectionCount, bPerSection, v, connected, qMax, nominalV, mainComponent, validated, emptyShuntData, false, true); @@ -228,7 +232,7 @@ public void write(String twtId, double error, double upIncrement, double downInc boolean mainComponent, boolean validated) throws IOException { Objects.requireNonNull(twtId); TransformerData emptyTwtData = new TransformerData(twtId, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, - Double.NaN, -1, -1, -1, Double.NaN, TwoSides.ONE, Double.NaN, false, false, false); + Double.NaN, -1, -1, -1, Double.NaN, TwoSides.ONE, Double.NaN, false, false, false); if (compareResults) { if (preLoadflowValidationCompleted) { boolean found = twtsData.containsKey(twtId); @@ -238,7 +242,7 @@ public void write(String twtId, double error, double upIncrement, double downInc twtsData.remove(twtId); } else { twtsData.put(twtId, new TransformerData(twtId, error, upIncrement, downIncrement, rho, rhoPreviousStep, rhoNextStep, tapPosition, - lowTapPosition, highTapPosition, targetV, regulatedSide, v, connected, mainComponent, validated)); + lowTapPosition, highTapPosition, targetV, regulatedSide, v, connected, mainComponent, validated)); } } else { write(twtId, error, upIncrement, downIncrement, rho, rhoPreviousStep, rhoNextStep, tapPosition, lowTapPosition, @@ -387,7 +391,7 @@ public void close() throws IOException { formatter.close(); } - class FlowData { + static class FlowData { final String branchId; final double p1; @@ -462,7 +466,7 @@ class FlowData { } - class GeneratorData { + static class GeneratorData { final String generatorId; final double p; final double q; @@ -503,7 +507,7 @@ class GeneratorData { } - class BusData { + static class BusData { final String busId; final double incomingP; @@ -564,7 +568,7 @@ class BusData { } - class SvcData { + static class SvcData { final String svcId; final double p; @@ -601,7 +605,7 @@ class SvcData { } - class ShuntData { + static class ShuntData { final String shuntId; final double q; @@ -636,7 +640,7 @@ class ShuntData { } - class TransformerData { + static class TransformerData { final String twtId; final double error; final double upIncrement; @@ -677,7 +681,7 @@ class TransformerData { } - class Transformer3WData { + static class Transformer3WData { final String twtId; final TwtData twtData; final boolean validated; From ab5be9cc1016eb7dc44348a6b936d04d90d37231 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:43:11 +0200 Subject: [PATCH 57/84] removed deprecated method UndirectedGraph.getMaxVertex Signed-off-by: Nicolas Rol --- .../powsybl/math/graph/UndirectedGraph.java | 20 +------------------ .../math/graph/UndirectedGraphImplTest.java | 2 +- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java b/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java index b23cdfb8d34..a9e91cf92a9 100644 --- a/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java +++ b/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java @@ -122,26 +122,8 @@ default boolean vertexExists(int v) { * To get the number of vertices in this graph, use {@link #getVertexCount()}. * * @return the maximum number of vertices contained in this graph. - * - * @deprecated Use {@link #getVertexCapacity} instead. */ - @Deprecated(since = "2.5.0") - default int getMaxVertex() { - return getVertexCapacity(); - } - - /** - * Return the maximum number of vertices that this graph can contain. The vertex indices are in the range [0, getVertexCapacity[ - * - * As the contiguity of the vertices is not mandatory, do not use this method to iterate over the vertices. Use {@link #getVertices()} instead. - * - * To get the number of vertices in this graph, use {@link #getVertexCount()}. - * - * @return the maximum number of vertices contained in this graph. - */ - default int getVertexCapacity() { - return getMaxVertex(); - } + int getVertexCapacity(); /** * Return an {@link Iterable} to iterate over the values attached to the vertices. diff --git a/math/src/test/java/com/powsybl/math/graph/UndirectedGraphImplTest.java b/math/src/test/java/com/powsybl/math/graph/UndirectedGraphImplTest.java index 7f00ef2346a..43af43db8a5 100644 --- a/math/src/test/java/com/powsybl/math/graph/UndirectedGraphImplTest.java +++ b/math/src/test/java/com/powsybl/math/graph/UndirectedGraphImplTest.java @@ -119,7 +119,7 @@ void testGetMaxVertex() { graph.addVertex(); graph.addVertex(); graph.removeVertex(1); - assertEquals(3, graph.getMaxVertex()); + assertEquals(3, graph.getVertexCapacity()); } @Test From eeb2475c3a5952f8001e53b2b43f5964ec3c750d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Mon, 8 Apr 2024 16:44:26 +0200 Subject: [PATCH 58/84] removed blank lines Signed-off-by: Nicolas Rol --- math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java b/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java index a9e91cf92a9..faf5534b916 100644 --- a/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java +++ b/math/src/main/java/com/powsybl/math/graph/UndirectedGraph.java @@ -116,9 +116,7 @@ default boolean vertexExists(int v) { /** * Return the maximum number of vertices that this graph can contain. The vertex indices are in the range [0, getVertexCapacity[ - * * As the contiguity of the vertices is not mandatory, do not use this method to iterate over the vertices. Use {@link #getVertices()} instead. - * * To get the number of vertices in this graph, use {@link #getVertexCount()}. * * @return the maximum number of vertices contained in this graph. @@ -250,7 +248,6 @@ default boolean vertexExists(int v) { * Traverse the entire graph, starting at the specified vertex v. * This method relies on a {@link Traverser} instance to know if the traverse of the graph should continue or stop. * This method throws a {@link com.powsybl.commons.PowsyblException} if the encountered table size is less than the maximum vertex index. - * * At the end of the method, the encountered array contains {@literal true} for all the traversed vertices, {@literal false} otherwise. * * @param v the vertex index where the traverse has to start. From 3ff8441d7b56d0e09228e92399872a5daca6997a Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 13:56:03 +0200 Subject: [PATCH 59/84] fix map with preserved order Signed-off-by: Nicolas Rol --- .../dynamicsimulation/DynamicSimulationParameters.java | 8 ++++++-- .../DynamicSimulationParametersTest.java | 8 ++++---- .../LoadFlowResultsCompletionParameters.java | 10 +++++++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java index c5bd9826355..70fea94cf00 100644 --- a/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java +++ b/dynamic-simulation/dynamic-simulation-api/src/main/java/com/powsybl/dynamicsimulation/DynamicSimulationParameters.java @@ -7,6 +7,8 @@ */ package com.powsybl.dynamicsimulation; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; @@ -136,8 +138,10 @@ public DynamicSimulationParameters setStopTime(int stopTime) { } protected Map toMap() { - return Map.of("startTime", startTime, - "stopTime", stopTime); + Map map = new LinkedHashMap<>(); + map.put("startTime", startTime); + map.put("stopTime", stopTime); + return Collections.unmodifiableMap(map); } public DynamicSimulationParameters copy() { diff --git a/dynamic-simulation/dynamic-simulation-api/src/test/java/com/powsybl/dynamicsimulation/DynamicSimulationParametersTest.java b/dynamic-simulation/dynamic-simulation-api/src/test/java/com/powsybl/dynamicsimulation/DynamicSimulationParametersTest.java index dbb4262ef4b..2b544289269 100644 --- a/dynamic-simulation/dynamic-simulation-api/src/test/java/com/powsybl/dynamicsimulation/DynamicSimulationParametersTest.java +++ b/dynamic-simulation/dynamic-simulation-api/src/test/java/com/powsybl/dynamicsimulation/DynamicSimulationParametersTest.java @@ -132,8 +132,8 @@ void testExtensions() { assertEquals(1, parameters.getExtensions().size()); assertTrue(parameters.getExtensions().contains(dummyExtension)); - assertTrue(parameters.getExtensionByName("dummyExtension") instanceof DummyExtension); - assertTrue(parameters.getExtension(DummyExtension.class) instanceof DummyExtension); + assertInstanceOf(DummyExtension.class, parameters.getExtensionByName("dummyExtension")); + assertInstanceOf(DummyExtension.class, parameters.getExtension(DummyExtension.class)); } @Test @@ -143,7 +143,7 @@ void testNoExtensions() { assertEquals(0, parameters.getExtensions().size()); assertFalse(parameters.getExtensions().contains(new DummyExtension())); assertFalse(parameters.getExtensionByName("dummyExtension") instanceof DummyExtension); - assertFalse(parameters.getExtension(DummyExtension.class) instanceof DummyExtension); + assertNull(parameters.getExtension(DummyExtension.class)); } @Test @@ -151,7 +151,7 @@ void testExtensionFromConfig() { DynamicSimulationParameters parameters = DynamicSimulationParameters.load(platformConfig); assertEquals(1, parameters.getExtensions().size()); - assertTrue(parameters.getExtensionByName("dummyExtension") instanceof DummyExtension); + assertInstanceOf(DummyExtension.class, parameters.getExtensionByName("dummyExtension")); assertNotNull(parameters.getExtension(DummyExtension.class)); } diff --git a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java index be0a32a3a1c..c8e1286c545 100644 --- a/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java +++ b/loadflow/loadflow-results-completion/src/main/java/com/powsybl/loadflow/resultscompletion/LoadFlowResultsCompletionParameters.java @@ -9,6 +9,8 @@ import com.powsybl.commons.config.PlatformConfig; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -65,9 +67,11 @@ public double getZ0ThresholdDiffVoltageAngle() { } protected Map toMap() { - return Map.of("epsilonX", epsilonX, - "applyReactanceCorrection", applyReactanceCorrection, - "z0ThresholdDiffVoltageAngle", z0ThresholdDiffVoltageAngle); + Map map = new LinkedHashMap<>(); + map.put("epsilonX", epsilonX); + map.put("applyReactanceCorrection", applyReactanceCorrection); + map.put("z0ThresholdDiffVoltageAngle", z0ThresholdDiffVoltageAngle); + return Collections.unmodifiableMap(map); } @Override From 46103a3e5349152ce6bc1b27323ea334cdc68578 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:02:51 +0200 Subject: [PATCH 60/84] fix PsseExporter issues Signed-off-by: Nicolas Rol --- .../powsybl/psse/converter/PsseExporter.java | 88 +++++++++---------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java b/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java index 0c379361168..db048a1b2ee 100644 --- a/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java +++ b/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java @@ -8,7 +8,6 @@ package com.powsybl.psse.converter; import com.google.auto.service.AutoService; -import com.google.common.collect.ImmutableList; import com.powsybl.commons.datasource.DataSource; import com.powsybl.iidm.network.Exporter; import com.powsybl.iidm.network.*; @@ -40,10 +39,10 @@ public class PsseExporter implements Exporter { @Override public List getParameters() { - return Collections.unmodifiableList(STATIC_PARAMETERS); + return STATIC_PARAMETERS; } - private static final List STATIC_PARAMETERS = ImmutableList.of(); + private static final List STATIC_PARAMETERS = List.of(); @Override public String getFormat() { @@ -62,50 +61,51 @@ public void export(Network network, Properties parameters, DataSource dataSource PssePowerFlowModel updatePsseModel = createUpdatePsseModel(network, psseModel); Context context = network.getExtension(PsseConversionContextExtension.class).getContext(); + PsseVersion version = PsseVersion.fromRevision(updatePsseModel.getCaseIdentification().getRev()); if (context.getFileFormat() == FileFormat.JSON) { - PsseVersion version = PsseVersion.fromRevision(updatePsseModel.getCaseIdentification().getRev()); - switch (version.major()) { - case V35: - PowerFlowRawxData35 rawXData35 = new PowerFlowRawxData35(); - try { - rawXData35.write(updatePsseModel, context, dataSource); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - break; - default: - throw new PsseException("Unsupported version " + version); + if (Objects.requireNonNull(version.major()) == PsseVersion.Major.V35) { + PowerFlowRawxData35 rawXData35 = new PowerFlowRawxData35(); + try { + rawXData35.write(updatePsseModel, context, dataSource); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } else { + throw new PsseException("Unsupported version " + version); } } else { - PsseVersion version = PsseVersion.fromRevision(updatePsseModel.getCaseIdentification().getRev()); - switch (version.major()) { - case V35: - PowerFlowRawData35 rawData35 = new PowerFlowRawData35(); - try { - rawData35.write(updatePsseModel, context, dataSource); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - break; - case V33: - PowerFlowRawData33 rawData33 = new PowerFlowRawData33(); - try { - rawData33.write(updatePsseModel, context, dataSource); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - break; - case V32: - PowerFlowRawData32 rawData32 = new PowerFlowRawData32(); - try { - rawData32.write(updatePsseModel, context, dataSource); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - break; - default: - throw new PsseException("Unsupported version " + version); - } + exportNotJson(context, updatePsseModel, version, dataSource); + } + } + + private void exportNotJson(Context context, PssePowerFlowModel updatePsseModel, PsseVersion version, DataSource dataSource) { + switch (version.major()) { + case V35: + PowerFlowRawData35 rawData35 = new PowerFlowRawData35(); + try { + rawData35.write(updatePsseModel, context, dataSource); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + break; + case V33: + PowerFlowRawData33 rawData33 = new PowerFlowRawData33(); + try { + rawData33.write(updatePsseModel, context, dataSource); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + break; + case V32: + PowerFlowRawData32 rawData32 = new PowerFlowRawData32(); + try { + rawData32.write(updatePsseModel, context, dataSource); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + break; + default: + throw new PsseException("Unsupported version " + version); } } From 66c58ea56055c80e6892d84be8a97668fed0a773 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:19:26 +0200 Subject: [PATCH 61/84] simplify condition Signed-off-by: Nicolas Rol --- .../powsybl/security/comparator/LimitViolationEquivalence.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/comparator/LimitViolationEquivalence.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/comparator/LimitViolationEquivalence.java index 6df6d5776cf..5ddbd2a1f73 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/comparator/LimitViolationEquivalence.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/comparator/LimitViolationEquivalence.java @@ -34,7 +34,7 @@ protected boolean doEquivalent(LimitViolation violation1, LimitViolation violati && Math.abs(violation1.getAcceptableDuration() - violation2.getAcceptableDuration()) <= threshold && Math.abs(violation1.getLimitReduction() - violation2.getLimitReduction()) <= threshold && Math.abs(violation1.getValue() - violation2.getValue()) <= threshold - && (violation1.getLimitType() == LimitViolationType.CURRENT ? violation1.getSide() == violation2.getSide() : true); + && (violation1.getLimitType() != LimitViolationType.CURRENT || violation1.getSide() == violation2.getSide()); } @Override From f14362bfd4bd4522eac74bb1bf895b2af4eac13d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:20:46 +0200 Subject: [PATCH 62/84] swap Supplier Signed-off-by: Nicolas Rol --- .../security/interceptors/SecurityAnalysisInterceptors.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/interceptors/SecurityAnalysisInterceptors.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/interceptors/SecurityAnalysisInterceptors.java index a384d28fdfa..a1d9a49ca8c 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/interceptors/SecurityAnalysisInterceptors.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/interceptors/SecurityAnalysisInterceptors.java @@ -7,11 +7,11 @@ */ package com.powsybl.security.interceptors; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.util.ServiceLoaderCache; import java.util.*; +import java.util.function.Supplier; import java.util.stream.Collectors; /** From 11ef1a7c60fc38b4216ec8b838fe00008df35705 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:21:06 +0200 Subject: [PATCH 63/84] swap Supplier Signed-off-by: Nicolas Rol --- .../com/powsybl/security/json/LimitViolationDeserializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/LimitViolationDeserializer.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/LimitViolationDeserializer.java index 57230f545d3..cad1a983aff 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/LimitViolationDeserializer.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/LimitViolationDeserializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.Extension; import com.powsybl.commons.extensions.ExtensionJsonSerializer; @@ -24,6 +23,7 @@ import java.io.IOException; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; /** * @author Mathieu Bague {@literal } From 480ef800ad66b1a7d2291868d3546f5b19f12ee9 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:22:57 +0200 Subject: [PATCH 64/84] swap Supplier Signed-off-by: Nicolas Rol --- .../com/powsybl/security/json/NetworkMetadataDeserializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/NetworkMetadataDeserializer.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/NetworkMetadataDeserializer.java index 1c8864c2cf2..be6eb2101f0 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/NetworkMetadataDeserializer.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/NetworkMetadataDeserializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.PowsyblException; import com.powsybl.commons.extensions.Extension; @@ -24,6 +23,7 @@ import java.time.ZonedDateTime; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; /** * @author Mathieu Bague {@literal } From 41b3e94c2c10ae6c4ae903a3b7c1da67bda378d8 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:24:53 +0200 Subject: [PATCH 65/84] swap Supplier + string variable Signed-off-by: Nicolas Rol --- .../security/json/OperatorStrategyDeserializer.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/OperatorStrategyDeserializer.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/OperatorStrategyDeserializer.java index 414d7665e19..359bbd609a7 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/OperatorStrategyDeserializer.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/OperatorStrategyDeserializer.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.Extension; import com.powsybl.commons.extensions.ExtensionJsonSerializer; @@ -25,6 +24,7 @@ import java.io.IOException; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; import static com.powsybl.security.json.SecurityAnalysisResultDeserializer.SOURCE_VERSION_ATTRIBUTE; @@ -34,6 +34,7 @@ public class OperatorStrategyDeserializer extends StdDeserializer { private static final String CONTEXT_NAME = "OperatorStrategy"; + private static final String TAG_CONTINGENCY_STATUS = "Tag: contingencyStatus"; public OperatorStrategyDeserializer() { super(OperatorStrategy.class); @@ -42,7 +43,7 @@ public OperatorStrategyDeserializer() { private static final Supplier> SUPPLIER = Suppliers.memoize(() -> ExtensionProviders.createProvider(ExtensionJsonSerializer.class, "security-analysis")); - private static class ParsingContext { + private static final class ParsingContext { String version; String id; ContingencyContextType contingencyContextType; @@ -75,19 +76,19 @@ public OperatorStrategy deserialize(JsonParser parser, DeserializationContext de return true; case "conditionalActions": parser.nextToken(); - JsonUtil.assertGreaterOrEqualThanReferenceVersion(CONTEXT_NAME, "Tag: contingencyStatus", + JsonUtil.assertGreaterOrEqualThanReferenceVersion(CONTEXT_NAME, TAG_CONTINGENCY_STATUS, context.version, "1.5"); context.stages = JsonUtil.readList(deserializationContext, parser, ConditionalActions.class); return true; case "condition": parser.nextToken(); - JsonUtil.assertLessThanOrEqualToReferenceVersion(CONTEXT_NAME, "Tag: contingencyStatus", + JsonUtil.assertLessThanOrEqualToReferenceVersion(CONTEXT_NAME, TAG_CONTINGENCY_STATUS, context.version, "1.4"); context.condition = JsonUtil.readValue(deserializationContext, parser, Condition.class); return true; case "actionIds": parser.nextToken(); - JsonUtil.assertLessThanOrEqualToReferenceVersion(CONTEXT_NAME, "Tag: contingencyStatus", + JsonUtil.assertLessThanOrEqualToReferenceVersion(CONTEXT_NAME, TAG_CONTINGENCY_STATUS, context.version, "1.4"); context.actionIds = JsonUtil.readList(deserializationContext, parser, String.class); return true; From 350bbd3a77f025ff18b373624334abd3f273578c Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:25:37 +0200 Subject: [PATCH 66/84] swap Supplier Signed-off-by: Nicolas Rol --- .../security/json/SecurityAnalysisResultDeserializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/SecurityAnalysisResultDeserializer.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/SecurityAnalysisResultDeserializer.java index 0179c95e408..2e3cd61defc 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/SecurityAnalysisResultDeserializer.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/json/SecurityAnalysisResultDeserializer.java @@ -12,7 +12,6 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.action.json.ActionJsonModule; import com.powsybl.commons.extensions.*; @@ -32,6 +31,7 @@ import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.function.Supplier; /** * @author Massimo Ferraro {@literal } From 5dd35e40b7951d58796e13bb045c3ab9391ebc7f Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:28:54 +0200 Subject: [PATCH 67/84] replace 3 tests with one parametrized Signed-off-by: Nicolas Rol --- .../security/converter/ExporterTest.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java index 1e0e89e31a9..d2f1f4cec0c 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java @@ -25,6 +25,9 @@ import com.powsybl.security.strategy.ConditionalActions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.*; import java.nio.file.Files; @@ -32,6 +35,7 @@ import java.nio.file.Paths; import java.util.*; import java.util.function.BiConsumer; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @@ -111,21 +115,18 @@ void testCompatibilityV11Deserialization() { assertEquals(3.3, result.getPreContingencyResult().getNetworkResult().getBranchResult("branch1").getI2(), 0.01); } - @Test - void testCompatibilityV12Deserialization() { - SecurityAnalysisResult result = SecurityAnalysisResultDeserializer.read(getClass().getResourceAsStream("/SecurityAnalysisResultV1.2.json")); - assertEquals(PostContingencyComputationStatus.CONVERGED, result.getPostContingencyResults().get(0).getStatus()); + private static Stream provideArguments() { + return Stream.of( + Arguments.of("/SecurityAnalysisResultV1.2.json"), + Arguments.of("/SecurityAnalysisResultV1.3.json"), + Arguments.of("/SecurityAnalysisResultV1.4.json") + ); } - @Test - void testCompatibilityV13Deserialization() { - SecurityAnalysisResult result = SecurityAnalysisResultDeserializer.read(getClass().getResourceAsStream("/SecurityAnalysisResultV1.3.json")); - assertEquals(PostContingencyComputationStatus.CONVERGED, result.getPostContingencyResults().get(0).getStatus()); - } - - @Test - void testCompatibilityV14Deserialization() { - SecurityAnalysisResult result = SecurityAnalysisResultDeserializer.read(getClass().getResourceAsStream("/SecurityAnalysisResultV1.4.json")); + @ParameterizedTest + @MethodSource("provideArguments") + void testCompatibilityV12To14Deserialization(String jsonFileName) { + SecurityAnalysisResult result = SecurityAnalysisResultDeserializer.read(getClass().getResourceAsStream(jsonFileName)); assertEquals(PostContingencyComputationStatus.CONVERGED, result.getPostContingencyResults().get(0).getStatus()); } From 5fb9736b406847351d0f02a2fa45e73c83d5691a Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:31:16 +0200 Subject: [PATCH 68/84] fix ExporterTest issues Signed-off-by: Nicolas Rol --- .../security/converter/ExporterTest.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java index d2f1f4cec0c..e5eb2e06b2d 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/converter/ExporterTest.java @@ -143,15 +143,15 @@ void roundTripJson() throws IOException { roundTripTest(result, ExporterTest::writeJson, SecurityAnalysisResultDeserializer::read, "/SecurityAnalysisResult.json"); - BiConsumer exporter = (res, path) -> { - SecurityAnalysisResultExporters.export(res, path, "JSON"); - }; + BiConsumer exporter = (res, path) -> SecurityAnalysisResultExporters.export(res, path, "JSON"); roundTripTest(result, exporter, SecurityAnalysisResultDeserializer::read, "/SecurityAnalysisResult.json"); // Check invalid path - assertThrows(UncheckedIOException.class, () -> SecurityAnalysisResultExporters.export(result, Paths.get(""), "JSON")); + Path path = Paths.get(""); + assertThrows(UncheckedIOException.class, () -> SecurityAnalysisResultExporters.export(result, path, "JSON")); // Check invalid format - assertThrows(PowsyblException.class, () -> SecurityAnalysisResultExporters.export(result, tmpDir.resolve("data"), "XXX")); + Path pathInvalidFormat = tmpDir.resolve("data"); + assertThrows(PowsyblException.class, () -> SecurityAnalysisResultExporters.export(result, pathInvalidFormat, "XXX")); } @Test @@ -160,15 +160,15 @@ void roundTripJsonWithProperties() throws IOException { roundTripTest(result, ExporterTest::writeJsonWithProperties, SecurityAnalysisResultDeserializer::read, "/SecurityAnalysisResult.json"); - BiConsumer exporter = (res, path) -> { - SecurityAnalysisResultExporters.export(res, null, path, "JSON"); - }; + BiConsumer exporter = (res, path) -> SecurityAnalysisResultExporters.export(res, null, path, "JSON"); roundTripTest(result, exporter, SecurityAnalysisResultDeserializer::read, "/SecurityAnalysisResult.json"); // Check invalid path - assertThrows(UncheckedIOException.class, () -> SecurityAnalysisResultExporters.export(result, null, Paths.get(""), "JSON")); + Path emptyPath = Paths.get(""); + assertThrows(UncheckedIOException.class, () -> SecurityAnalysisResultExporters.export(result, null, emptyPath, "JSON")); // Check invalid format - assertThrows(PowsyblException.class, () -> SecurityAnalysisResultExporters.export(result, null, tmpDir.resolve("data"), "XXX")); + Path pathInvalidFormat = tmpDir.resolve("data"); + assertThrows(PowsyblException.class, () -> SecurityAnalysisResultExporters.export(result, null, pathInvalidFormat, "XXX")); } private static void writeJson(SecurityAnalysisResult result, Path path) { From 2a36e4edb59effbf2448e2aa301accd7b530af67 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:32:28 +0200 Subject: [PATCH 69/84] swap supplier Signed-off-by: Nicolas Rol --- .../com/powsybl/shortcircuit/json/FaultResultDeserializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shortcircuit-api/src/main/java/com/powsybl/shortcircuit/json/FaultResultDeserializer.java b/shortcircuit-api/src/main/java/com/powsybl/shortcircuit/json/FaultResultDeserializer.java index 8574db02d06..b276bad5216 100644 --- a/shortcircuit-api/src/main/java/com/powsybl/shortcircuit/json/FaultResultDeserializer.java +++ b/shortcircuit-api/src/main/java/com/powsybl/shortcircuit/json/FaultResultDeserializer.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; -import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.Extension; import com.powsybl.commons.extensions.ExtensionJsonSerializer; @@ -24,6 +23,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; /** * @author Teofil-Calin BANC {@literal } From 02a54ff2ccc425ebf3b1fef98d6686df0e011c02 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:39:25 +0200 Subject: [PATCH 70/84] replaced 3 tests with one parametrized Signed-off-by: Nicolas Rol --- .../ShortCircuitParametersTest.java | 60 ++++++++++--------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/shortcircuit-api/src/test/java/com/powsybl/shortcircuit/ShortCircuitParametersTest.java b/shortcircuit-api/src/test/java/com/powsybl/shortcircuit/ShortCircuitParametersTest.java index 3f3898f7804..9e5e6a96138 100644 --- a/shortcircuit-api/src/test/java/com/powsybl/shortcircuit/ShortCircuitParametersTest.java +++ b/shortcircuit-api/src/test/java/com/powsybl/shortcircuit/ShortCircuitParametersTest.java @@ -25,6 +25,9 @@ import com.powsybl.shortcircuit.json.JsonShortCircuitParameters; import org.apache.commons.lang3.Range; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.io.InputStream; @@ -33,6 +36,8 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @@ -149,7 +154,7 @@ void testExtensions() { assertEquals(1, parameters.getExtensions().size()); assertTrue(parameters.getExtensions().contains(dummyExtension)); - assertTrue(parameters.getExtensionByName(DUMMY_EXTENSION_NAME) instanceof DummyExtension); + assertInstanceOf(DummyExtension.class, parameters.getExtensionByName(DUMMY_EXTENSION_NAME)); assertNotNull(parameters.getExtension(DummyExtension.class)); } @@ -193,8 +198,8 @@ void testConfigLoader() throws IOException { Path cfgFile = cfgDir.resolve("config.yml"); Path voltageDataFile = cfgDir.resolve("voltage-ranges.json"); - Files.copy(getClass().getResourceAsStream("/config.yml"), cfgFile); - Files.copy(getClass().getResourceAsStream("/voltage-ranges.json"), voltageDataFile); + Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/config.yml")), cfgFile); + Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/voltage-ranges.json")), voltageDataFile); PlatformConfig platformConfig = new PlatformConfig(new YamlModuleConfigRepository(cfgFile), cfgDir); ShortCircuitParameters parameters = ShortCircuitParameters.load(platformConfig); assertFalse(parameters.isWithLimitViolations()); @@ -297,10 +302,11 @@ void readVersion12() { } @Test - void testInvalidVersion12VoltageNotSupportedInVoltageRange() { - InputStream is = getClass().getResourceAsStream("/ShortCircuitParametersVersion12Invalid.json"); - UncheckedIOException e = assertThrows(UncheckedIOException.class, () -> JsonShortCircuitParameters.read(is)); - assertTrue(e.getMessage().contains("VoltageRange. Tag: voltage is not valid for version 1.2. Version should be >= 1.3")); + void testInvalidVersion12VoltageNotSupportedInVoltageRange() throws IOException { + try (InputStream is = getClass().getResourceAsStream("/ShortCircuitParametersVersion12Invalid.json")) { + UncheckedIOException e = assertThrows(UncheckedIOException.class, () -> JsonShortCircuitParameters.read(is)); + assertTrue(e.getMessage().contains("VoltageRange. Tag: voltage is not valid for version 1.2. Version should be >= 1.3")); + } } @Test @@ -366,25 +372,33 @@ void testLoadFromConfigButVoltageRangeMissing() throws IOException { Path cfgDir = Files.createDirectory(fileSystem.getPath("config")); Path cfgFile = cfgDir.resolve("wrongConfig.yml"); - Files.copy(getClass().getResourceAsStream("/wrongConfig.yml"), cfgFile); + Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/wrongConfig.yml")), cfgFile); PlatformConfig platformConfig = new PlatformConfig(new YamlModuleConfigRepository(cfgFile), cfgDir); assertThrows(PowsyblException.class, () -> ShortCircuitParameters.load(platformConfig)); } - @Test - void testReadButVoltageRangeMissing() { - InputStream stream = getClass().getResourceAsStream("/ShortCircuitParametersConfiguredWithoutVoltageRanges.json"); - PowsyblException e0 = assertThrows(PowsyblException.class, () -> JsonShortCircuitParameters - .read(stream)); - assertEquals("Configured initial voltage profile but nominal voltage ranges with associated coefficients are missing.", e0.getMessage()); + private static Stream provideArguments() { + return Stream.of( + Arguments.of( + "/ShortCircuitParametersConfiguredWithoutVoltageRanges.json", + "Configured initial voltage profile but nominal voltage ranges with associated coefficients are missing."), + Arguments.of( + "/ShortCircuitParametersConfiguredWithEmptyVoltageRanges.json", + "Configured initial voltage profile but nominal voltage ranges with associated coefficients are missing."), + Arguments.of( + "/ShortCircuitParametersWithUnsortedOverlappingVoltageRanges.json", + "Voltage ranges for configured initial voltage profile are overlapping") + ); } - @Test - void testReadButVoltageRangeEmpty() { - InputStream stream = getClass().getResourceAsStream("/ShortCircuitParametersConfiguredWithEmptyVoltageRanges.json"); - PowsyblException e0 = assertThrows(PowsyblException.class, () -> JsonShortCircuitParameters + @ParameterizedTest + @MethodSource("provideArguments") + void testReadButVoltageRangeExceptions(String jsonFileName, String exceptionMessage) throws IOException { + try (InputStream stream = getClass().getResourceAsStream(jsonFileName)) { + PowsyblException e0 = assertThrows(PowsyblException.class, () -> JsonShortCircuitParameters .read(stream)); - assertEquals("Configured initial voltage profile but nominal voltage ranges with associated coefficients are missing.", e0.getMessage()); + assertEquals(exceptionMessage, e0.getMessage()); + } } @Test @@ -418,14 +432,6 @@ void testInvalidSubtransientCoefficient() { assertEquals("subTransientCoefficient > 1", e1.getMessage()); } - @Test - void testReadWithUnsortedRanges() { - InputStream stream = getClass().getResourceAsStream("/ShortCircuitParametersWithUnsortedOverlappingVoltageRanges.json"); - PowsyblException e0 = assertThrows(PowsyblException.class, () -> JsonShortCircuitParameters - .read(stream)); - assertEquals("Voltage ranges for configured initial voltage profile are overlapping", e0.getMessage()); - } - @Test void testVoltageRangeWithSpecificVoltage() { VoltageRange range = new VoltageRange(100, 200, 0.9, 150); From fe39abe794e934ae011a27bc89d66f4c71dafe3d Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:42:37 +0200 Subject: [PATCH 71/84] fix TimeSeriesMetadata issues Signed-off-by: Nicolas Rol --- .../java/com/powsybl/timeseries/TimeSeriesMetadata.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/time-series/time-series-api/src/main/java/com/powsybl/timeseries/TimeSeriesMetadata.java b/time-series/time-series-api/src/main/java/com/powsybl/timeseries/TimeSeriesMetadata.java index f4f01616861..b4c8a570930 100644 --- a/time-series/time-series-api/src/main/java/com/powsybl/timeseries/TimeSeriesMetadata.java +++ b/time-series/time-series-api/src/main/java/com/powsybl/timeseries/TimeSeriesMetadata.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; -import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.io.UncheckedIOException; @@ -33,7 +32,7 @@ public class TimeSeriesMetadata { private final TimeSeriesIndex index; public TimeSeriesMetadata(String name, TimeSeriesDataType dataType, TimeSeriesIndex index) { - this(name, dataType, ImmutableMap.of(), index); + this(name, dataType, Collections.unmodifiableMap(new LinkedHashMap<>()), index); } public TimeSeriesMetadata(String name, TimeSeriesDataType dataType, Map tags, TimeSeriesIndex index) { @@ -84,10 +83,10 @@ public void writeJson(JsonGenerator generator) { } } - private static class JsonParsingContext { + private static final class JsonParsingContext { private String name; private TimeSeriesDataType dataType; - private Map tags = new LinkedHashMap<>(); + private final Map tags = new LinkedHashMap<>(); private TimeSeriesIndex index; private boolean insideTags = false; From dc113b4224be3a8db71dd6a43a8f5a28e84b5024 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:49:55 +0200 Subject: [PATCH 72/84] replace ImmutableMap with Collections.unmodifiableMap(LinkedHashMap) Signed-off-by: Nicolas Rol --- .../java/com/powsybl/tools/AbstractVersion.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tools/src/main/java/com/powsybl/tools/AbstractVersion.java b/tools/src/main/java/com/powsybl/tools/AbstractVersion.java index b545d18eeda..cf68c577743 100644 --- a/tools/src/main/java/com/powsybl/tools/AbstractVersion.java +++ b/tools/src/main/java/com/powsybl/tools/AbstractVersion.java @@ -7,8 +7,8 @@ */ package com.powsybl.tools; -import com.google.common.collect.ImmutableMap; - +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -61,11 +61,13 @@ public long getBuildTimestamp() { } public Map toMap() { - return ImmutableMap.of("repositoryName", repositoryName, - "mavenProjectVersion", mavenProjectVersion, - "gitVersion", gitVersion, - "gitBranch", gitBranch, - "buildTimestamp", Version.convertBuildTimestamp(buildTimestamp)); + Map map = new LinkedHashMap<>(); + map.put("repositoryName", repositoryName); + map.put("mavenProjectVersion", mavenProjectVersion); + map.put("gitVersion", gitVersion); + map.put("gitBranch", gitBranch); + map.put("buildTimestamp", Version.convertBuildTimestamp(buildTimestamp)); + return Collections.unmodifiableMap(map); } @Override From aafadaa141b0c923d9f118ceb4011ac8e0fd1603 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:52:33 +0200 Subject: [PATCH 73/84] replace XMLSchema.STRING with XSD.STRING Signed-off-by: Nicolas Rol --- .../java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java b/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java index e9d98aaef09..80464294e8c 100644 --- a/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java +++ b/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java @@ -22,6 +22,7 @@ import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XMLSchema; +import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.rdfxml.RDFXMLWriter; @@ -174,7 +175,7 @@ private void writeLiteral(Value obj) throws IOException { if (isXMLLiteral) { writeAttribute(RDF.NAMESPACE, "parseType", "Literal"); - } else if (!datatype.equals(XMLSchema.STRING)) { + } else if (!datatype.equals(XSD.STRING)) { writeAttribute(RDF.NAMESPACE, "datatype", datatype.toString()); } } From f6381cf7043fdb6dfe2bba5387b2ef7a799da8fe Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 14:53:15 +0200 Subject: [PATCH 74/84] replace XMLSchema.STRING with XSD.STRING Signed-off-by: Nicolas Rol --- .../java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java | 1 - 1 file changed, 1 deletion(-) diff --git a/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java b/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java index 80464294e8c..1117520e913 100644 --- a/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java +++ b/triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/PowsyblWriter.java @@ -21,7 +21,6 @@ import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.XMLSchema; import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.rdfxml.RDFXMLWriter; From 8194926e457e504f6f33a8ac672bb4a4d7c38b37 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 10 Apr 2024 15:14:58 +0200 Subject: [PATCH 75/84] regroup 17 tests in 4 parametrized tests Signed-off-by: Nicolas Rol --- .../ucte/network/io/UcteRecordWriterTest.java | 239 ++++-------------- 1 file changed, 56 insertions(+), 183 deletions(-) diff --git a/ucte/ucte-network/src/test/java/com/powsybl/ucte/network/io/UcteRecordWriterTest.java b/ucte/ucte-network/src/test/java/com/powsybl/ucte/network/io/UcteRecordWriterTest.java index 6c952dc23ac..f87bf203c7f 100644 --- a/ucte/ucte-network/src/test/java/com/powsybl/ucte/network/io/UcteRecordWriterTest.java +++ b/ucte/ucte-network/src/test/java/com/powsybl/ucte/network/io/UcteRecordWriterTest.java @@ -7,235 +7,108 @@ */ package com.powsybl.ucte.network.io; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -import java.io.*; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Sebastien Murgey {@literal } */ class UcteRecordWriterTest { - @Test - void shouldWriteZeroPaddedPositiveDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = 3.14; - recordWriter.writeDouble(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("3.1400%n"), writer.toString()); - } - - @Test - void shouldWriteShrinkedPositiveDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = 3.1415927; - recordWriter.writeDouble(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("3.1415%n"), writer.toString()); + private static Stream provideDoubleArguments() { + return Stream.of( + Arguments.of(3.14, "3.1400%n"), + Arguments.of(3.1415927, "3.1415%n"), + Arguments.of(-3.1, "-3.100%n"), + Arguments.of(0.0001, "0.0001%n"), + Arguments.of(999999.9, "999999%n"), + Arguments.of(-99999.9, "-99999%n"), + Arguments.of(-Double.NaN, "%n") + ); } - @Test - void shouldWriteZeroPaddedNegativeDouble() throws IOException { + @ParameterizedTest + @MethodSource("provideDoubleArguments") + void shouldWriteDoubleTests(double value, String expected) throws IOException { StringWriter writer = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(writer); UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - double input = -3.1; - recordWriter.writeDouble(input, 0, 6); + recordWriter.writeDouble(value, 0, 6); recordWriter.newLine(); bufferedWriter.close(); - assertEquals(String.format("-3.100%n"), writer.toString()); + assertEquals(String.format(expected), writer.toString()); } - @Test - void shouldNotUseScientificNotationForSmallDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = 0.0001; - recordWriter.writeDouble(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("0.0001%n"), writer.toString()); - } - - @Test - void shouldReturnEmptyValueOnNanInput() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = Double.NaN; - recordWriter.writeDouble(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("%n"), writer.toString()); + private static Stream provideDoubleForFailingWriting() { + return Stream.of( + Arguments.of(12345678), + Arguments.of(-12345678), + Arguments.of(1000000.1), + Arguments.of(-100000.1) + ); } - @Test - void shouldFailOnBigPositiveDouble() throws IOException { + @ParameterizedTest + @MethodSource("provideDoubleForFailingWriting") + void shouldFailWriteDoubleTests(double value) throws IOException { StringWriter writer = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(writer); UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - double input = 12345678; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeDouble(input, 0, 6)); + assertThrows(IllegalArgumentException.class, () -> recordWriter.writeDouble(value, 0, 6)); recordWriter.newLine(); bufferedWriter.close(); } - @Test - void shouldFailOnBigNegativeDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = -12345678; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeDouble(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); + private static Stream provideIntArguments() { + return Stream.of( + Arguments.of(999999, "999999%n"), + Arguments.of(-99999, "-99999%n") + ); } - @Test - void shouldSucceedOnLimitBigPositiveDouble() throws IOException { + @ParameterizedTest + @MethodSource("provideIntArguments") + void shouldWriteIntTests(int value, String expected) throws IOException { StringWriter writer = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(writer); UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - double input = 999999.9; - recordWriter.writeDouble(input, 0, 6); + recordWriter.writeInteger(value, 0, 6); recordWriter.newLine(); bufferedWriter.close(); - assertEquals(String.format("999999%n"), writer.toString()); - } - - @Test - void shouldFailOnLimitBigPositiveDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = 1000000.1; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeDouble(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); + assertEquals(String.format(expected), writer.toString()); } - @Test - void shouldSucceedOnLimitBigNegativeDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = -99999.9; - recordWriter.writeDouble(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("-99999%n"), writer.toString()); - } - - @Test - void shouldFailOnLimitBigNegativeDouble() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - double input = -100000.1; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeDouble(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); - } - - @Test - void shouldFailOnBigPositiveInteger() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - int input = 12345678; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeInteger(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); - } - - @Test - void shouldFailOnBigNegativeInteger() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - int input = -12345678; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeInteger(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); - } - - @Test - void shouldSucceedOnLimitBigPositiveInteger() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - int input = 999999; - recordWriter.writeInteger(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("999999%n"), writer.toString()); - } - - @Test - void shouldFailOnLimitBigPositiveInteger() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - int input = 1000000; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeInteger(input, 0, 6)); - recordWriter.newLine(); - bufferedWriter.close(); - } - - @Test - void shouldSucceedOnLimitBigNegativeInteger() throws IOException { - StringWriter writer = new StringWriter(); - BufferedWriter bufferedWriter = new BufferedWriter(writer); - UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - - int input = -99999; - recordWriter.writeInteger(input, 0, 6); - recordWriter.newLine(); - bufferedWriter.close(); - - assertEquals(String.format("-99999%n"), writer.toString()); + private static Stream provideIntForFailingWriting() { + return Stream.of( + Arguments.of(12345678), + Arguments.of(-12345678), + Arguments.of(1000000), + Arguments.of(-100000) + ); } - @Test - void shouldFailOnLimitBigNegativeInteger() throws IOException { + @ParameterizedTest + @MethodSource("provideIntForFailingWriting") + void shouldFailWriteIntTests(int value) throws IOException { StringWriter writer = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(writer); UcteRecordWriter recordWriter = new UcteRecordWriter(bufferedWriter); - int input = -100000; - assertThrows(IllegalArgumentException.class, () -> recordWriter.writeInteger(input, 0, 6)); + assertThrows(IllegalArgumentException.class, () -> recordWriter.writeInteger(value, 0, 6)); recordWriter.newLine(); bufferedWriter.close(); } From bd66190528770505f13abd8c14ee34c8d94ca175 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Tue, 16 Apr 2024 08:40:30 +0200 Subject: [PATCH 76/84] switch conditions Signed-off-by: Nicolas Rol --- .../src/main/java/com/powsybl/commons/parameters/Parameter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java b/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java index 8a860111ef4..2dc99ce81fe 100644 --- a/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java +++ b/commons/src/main/java/com/powsybl/commons/parameters/Parameter.java @@ -180,7 +180,7 @@ private static T read(Properties parameters, Parameter configuredParameter, } } // if none, use configured parameters - if (isPresent.test(value) && value != null) { + if (value != null && isPresent.test(value)) { return value; } return defaultValue; From 81e55d10dc49e0d7485128341a9b94adc67cb1d2 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 09:52:59 +0200 Subject: [PATCH 77/84] fix for review Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 24 +++++++-------- .../config/ComponentDefaultConfig.java | 14 ++++++--- .../UncheckedInvocationTargetException.java | 29 +++++++++++++++++++ .../UncheckedNoSuchMethodException.java | 28 ++++++++++++++++++ .../com/powsybl/commons/json/JsonUtil.java | 4 +-- .../DefaultComputationManagerConfig.java | 12 ++++---- .../com/powsybl/iidm/serde/XMLImporter.java | 4 +-- .../validation/CandidateComputations.java | 2 ++ .../loadflow/validation/ValidationUtils.java | 13 ++++----- .../powsybl/psse/converter/PsseExporter.java | 2 +- 10 files changed, 95 insertions(+), 37 deletions(-) create mode 100644 commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java create mode 100644 commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index d3ef0fa506d..53f353a6935 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -512,20 +512,20 @@ private static T3xFlow threeWindingsTransformerFlow(ThreeWindingsTransformer twt private boolean sameFlow(T2xFlow expected, T2xFlow actual) { double tol = 0.00001; - return !(Math.abs(expected.p1 - actual.p1) > tol) && - !(Math.abs(expected.q1 - actual.q1) > tol) && - !(Math.abs(expected.p2 - actual.p2) > tol) && - !(Math.abs(expected.q2 - actual.q2) > tol); + return Math.abs(expected.p1 - actual.p1) <= tol && + Math.abs(expected.q1 - actual.q1) <= tol && + Math.abs(expected.p2 - actual.p2) <= tol && + Math.abs(expected.q2 - actual.q2) <= tol; } private boolean sameFlow(T3xFlow expected, T3xFlow actual) { double tol = 0.00001; - return !(Math.abs(expected.p1 - actual.p1) > tol) && - !(Math.abs(expected.q1 - actual.q1) > tol) && - !(Math.abs(expected.p2 - actual.p2) > tol) && - !(Math.abs(expected.q2 - actual.q2) > tol) && - !(Math.abs(expected.p3 - actual.p3) > tol) && - !(Math.abs(expected.q3 - actual.q3) > tol); + return Math.abs(expected.p1 - actual.p1) <= tol && + Math.abs(expected.q1 - actual.q1) <= tol && + Math.abs(expected.p2 - actual.p2) <= tol && + Math.abs(expected.q2 - actual.q2) <= tol && + Math.abs(expected.p3 - actual.p3) <= tol && + Math.abs(expected.q3 - actual.q3) <= tol; } private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowParameters, Conversion.Config config) { @@ -550,13 +550,11 @@ private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowP case SPLIT: t3wtSplitShuntAdmittance = true; } - boolean twtSplitShuntAdmittance = false; if (t2wtSplitShuntAdmittance != t3wtSplitShuntAdmittance) { throw new PowsyblException(String.format("Unexpected SplitShuntAdmittance configuration %s %s", t2wtSplitShuntAdmittance, t3wtSplitShuntAdmittance)); - } else if (t2wtSplitShuntAdmittance) { - twtSplitShuntAdmittance = true; } + boolean twtSplitShuntAdmittance = t2wtSplitShuntAdmittance; copyLoadFlowParameters.setTwtSplitShuntAdmittance(twtSplitShuntAdmittance); diff --git a/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java b/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java index 48bd2bb5698..0015f0a5744 100644 --- a/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java +++ b/commons/src/main/java/com/powsybl/commons/config/ComponentDefaultConfig.java @@ -10,6 +10,8 @@ import com.powsybl.commons.PowsyblException; import com.powsybl.commons.exceptions.UncheckedIllegalAccessException; import com.powsybl.commons.exceptions.UncheckedInstantiationException; +import com.powsybl.commons.exceptions.UncheckedInvocationTargetException; +import com.powsybl.commons.exceptions.UncheckedNoSuchMethodException; import java.lang.reflect.InvocationTargetException; import java.util.Objects; @@ -75,8 +77,10 @@ public T newFactoryImpl(Class factoryBaseClass) { throw new UncheckedIllegalAccessException(e); } catch (InstantiationException e) { throw new UncheckedInstantiationException(e); - } catch (InvocationTargetException | NoSuchMethodException e) { - throw new PowsyblException(e); + } catch (NoSuchMethodException e) { + throw new UncheckedNoSuchMethodException(e); + } catch (InvocationTargetException e) { + throw new UncheckedInvocationTargetException(e); } } @@ -88,8 +92,10 @@ public T newFactoryImpl(Class factoryBaseClass, Class def throw new UncheckedIllegalAccessException(e); } catch (InstantiationException e) { throw new UncheckedInstantiationException(e); - } catch (NoSuchMethodException | InvocationTargetException e) { - throw new PowsyblException(e); + } catch (NoSuchMethodException e) { + throw new UncheckedNoSuchMethodException(e); + } catch (InvocationTargetException e) { + throw new UncheckedInvocationTargetException(e); } } } diff --git a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java new file mode 100644 index 00000000000..83d533acc25 --- /dev/null +++ b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * SPDX-License-Identifier: MPL-2.0 + */ +package com.powsybl.commons.exceptions; + +import java.io.Serial; +import java.lang.reflect.InvocationTargetException; + +/** + * @author Nicolas Rol {@literal } + */ +public class UncheckedInvocationTargetException extends RuntimeException { + + @Serial + private static final long serialVersionUID = -1317642521380494026L; + + public UncheckedInvocationTargetException(InvocationTargetException cause) { + super(cause); + } + + @Override + public synchronized InstantiationException getCause() { + return (InstantiationException) super.getCause(); + } +} diff --git a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java new file mode 100644 index 00000000000..68d9a538332 --- /dev/null +++ b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * SPDX-License-Identifier: MPL-2.0 + */ +package com.powsybl.commons.exceptions; + +import java.io.Serial; + +/** + * @author Nicolas Rol {@literal } + */ +public class UncheckedNoSuchMethodException extends RuntimeException { + + @Serial + private static final long serialVersionUID = -6199102529457589212L; + + public UncheckedNoSuchMethodException(NoSuchMethodException cause) { + super(cause); + } + + @Override + public synchronized InstantiationException getCause() { + return (InstantiationException) super.getCause(); + } +} diff --git a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java index 7ca6119cfe6..4b754403d41 100644 --- a/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java +++ b/commons/src/main/java/com/powsybl/commons/json/JsonUtil.java @@ -352,7 +352,7 @@ public static List> updateExtensions(JsonPar Objects.requireNonNull(supplier); List> extensions = new ArrayList<>(); - if (parser.currentToken() != com.fasterxml.jackson.core.JsonToken.START_OBJECT) { + if (parser.currentToken() != JsonToken.START_OBJECT) { throw new PowsyblException("Error updating extensions, \"extensions\" field expected START_OBJECT, got " + parser.currentToken()); } @@ -504,7 +504,7 @@ public static void parseObject(JsonParser parser, boolean polymorphic, FieldHand Objects.requireNonNull(parser); Objects.requireNonNull(fieldHandler); try { - com.fasterxml.jackson.core.JsonToken token = parser.currentToken(); + JsonToken token = parser.currentToken(); if (!polymorphic && token != JsonToken.START_OBJECT) { throw new PowsyblException("Start object token was expected instead got: " + token); } diff --git a/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java b/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java index 20f1845b641..b41cbd9e706 100644 --- a/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java +++ b/computation/src/main/java/com/powsybl/computation/DefaultComputationManagerConfig.java @@ -7,12 +7,8 @@ */ package com.powsybl.computation; -import com.powsybl.commons.PowsyblException; import com.powsybl.commons.config.PlatformConfig; -import com.powsybl.commons.exceptions.UncheckedClassCastExceptionException; -import com.powsybl.commons.exceptions.UncheckedClassNotFoundException; -import com.powsybl.commons.exceptions.UncheckedIllegalAccessException; -import com.powsybl.commons.exceptions.UncheckedInstantiationException; +import com.powsybl.commons.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,8 +76,10 @@ private ComputationManager createComputationManager(Class getComputations() { return COMPUTATIONS.get(); @@ -38,6 +39,7 @@ public static List getComputations() { /** * Get the list of all known candidate computations names. + * The returned list is immutable. */ public static List getComputationsNames() { return getComputations().stream().map(CandidateComputation::getName).toList(); diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java index 0c518c3462d..696fa65115b 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/ValidationUtils.java @@ -7,15 +7,14 @@ */ package com.powsybl.loadflow.validation; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.util.Objects; - -import com.powsybl.commons.PowsyblException; import com.powsybl.commons.config.ConfigurationException; import com.powsybl.loadflow.validation.io.ValidationWriter; import com.powsybl.loadflow.validation.io.ValidationWriterFactory; +import java.io.Writer; +import java.lang.reflect.InvocationTargetException; +import java.util.Objects; + /** * * @author Massimo Ferraro {@literal } @@ -36,10 +35,8 @@ public static ValidationWriter createValidationWriter(String id, ValidationConfi try { ValidationWriterFactory factory = config.getValidationOutputWriter().getValidationWriterFactory().getDeclaredConstructor().newInstance(); return factory.create(id, config.getTableFormatterFactory(), writer, config.isVerbose(), validationType, config.isCompareResults()); - } catch (InstantiationException | IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new ConfigurationException(e); - } catch (InvocationTargetException | NoSuchMethodException e) { - throw new PowsyblException(e); } } diff --git a/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java b/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java index db048a1b2ee..02b178785b1 100644 --- a/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java +++ b/psse/psse-converter/src/main/java/com/powsybl/psse/converter/PsseExporter.java @@ -63,7 +63,7 @@ public void export(Network network, Properties parameters, DataSource dataSource Context context = network.getExtension(PsseConversionContextExtension.class).getContext(); PsseVersion version = PsseVersion.fromRevision(updatePsseModel.getCaseIdentification().getRev()); if (context.getFileFormat() == FileFormat.JSON) { - if (Objects.requireNonNull(version.major()) == PsseVersion.Major.V35) { + if (version.major() == PsseVersion.Major.V35) { PowerFlowRawxData35 rawXData35 = new PowerFlowRawxData35(); try { rawXData35.write(updatePsseModel, context, dataSource); From 8457e18e6daf31b35925d3a4458d9b66959b9ad8 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 12:27:37 +0200 Subject: [PATCH 78/84] fix indentation Signed-off-by: Nicolas Rol --- .../test/TransformerConversionTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java index eb97e7a84e4..0905264d09f 100644 --- a/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java +++ b/cgmes/cgmes-conversion/src/test/java/com/powsybl/cgmes/conversion/test/TransformerConversionTest.java @@ -514,20 +514,20 @@ private boolean sameFlow(T2xFlow expected, T2xFlow actual) { double tol = 0.00001; // Comparison fails if actual has NaN values return Math.abs(expected.p1 - actual.p1) <= tol && - Math.abs(expected.q1 - actual.q1) <= tol && - Math.abs(expected.p2 - actual.p2) <= tol && - Math.abs(expected.q2 - actual.q2) <= tol; + Math.abs(expected.q1 - actual.q1) <= tol && + Math.abs(expected.p2 - actual.p2) <= tol && + Math.abs(expected.q2 - actual.q2) <= tol; } private boolean sameFlow(T3xFlow expected, T3xFlow actual) { double tol = 0.00001; // Comparison fails if actual has NaN values return Math.abs(expected.p1 - actual.p1) <= tol && - Math.abs(expected.q1 - actual.q1) <= tol && - Math.abs(expected.p2 - actual.p2) <= tol && - Math.abs(expected.q2 - actual.q2) <= tol && - Math.abs(expected.p3 - actual.p3) <= tol && - Math.abs(expected.q3 - actual.q3) <= tol; + Math.abs(expected.q1 - actual.q1) <= tol && + Math.abs(expected.p2 - actual.p2) <= tol && + Math.abs(expected.q2 - actual.q2) <= tol && + Math.abs(expected.p3 - actual.p3) <= tol && + Math.abs(expected.q3 - actual.q3) <= tol; } private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowParameters, Conversion.Config config) { @@ -555,7 +555,7 @@ private LoadFlowParameters defineLoadflowParameters(LoadFlowParameters loadFlowP if (t2wtSplitShuntAdmittance != t3wtSplitShuntAdmittance) { throw new PowsyblException(String.format("Unexpected SplitShuntAdmittance configuration %s %s", - t2wtSplitShuntAdmittance, t3wtSplitShuntAdmittance)); + t2wtSplitShuntAdmittance, t3wtSplitShuntAdmittance)); } boolean twtSplitShuntAdmittance = t2wtSplitShuntAdmittance; From b8ceacfb0125bb9da931202d5342910e30d1b9ce Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 14:03:03 +0200 Subject: [PATCH 79/84] coverage Signed-off-by: Nicolas Rol --- .../config/ComponentDefaultConfigTest.java | 13 ++++ .../commons/util/StringToIntMapperTest.java | 68 ++++++++++++++++++- .../DefaultComputationManagerConfigTest.java | 19 ++++++ 3 files changed, 97 insertions(+), 3 deletions(-) diff --git a/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java b/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java index fbe6c652efd..18cfb614eb4 100644 --- a/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java +++ b/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java @@ -9,6 +9,7 @@ import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; +import com.powsybl.commons.exceptions.UncheckedNoSuchMethodException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +17,7 @@ import java.io.IOException; import java.nio.file.FileSystem; +import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -31,6 +33,10 @@ interface A { static class B implements A { } + static class C implements A { + C(String a, String b) {} + } + private FileSystem fileSystem; private MapModuleConfig moduleConfig; private ComponentDefaultConfig config; @@ -69,4 +75,11 @@ void newFactoryImplTest() throws IOException { void newFactoryImplDefaultTest() throws IOException { assertTrue(config.newFactoryImpl(A.class, B.class) instanceof B); } + + @Test + void newFactoryExceptionTest() { + moduleConfig.setClassProperty(C.class.getSimpleName(), C.class); + assertThrows(UncheckedNoSuchMethodException.class, () -> config.newFactoryImpl(C.class)); + assertThrows(UncheckedNoSuchMethodException.class, () -> config.newFactoryImpl(A.class, C.class)); + } } diff --git a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java index 1cc10c7ff81..8555384280c 100644 --- a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java +++ b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java @@ -7,15 +7,23 @@ */ package com.powsybl.commons.util; +import static com.powsybl.commons.test.ComparisonUtils.compareTxt; +import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import com.powsybl.commons.PowsyblException; +import com.powsybl.commons.test.TestUtil; import org.junit.jupiter.api.Test; /** @@ -53,6 +61,60 @@ void test() throws IOException { } } + @Test + void testDump() throws IOException { + try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { + Path testDir = fileSystem.getPath("/tmp"); + Files.createDirectories(testDir); + Path outputFile = testDir.resolve("output.txt"); + + StringToIntMapper mapper = new StringToIntMapper<>(TestSubset.class); + String value = "value1"; + mapper.newInt(TestSubset.TYPE, value); + mapper.dump(outputFile); + + String expectedStr = "TYPE;value1;1\n"; + try (InputStream in = Files.newInputStream(outputFile)) { + compareTxt(expectedStr, in); + } catch (Exception e) { + fail(e); + } + } + } + + @Test + void testLoad() throws IOException { + try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { + Path testDir = fileSystem.getPath("/tmp"); + Files.createDirectories(testDir); + Path outputFile = testDir.resolve("output.txt"); + try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { + writer.write("TYPE;value1;1\n"); + } + + StringToIntMapper mapper = new StringToIntMapper<>(TestSubset.class); + mapper.load(outputFile); + + assertEquals(1, mapper.getInt(TestSubset.TYPE, "value1")); + } + } + + @Test + void testLoadException() throws IOException { + try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { + Path testDir = fileSystem.getPath("/tmp"); + Files.createDirectories(testDir); + Path outputFile = testDir.resolve("output.txt"); + try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { + writer.write("TYPE;value1;1;5\n"); + } + + StringToIntMapper mapper = new StringToIntMapper<>(TestSubset.class); + PowsyblException exception = assertThrows(PowsyblException.class, () -> mapper.load(outputFile)); + assertEquals("Bad format: TYPE;value1;1;5", exception.getMessage()); + } + } + private void testAddMapping(StringToIntMapper mapper) throws IOException { String value = "value1"; assertFalse(mapper.isMapped(TestSubset.TYPE, value)); diff --git a/computation/src/test/java/com/powsybl/computation/DefaultComputationManagerConfigTest.java b/computation/src/test/java/com/powsybl/computation/DefaultComputationManagerConfigTest.java index 7e1f3a6f0c9..4e20309efc6 100644 --- a/computation/src/test/java/com/powsybl/computation/DefaultComputationManagerConfigTest.java +++ b/computation/src/test/java/com/powsybl/computation/DefaultComputationManagerConfigTest.java @@ -11,6 +11,7 @@ import com.google.common.jimfs.Jimfs; import com.powsybl.commons.config.InMemoryPlatformConfig; import com.powsybl.commons.config.MapModuleConfig; +import com.powsybl.commons.exceptions.UncheckedNoSuchMethodException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,6 +40,16 @@ public ComputationManager create() { } } + static class ThirdComputationManagerFactory implements ComputationManagerFactory { + ThirdComputationManagerFactory(String a, String b) { + } + + @Override + public ComputationManager create() { + return Mockito.mock(ComputationManager.class); + } + } + private FileSystem fileSystem; @BeforeEach @@ -73,4 +84,12 @@ void test() { + ", longTimeExecutionComputationManagerFactoryClass=" + SecondComputationManagerFactory.class.getName() + ")", config.toString()); } + + @Test + void testExceptions() { + DefaultComputationManagerConfig config = new DefaultComputationManagerConfig( + FirstComputationManagerFactory.class, + ThirdComputationManagerFactory.class); + assertThrows(UncheckedNoSuchMethodException.class, config::createLongTimeExecutionComputationManager); + } } From 31d7ddcd8782c8a37b8747a04821e4d03ac126f5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 14:27:29 +0200 Subject: [PATCH 80/84] fix imports Signed-off-by: Nicolas Rol --- .../commons/util/StringToIntMapperTest.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java index 8555384280c..3b2981ebf2b 100644 --- a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java +++ b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java @@ -7,12 +7,10 @@ */ package com.powsybl.commons.util; -import static com.powsybl.commons.test.ComparisonUtils.compareTxt; -import static org.junit.Assert.assertThrows; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import com.powsybl.commons.PowsyblException; +import org.junit.jupiter.api.Test; import java.io.*; import java.nio.charset.StandardCharsets; @@ -20,11 +18,9 @@ import java.nio.file.Files; import java.nio.file.Path; -import com.google.common.jimfs.Configuration; -import com.google.common.jimfs.Jimfs; -import com.powsybl.commons.PowsyblException; -import com.powsybl.commons.test.TestUtil; -import org.junit.jupiter.api.Test; +import static com.powsybl.commons.test.ComparisonUtils.compareTxt; +import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * From f76c3bef7d5175cf84d33d35a1e481b8ce6286e4 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 14:49:35 +0200 Subject: [PATCH 81/84] fix exceptions Signed-off-by: Nicolas Rol --- .../exceptions/UncheckedInvocationTargetException.java | 4 ++-- .../commons/exceptions/UncheckedNoSuchMethodException.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java index 83d533acc25..01bdf9c44b4 100644 --- a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java +++ b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedInvocationTargetException.java @@ -23,7 +23,7 @@ public UncheckedInvocationTargetException(InvocationTargetException cause) { } @Override - public synchronized InstantiationException getCause() { - return (InstantiationException) super.getCause(); + public synchronized InvocationTargetException getCause() { + return (InvocationTargetException) super.getCause(); } } diff --git a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java index 68d9a538332..baa22c716fe 100644 --- a/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java +++ b/commons/src/main/java/com/powsybl/commons/exceptions/UncheckedNoSuchMethodException.java @@ -22,7 +22,7 @@ public UncheckedNoSuchMethodException(NoSuchMethodException cause) { } @Override - public synchronized InstantiationException getCause() { - return (InstantiationException) super.getCause(); + public synchronized NoSuchMethodException getCause() { + return (NoSuchMethodException) super.getCause(); } } From 64ab16a64edf6c2c754a0af4b5dcb0319db9b3d5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 14:51:04 +0200 Subject: [PATCH 82/84] fix checkstyle + newline character Signed-off-by: Nicolas Rol --- .../powsybl/commons/config/ComponentDefaultConfigTest.java | 2 +- .../java/com/powsybl/commons/util/StringToIntMapperTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java b/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java index 18cfb614eb4..55ee665418e 100644 --- a/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java +++ b/commons/src/test/java/com/powsybl/commons/config/ComponentDefaultConfigTest.java @@ -34,7 +34,7 @@ static class B implements A { } static class C implements A { - C(String a, String b) {} + C(String a, String b) { } } private FileSystem fileSystem; diff --git a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java index 3b2981ebf2b..0cab310c726 100644 --- a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java +++ b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java @@ -85,7 +85,7 @@ void testLoad() throws IOException { Files.createDirectories(testDir); Path outputFile = testDir.resolve("output.txt"); try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { - writer.write("TYPE;value1;1\n"); + writer.write("TYPE;value1;1" + System.lineSeparator()); } StringToIntMapper mapper = new StringToIntMapper<>(TestSubset.class); @@ -102,7 +102,7 @@ void testLoadException() throws IOException { Files.createDirectories(testDir); Path outputFile = testDir.resolve("output.txt"); try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { - writer.write("TYPE;value1;1;5\n"); + writer.write("TYPE;value1;1;5" + System.lineSeparator()); } StringToIntMapper mapper = new StringToIntMapper<>(TestSubset.class); From b5fdf093f668971afab2d92637d1b4c601bc7159 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 15:00:24 +0200 Subject: [PATCH 83/84] fix newline character + regroup exceptions + add comment Signed-off-by: Nicolas Rol --- .../java/com/powsybl/commons/util/StringToIntMapperTest.java | 2 +- .../validation/io/AbstractValidationFormatterWriter.java | 4 +--- .../main/java/com/powsybl/timeseries/TimeSeriesMetadata.java | 1 + 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java index 0cab310c726..9792d0a9d53 100644 --- a/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java +++ b/commons/src/test/java/com/powsybl/commons/util/StringToIntMapperTest.java @@ -69,7 +69,7 @@ void testDump() throws IOException { mapper.newInt(TestSubset.TYPE, value); mapper.dump(outputFile); - String expectedStr = "TYPE;value1;1\n"; + String expectedStr = "TYPE;value1;1" + System.lineSeparator(); try (InputStream in = Files.newInputStream(outputFile)) { compareTxt(expectedStr, in); } catch (Exception e) { diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java index 1a3e09ee772..c8489584f46 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java @@ -76,10 +76,8 @@ protected TableFormatter createTableFormatter(String id, Class()), index); } From de1526ed7069cd3f50aefca1849e9e650ea32ba5 Mon Sep 17 00:00:00 2001 From: Nicolas Rol Date: Wed, 24 Apr 2024 15:00:48 +0200 Subject: [PATCH 84/84] delete unused import Signed-off-by: Nicolas Rol --- .../io/AbstractValidationFormatterWriter.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java index c8489584f46..723f2b8039a 100644 --- a/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java +++ b/loadflow/loadflow-validation/src/main/java/com/powsybl/loadflow/validation/io/AbstractValidationFormatterWriter.java @@ -7,25 +7,23 @@ */ package com.powsybl.loadflow.validation.io; -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import com.powsybl.commons.PowsyblException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.powsybl.commons.io.table.Column; import com.powsybl.commons.io.table.TableFormatter; import com.powsybl.commons.io.table.TableFormatterConfig; import com.powsybl.commons.io.table.TableFormatterFactory; -import com.powsybl.iidm.network.TwoSides; import com.powsybl.iidm.network.StaticVarCompensator.RegulationMode; +import com.powsybl.iidm.network.TwoSides; import com.powsybl.iidm.network.util.TwtData; import com.powsybl.loadflow.validation.ValidationType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; /** *