diff --git a/CHANGELOG.md b/CHANGELOG.md index c614ee4b4..bc3f65b80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Deleted parameter initFiles, set parameter append to false by default [#791](https://github.com/ie3-institute/PowerSystemDataModel/issues/791) - Use nio paths instead of strings for file path [#723](https://github.com/ie3-institute/PowerSystemDataModel/issues/723) - Data source will throw an exceptions instead of returning an empty optionals [#707](https://github.com/ie3-institute/PowerSystemDataModel/issues/707) +- Improving `ValidationUtils` [#758](https://github.com/ie3-institute/PowerSystemDataModel/issues/758) ## [3.0.0] - 2023-02-16 diff --git a/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java new file mode 100644 index 000000000..0fc60cd13 --- /dev/null +++ b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java @@ -0,0 +1,25 @@ +/* + * © 2023. TU Dortmund University, + * Institute of Energy Systems, Energy Efficiency and Energy Economics, + * Research group Distribution grid planning and operation +*/ +package edu.ie3.datamodel.exceptions; + +import edu.ie3.datamodel.utils.ExceptionUtils; +import java.util.List; + +public class FailedValidationException extends ValidationException { + public FailedValidationException(String message, Throwable throwable) { + super(message, throwable); + } + + public FailedValidationException(String message) { + super(message); + } + + /** @param exceptions List of exceptions, which must not be empty */ + public FailedValidationException(List exceptions) { + super( + "Validation failed due to: \n" + ExceptionUtils.getMessages(exceptions), exceptions.get(0)); + } +} diff --git a/src/main/java/edu/ie3/datamodel/exceptions/InvalidEntityException.java b/src/main/java/edu/ie3/datamodel/exceptions/InvalidEntityException.java index 162acd0b1..744e08c25 100644 --- a/src/main/java/edu/ie3/datamodel/exceptions/InvalidEntityException.java +++ b/src/main/java/edu/ie3/datamodel/exceptions/InvalidEntityException.java @@ -13,12 +13,13 @@ public class InvalidEntityException extends ValidationException { private static final long serialVersionUID = 809496087520306374L; public InvalidEntityException(String faultDescription, UniqueEntity invalidEntity) { - super("Entity is invalid because of: " + faultDescription + " [" + invalidEntity + "]"); + super("Entity is invalid because of: \n" + faultDescription + " [" + invalidEntity + "]"); } public InvalidEntityException( String faultDescription, Throwable cause, UniqueEntity invalidEntity) { - super("Entity is invalid because of: " + faultDescription + " [" + invalidEntity + "]", cause); + super( + "Entity is invalid because of: \n" + faultDescription + " [" + invalidEntity + "]", cause); } public InvalidEntityException(String message, Throwable cause) { diff --git a/src/main/java/edu/ie3/datamodel/exceptions/ValidationException.java b/src/main/java/edu/ie3/datamodel/exceptions/ValidationException.java index 080602f9c..e74d70696 100644 --- a/src/main/java/edu/ie3/datamodel/exceptions/ValidationException.java +++ b/src/main/java/edu/ie3/datamodel/exceptions/ValidationException.java @@ -5,7 +5,7 @@ */ package edu.ie3.datamodel.exceptions; -public abstract class ValidationException extends RuntimeException { +public abstract class ValidationException extends Exception { protected ValidationException(String s) { super(s); } diff --git a/src/main/java/edu/ie3/datamodel/io/source/WeatherSource.java b/src/main/java/edu/ie3/datamodel/io/source/WeatherSource.java index c3702993f..31f5150f0 100644 --- a/src/main/java/edu/ie3/datamodel/io/source/WeatherSource.java +++ b/src/main/java/edu/ie3/datamodel/io/source/WeatherSource.java @@ -119,8 +119,7 @@ public List> buildTimeBasedValues( return factory.get(data.get()); }), "TimeBasedValue") - .transformF(SourceException::new) - .getOrThrow() - .toList(); + .transform(Stream::toList, SourceException::new) + .getOrThrow(); } } diff --git a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvIdCoordinateSource.java b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvIdCoordinateSource.java index 9926e29c0..d7f293f0f 100644 --- a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvIdCoordinateSource.java +++ b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvIdCoordinateSource.java @@ -67,9 +67,9 @@ private Map setupIdToCoordinateMap() throws SourceException { .map(fieldToValues -> new SimpleFactoryData(fieldToValues, Pair.class)) .map(factory::get), "Pair") - .transformF(SourceException::new) - .getOrThrow() - .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); + .transform( + s -> s.collect(Collectors.toMap(Pair::getKey, Pair::getValue)), SourceException::new) + .getOrThrow(); } /** diff --git a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvJointGridContainerSource.java b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvJointGridContainerSource.java index 31b209676..2fa9e0f2a 100644 --- a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvJointGridContainerSource.java +++ b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvJointGridContainerSource.java @@ -6,6 +6,7 @@ package edu.ie3.datamodel.io.source.csv; import edu.ie3.datamodel.exceptions.FileException; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.exceptions.SourceException; import edu.ie3.datamodel.io.naming.DefaultDirectoryHierarchy; import edu.ie3.datamodel.io.naming.EntityPersistenceNamingStrategy; @@ -25,7 +26,7 @@ private CsvJointGridContainerSource() {} public static JointGridContainer read( String gridName, String csvSep, Path directoryPath, boolean isHierarchic) - throws SourceException, FileException { + throws SourceException, FileException, InvalidGridException { /* Parameterization */ FileNamingStrategy namingStrategy; diff --git a/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java b/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java index 030f9dc61..333056974 100644 --- a/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java +++ b/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java @@ -52,7 +52,7 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - protected abstract static class UniqueEntityCopyBuilder + public abstract static class UniqueEntityCopyBuilder implements UniqueEntityBuilder { private UUID uuid; @@ -61,16 +61,16 @@ protected UniqueEntityCopyBuilder(UniqueEntity entity) { this.uuid = entity.getUuid(); } - public T uuid(UUID uuid) { + public B uuid(UUID uuid) { this.uuid = uuid; - return childInstance(); + return thisInstance(); } protected UUID getUuid() { return uuid; } - protected abstract T childInstance(); + protected abstract B thisInstance(); } protected interface UniqueEntityBuilder { diff --git a/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java b/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java index 646ac245e..a0840fbcc 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java @@ -58,7 +58,7 @@ public String getId() { return id; } - public abstract UniqueEntityBuilder copy(); + public abstract AssetInputCopyBuilder copy(); @Override public boolean equals(Object o) { @@ -95,8 +95,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - protected abstract static class AssetInputCopyBuilder> - extends UniqueEntityCopyBuilder { + public abstract static class AssetInputCopyBuilder> + extends UniqueEntityCopyBuilder { private String id; private OperatorInput operator; @@ -109,19 +109,19 @@ protected AssetInputCopyBuilder(AssetInput entity) { this.operationTime = entity.getOperationTime(); } - public T id(String id) { + public B id(String id) { this.id = id; - return childInstance(); + return thisInstance(); } - public T operator(OperatorInput operator) { + public B operator(OperatorInput operator) { this.operator = operator; - return childInstance(); + return thisInstance(); } - public T operationTime(OperationTime operationTime) { + public B operationTime(OperationTime operationTime) { this.operationTime = operationTime; - return childInstance(); + return thisInstance(); } protected String getId() { @@ -140,6 +140,6 @@ protected OperationTime getOperationTime() { public abstract AssetInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java b/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java index 07688612d..11e90713c 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java @@ -98,6 +98,7 @@ public boolean getQ() { return q; } + @Override public MeasurementUnitInputCopyBuilder copy() { return new MeasurementUnitInputCopyBuilder(this); } @@ -206,7 +207,7 @@ public MeasurementUnitInputCopyBuilder q(boolean q) { } @Override - protected MeasurementUnitInputCopyBuilder childInstance() { + protected MeasurementUnitInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java b/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java index b70a095b1..0366964e0 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java @@ -115,6 +115,7 @@ public int getSubnet() { return subnet; } + @Override public NodeInputCopyBuilder copy() { return new NodeInputCopyBuilder(this); } @@ -226,7 +227,7 @@ public NodeInputCopyBuilder subnet(int subnet) { } @Override - protected NodeInputCopyBuilder childInstance() { + protected NodeInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/OperatorInput.java b/src/main/java/edu/ie3/datamodel/models/input/OperatorInput.java index b65422ae2..1fc2005cf 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/OperatorInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/OperatorInput.java @@ -83,7 +83,7 @@ public OperatorInputCopyBuilder id(String id) { } @Override - protected OperatorInputCopyBuilder childInstance() { + protected OperatorInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/ConnectorInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/ConnectorInput.java index dd7ed2028..cc5965af3 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/ConnectorInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/ConnectorInput.java @@ -127,8 +127,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class ConnectorInputCopyBuilder> - extends AssetInputCopyBuilder { + public abstract static class ConnectorInputCopyBuilder> + extends AssetInputCopyBuilder { private NodeInput nodeA; private NodeInput nodeB; @@ -141,19 +141,19 @@ protected ConnectorInputCopyBuilder(ConnectorInput entity) { this.parallelDevices = entity.getParallelDevices(); } - public T nodeA(NodeInput nodeA) { + public B nodeA(NodeInput nodeA) { this.nodeA = nodeA; - return childInstance(); + return thisInstance(); } - public T nodeB(NodeInput nodeB) { + public B nodeB(NodeInput nodeB) { this.nodeB = nodeB; - return childInstance(); + return thisInstance(); } - public T parallelDevices(int parallelDevices) { + public B parallelDevices(int parallelDevices) { this.parallelDevices = parallelDevices; - return childInstance(); + return thisInstance(); } protected NodeInput getNodeA() { @@ -172,6 +172,6 @@ protected int getParallelDevices() { public abstract ConnectorInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/LineInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/LineInput.java index c5bbe27ed..2d77bd425 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/LineInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/LineInput.java @@ -117,6 +117,7 @@ public OlmCharacteristicInput getOlmCharacteristic() { return olmCharacteristic; } + @Override public LineInputCopyBuilder copy() { return new LineInputCopyBuilder(this); } @@ -223,7 +224,7 @@ public LineInputCopyBuilder olmCharacteristic(OlmCharacteristicInput olmCharacte } @Override - protected LineInputCopyBuilder childInstance() { + protected LineInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/SwitchInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/SwitchInput.java index 6e36b1ba0..59762ea43 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/SwitchInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/SwitchInput.java @@ -57,6 +57,7 @@ public boolean isClosed() { return closed; } + @Override public SwitchInputCopyBuilder copy() { return new SwitchInputCopyBuilder(this); } @@ -126,7 +127,7 @@ public SwitchInputCopyBuilder closed(boolean closed) { } @Override - protected SwitchInputCopyBuilder childInstance() { + protected SwitchInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer2WInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer2WInput.java index 99b0bc9ac..435f49a3a 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer2WInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer2WInput.java @@ -77,6 +77,7 @@ public Transformer2WInput( this.type = type; } + @Override public Transformer2WInputCopyBuilder copy() { return new Transformer2WInputCopyBuilder(this); } @@ -160,7 +161,7 @@ public Transformer2WInputCopyBuilder type(Transformer2WTypeInput type) { } @Override - protected Transformer2WInputCopyBuilder childInstance() { + protected Transformer2WInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer3WInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer3WInput.java index 54bafaa90..3e53dda9d 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer3WInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/Transformer3WInput.java @@ -232,6 +232,7 @@ public NodeInput getNodeInternal() { return nodeInternal; } + @Override public Transformer3WInputCopyBuilder copy() { return new Transformer3WInputCopyBuilder(this); } @@ -335,7 +336,7 @@ public Transformer3WInputCopyBuilder internalSlack(boolean internalNodeIsSlack) } @Override - protected Transformer3WInputCopyBuilder childInstance() { + protected Transformer3WInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/connector/TransformerInput.java b/src/main/java/edu/ie3/datamodel/models/input/connector/TransformerInput.java index cf0b42127..903bcf94d 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/connector/TransformerInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/connector/TransformerInput.java @@ -81,7 +81,7 @@ public int getTapPos() { } @Override - public abstract TransformerInputCopyBuilder copy(); + public abstract TransformerInputCopyBuilder> copy(); @Override public boolean equals(Object o) { @@ -127,8 +127,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class TransformerInputCopyBuilder> - extends ConnectorInputCopyBuilder { + public abstract static class TransformerInputCopyBuilder> + extends ConnectorInputCopyBuilder { private int tapPos; private boolean autoTap; @@ -139,14 +139,14 @@ protected TransformerInputCopyBuilder(TransformerInput entity) { this.autoTap = entity.isAutoTap(); } - public T tapPos(int tapPos) { + public B tapPos(int tapPos) { this.tapPos = tapPos; - return childInstance(); + return thisInstance(); } - public T autoTap(boolean autoTap) { + public B autoTap(boolean autoTap) { this.autoTap = autoTap; - return childInstance(); + return thisInstance(); } protected int getTapPos() { @@ -161,6 +161,6 @@ protected boolean isAutoTap() { public abstract TransformerInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/GraphicElements.java b/src/main/java/edu/ie3/datamodel/models/input/container/GraphicElements.java index edbc69666..e18430cab 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/GraphicElements.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/GraphicElements.java @@ -103,7 +103,7 @@ public int hashCode() { * @since 14.02.23 */ public static class GraphicElementsCopyBuilder - extends InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set nodeGraphics; private Set lineGraphics; @@ -113,7 +113,6 @@ public static class GraphicElementsCopyBuilder * @param graphicElements instance of {@link GraphicElements} */ protected GraphicElementsCopyBuilder(GraphicElements graphicElements) { - super(); this.nodeGraphics = graphicElements.getNodeGraphics(); this.lineGraphics = graphicElements.getLineGraphics(); } @@ -122,31 +121,26 @@ protected GraphicElementsCopyBuilder(GraphicElements graphicElements) { * Method to alter the {@link NodeGraphicInput}. * * @param nodeGraphics set of altered {@link NodeGraphicInput}'s - * @return child instance of {@link GraphicElementsCopyBuilder} + * @return this instance of {@link GraphicElementsCopyBuilder} */ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphics) { this.nodeGraphics = nodeGraphics; - return childInstance(); + return this; } /** * Method to alter the {@link LineGraphicInput}. * * @param lineGraphics set of altered {@link LineGraphicInput}'s - * @return child instance of {@link GraphicElementsCopyBuilder} + * @return this instance of {@link GraphicElementsCopyBuilder} */ public GraphicElementsCopyBuilder lineGraphics(Set lineGraphics) { this.lineGraphics = lineGraphics; - return childInstance(); - } - - @Override - protected GraphicElementsCopyBuilder childInstance() { return this; } @Override - GraphicElements build() { + public GraphicElements build() { return new GraphicElements(nodeGraphics, lineGraphics); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/GridContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/GridContainer.java index b4b296671..3c076cfff 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/GridContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/GridContainer.java @@ -86,8 +86,8 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - protected abstract static class GridContainerCopyBuilder> - extends InputContainerCopyBuilder { + protected abstract static class GridContainerCopyBuilder> + implements InputContainerCopyBuilder { private String gridName; private RawGridElements rawGrid; private SystemParticipants systemParticipants; @@ -99,7 +99,6 @@ protected abstract static class GridContainerCopyBuilder extends Serializable { List allEntitiesAsList(); /** Returns an input container copy builder */ - InputContainerCopyBuilder> copy(); + InputContainerCopyBuilder copy(); /** * Abstract class for all builder that build child containers of interface {@link @@ -25,15 +26,9 @@ public interface InputContainer extends Serializable { * @version 3.1 * @since 14.02.23 */ - abstract class InputContainerCopyBuilder> { - - /** Constructor for {@link InputContainerCopyBuilder}. */ - protected InputContainerCopyBuilder() {} - - /** Returns a child instance of {@link InputContainerCopyBuilder} */ - protected abstract InputContainerCopyBuilder childInstance(); + interface InputContainerCopyBuilder { /** Returns the altered {@link InputContainer} */ - abstract InputContainer build(); + InputContainer build() throws ValidationException; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/JointGridContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/JointGridContainer.java index 6cdac479e..5a15f0bfb 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/JointGridContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/JointGridContainer.java @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.graph.SubGridTopologyGraph; import edu.ie3.datamodel.utils.ContainerUtils; import java.util.Objects; @@ -22,7 +23,8 @@ public JointGridContainer( String gridName, RawGridElements rawGrid, SystemParticipants systemParticipants, - GraphicElements graphics) { + GraphicElements graphics) + throws InvalidGridException { super(gridName, rawGrid, systemParticipants, graphics); /* Build sub grid dependency */ @@ -105,12 +107,12 @@ protected JointGridContainerCopyBuilder(JointGridContainer jointGridContainer) { } @Override - protected JointGridContainerCopyBuilder childInstance() { + protected JointGridContainerCopyBuilder thisInstance() { return this; } @Override - JointGridContainer build() { + public JointGridContainer build() { return new JointGridContainer( getGridName(), getRawGrid(), diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/RawGridElements.java b/src/main/java/edu/ie3/datamodel/models/input/container/RawGridElements.java index 879c1810e..498ef1850 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/RawGridElements.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/RawGridElements.java @@ -187,8 +187,7 @@ public int hashCode() { * @version 3.1 * @since 14.02.23 */ - public static class RawGridElementsCopyBuilder - extends InputContainerCopyBuilder { + public static class RawGridElementsCopyBuilder implements InputContainerCopyBuilder { private Set nodes; private Set lines; private Set transformer2Ws; @@ -202,7 +201,6 @@ public static class RawGridElementsCopyBuilder * @param rawGridElements instance of {@link RawGridElementsCopyBuilder} */ protected RawGridElementsCopyBuilder(RawGridElements rawGridElements) { - super(); this.nodes = rawGridElements.getNodes(); this.lines = rawGridElements.getLines(); this.transformer2Ws = rawGridElements.getTransformer2Ws(); @@ -215,75 +213,70 @@ protected RawGridElementsCopyBuilder(RawGridElements rawGridElements) { * Method to alter {@link NodeInput} * * @param nodes set of altered nodes - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder nodes(Set nodes) { this.nodes = nodes; - return childInstance(); + return this; } /** * Method to alter {@link LineInput} * * @param lines set of altered lines - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder lines(Set lines) { this.lines = lines; - return childInstance(); + return this; } /** * Method to alter {@link Transformer2WInput} * * @param transformer2Ws set of altered two winding transformers - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder transformers2Ws(Set transformer2Ws) { this.transformer2Ws = transformer2Ws; - return childInstance(); + return this; } /** * Method to alter {@link Transformer3WInput} * * @param transformer3Ws set of altered three winding trnasformers - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder transformer3Ws(Set transformer3Ws) { this.transformer3Ws = transformer3Ws; - return childInstance(); + return this; } /** * Method to alter {@link SwitchInput} * * @param switches set of altered switches - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder switches(Set switches) { this.switches = switches; - return childInstance(); + return this; } /** * Method to alter {@link MeasurementUnitInput} * * @param measurementUnits set of altered measurement units - * @return child instance of {@link RawGridElementsCopyBuilder} + * @return this instance of {@link RawGridElementsCopyBuilder} */ public RawGridElementsCopyBuilder measurementUnits(Set measurementUnits) { this.measurementUnits = measurementUnits; - return childInstance(); - } - - @Override - protected RawGridElementsCopyBuilder childInstance() { return this; } @Override - RawGridElements build() { + public RawGridElements build() { return new RawGridElements( nodes, lines, transformer2Ws, transformer3Ws, switches, measurementUnits); } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/SubGridContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/SubGridContainer.java index 9058ba57d..2c05b187f 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/SubGridContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/SubGridContainer.java @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.models.voltagelevels.VoltageLevel; import edu.ie3.datamodel.utils.ContainerUtils; import java.util.Objects; @@ -23,7 +24,8 @@ public SubGridContainer( int subnet, RawGridElements rawGrid, SystemParticipants systemParticipants, - GraphicElements graphics) { + GraphicElements graphics) + throws InvalidGridException { super(gridName, rawGrid, systemParticipants, graphics); this.subnet = subnet; this.predominantVoltageLevel = ContainerUtils.determinePredominantVoltLvl(rawGrid, subnet); @@ -95,20 +97,20 @@ protected SubGridContainerCopyBuilder(SubGridContainer subGridContainer) { * Method to alter the subnet number. * * @param subnet altered subnet number. - * @return child instance of {@link SubGridContainerCopyBuilder} + * @return this instance of {@link SubGridContainerCopyBuilder} */ public SubGridContainerCopyBuilder subnet(int subnet) { this.subnet = subnet; - return childInstance(); + return thisInstance(); } @Override - protected SubGridContainerCopyBuilder childInstance() { + protected SubGridContainerCopyBuilder thisInstance() { return this; } @Override - SubGridContainer build() { + public SubGridContainer build() throws InvalidGridException { return new SubGridContainer( getGridName(), subnet, getRawGrid(), getSystemParticipants(), getGraphics()); } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/SystemParticipants.java b/src/main/java/edu/ie3/datamodel/models/input/container/SystemParticipants.java index 5ea6ecf30..ae90f50c4 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/SystemParticipants.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/SystemParticipants.java @@ -284,7 +284,7 @@ public int hashCode() { * @since 14.02.23 */ public static class SystemParticipantsCopyBuilder - extends InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set bmPlants; private Set chpPlants; private Set evCS; @@ -303,7 +303,6 @@ public static class SystemParticipantsCopyBuilder * @param systemParticipants instance of {@link SystemParticipants} */ protected SystemParticipantsCopyBuilder(SystemParticipants systemParticipants) { - super(); this.bmPlants = systemParticipants.bmPlants; this.chpPlants = systemParticipants.chpPlants; this.evCS = systemParticipants.evCS; @@ -321,121 +320,121 @@ protected SystemParticipantsCopyBuilder(SystemParticipants systemParticipants) { * Method to alter {@link BmInput} * * @param bmPlants set of altered biomass plants - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { this.bmPlants = bmPlants; - return childInstance(); + return this; } /** * Method to alter {@link ChpInput} * * @param chpPlants set of altered combined heat and power plants - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { this.chpPlants = chpPlants; - return childInstance(); + return this; } /** * Method to alter {@link EvcsInput} * * @param evCS set of altered biomass electric vehicle charging stations - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder evCS(Set evCS) { this.evCS = evCS; - return childInstance(); + return this; } /** * Method to alter {@link EvInput} * * @param evs set of altered electric vehicles - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder evs(Set evs) { this.evs = evs; - return childInstance(); + return this; } /** * Method to alter {@link FixedFeedInInput} * * @param fixedFeedIns set of altered fixed feed in facilities - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeedIns) { this.fixedFeedIns = fixedFeedIns; - return childInstance(); + return this; } /** * Method to alter {@link HpInput} * * @param heatPumps set of altered heat pumps - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { this.heatPumps = heatPumps; - return childInstance(); + return this; } /** * Method to alter {@link LoadInput} * * @param loads set of altered loads - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder loads(Set loads) { this.loads = loads; - return childInstance(); + return this; } /** * Method to alter {@link PvInput} * * @param pvPlants set of altered photovoltaic power plants - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { this.pvPlants = pvPlants; - return childInstance(); + return this; } /** * Method to alter {@link StorageInput} * * @param storages set of altered electric energy storages - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); + return this; } /** * Method to alter {@link WecInput} * * @param wecPlants set of altered wind energy converters - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { this.wecPlants = wecPlants; - return childInstance(); + return this; } /** * Method to alter {@link EmInput} * * @param emSystems set of altered energy management systems - * @return child instance of {@link SystemParticipantsCopyBuilder} + * @return this instance of {@link SystemParticipantsCopyBuilder} */ public SystemParticipantsCopyBuilder emSystems(Set emSystems) { this.emSystems = emSystems; - return childInstance(); + return this; } @Override @@ -453,10 +452,5 @@ public SystemParticipants build() { wecPlants, emSystems); } - - @Override - protected SystemParticipantsCopyBuilder childInstance() { - return this; - } } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/ThermalGrid.java b/src/main/java/edu/ie3/datamodel/models/input/container/ThermalGrid.java index 1a4852dcc..3b6d277cc 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/ThermalGrid.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/ThermalGrid.java @@ -59,8 +59,7 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalGridCopyBuilder - extends InputContainerCopyBuilder { + public static class ThermalGridCopyBuilder implements InputContainerCopyBuilder { private ThermalBusInput bus; private Set houses; private Set storages; @@ -71,7 +70,6 @@ public static class ThermalGridCopyBuilder * @param thermalGrid instance of {@link ThermalGrid} */ protected ThermalGridCopyBuilder(ThermalGrid thermalGrid) { - super(); this.bus = thermalGrid.bus(); this.houses = thermalGrid.houses(); this.storages = thermalGrid.storages(); @@ -81,42 +79,37 @@ protected ThermalGridCopyBuilder(ThermalGrid thermalGrid) { * Method to alter {@link ThermalBusInput} * * @param bus altered thermal bus - * @return child instance of {@link ThermalGridCopyBuilder} + * @return this instance of {@link ThermalGridCopyBuilder} */ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { this.bus = bus; - return childInstance(); + return this; } /** * Method to alter {@link ThermalHouseInput} * * @param houses altered thermal houses - * @return child instance of {@link ThermalGridCopyBuilder} + * @return this instance of {@link ThermalGridCopyBuilder} */ public ThermalGridCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** * Method to alter {@link ThermalStorageInput} * * @param storages altered thermal storages - * @return child instance of {@link ThermalGridCopyBuilder} + * @return this instance of {@link ThermalGridCopyBuilder} */ public ThermalGridCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalGridCopyBuilder childInstance() { return this; } @Override - ThermalGrid build() { + public ThermalGrid build() { return new ThermalGrid(bus, houses, storages); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/ThermalUnits.java b/src/main/java/edu/ie3/datamodel/models/input/container/ThermalUnits.java index 2876b40da..0a2b84a03 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/ThermalUnits.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/ThermalUnits.java @@ -50,7 +50,7 @@ public String toString() { * @since 14.02.23 */ public static class ThermalUnitsCopyBuilder - extends InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set houses; private Set storages; @@ -60,7 +60,6 @@ public static class ThermalUnitsCopyBuilder * @param thermalUnits instance of {@link ThermalUnits} */ protected ThermalUnitsCopyBuilder(ThermalUnits thermalUnits) { - super(); this.houses = thermalUnits.houses(); this.storages = thermalUnits.storages(); } @@ -69,31 +68,26 @@ protected ThermalUnitsCopyBuilder(ThermalUnits thermalUnits) { * Method to alter {@link ThermalHouseInput} * * @param houses altered thermal houses - * @return child instance of {@link ThermalUnitsCopyBuilder} + * @return this instance of {@link ThermalUnitsCopyBuilder} */ public ThermalUnitsCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** * Method to alter {@link ThermalStorageInput} * * @param storages altered thermal storages - * @return child instance of {@link ThermalUnitsCopyBuilder} + * @return this instance of {@link ThermalUnitsCopyBuilder} */ public ThermalUnitsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalUnitsCopyBuilder childInstance() { return this; } @Override - ThermalUnits build() { + public ThermalUnits build() { return new ThermalUnits(houses, storages); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/graphics/GraphicInput.java b/src/main/java/edu/ie3/datamodel/models/input/graphics/GraphicInput.java index a7648c522..cf865732d 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/graphics/GraphicInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/graphics/GraphicInput.java @@ -65,14 +65,16 @@ public String toString() { + '}'; } + public abstract GraphicInputCopyBuilder> copy(); + /** * Abstract class for all builder that build child entities of abstract class {@link GraphicInput} * * @version 0.1 * @since 05.06.20 */ - protected abstract static class GraphicInputCopyBuilder> - extends UniqueEntityCopyBuilder { + public abstract static class GraphicInputCopyBuilder> + extends UniqueEntityCopyBuilder { private String graphicLayer; private LineString path; @@ -83,14 +85,14 @@ protected GraphicInputCopyBuilder(GraphicInput entity) { this.path = entity.getPath(); } - public T graphicLayer(String graphicLayer) { + public B graphicLayer(String graphicLayer) { this.graphicLayer = graphicLayer; - return childInstance(); + return thisInstance(); } - public T path(LineString path) { + public B path(LineString path) { this.path = path; - return childInstance(); + return thisInstance(); } protected String getGraphicLayer() { @@ -105,6 +107,6 @@ protected LineString getPath() { public abstract GraphicInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/graphics/LineGraphicInput.java b/src/main/java/edu/ie3/datamodel/models/input/graphics/LineGraphicInput.java index a1b289c64..65520abc9 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/graphics/LineGraphicInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/graphics/LineGraphicInput.java @@ -76,7 +76,7 @@ private LineGraphicInputCopyBuilder(LineGraphicInput entity) { } @Override - protected LineGraphicInputCopyBuilder childInstance() { + protected LineGraphicInputCopyBuilder thisInstance() { return this; } diff --git a/src/main/java/edu/ie3/datamodel/models/input/graphics/NodeGraphicInput.java b/src/main/java/edu/ie3/datamodel/models/input/graphics/NodeGraphicInput.java index 85f8594ca..9ad76c8f7 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/graphics/NodeGraphicInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/graphics/NodeGraphicInput.java @@ -105,7 +105,7 @@ public NodeGraphicInputCopyBuilder node(NodeInput node) { } @Override - protected NodeGraphicInputCopyBuilder childInstance() { + protected NodeGraphicInputCopyBuilder thisInstance() { return this; } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/BmInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/BmInput.java index 3ef758a59..ec6003abe 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/BmInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/BmInput.java @@ -215,7 +215,7 @@ public BmInput build() { } @Override - protected BmInputCopyBuilder childInstance() { + protected BmInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/ChpInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/ChpInput.java index b1bf2ee53..422817ecb 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/ChpInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/ChpInput.java @@ -216,7 +216,7 @@ public ChpInputCopyBuilder marketReaction(boolean marketReaction) { } @Override - protected ChpInputCopyBuilder childInstance() { + protected ChpInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/EmInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/EmInput.java index 42329dc07..eeac609aa 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/EmInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/EmInput.java @@ -206,7 +206,7 @@ public EmInput build() { } @Override - protected EmInputCopyBuilder childInstance() { + protected EmInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/EvInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/EvInput.java index a483bb756..5f2edeae9 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/EvInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/EvInput.java @@ -139,7 +139,7 @@ public EvInputCopyBuilder type(EvTypeInput type) { } @Override - protected EvInputCopyBuilder childInstance() { + protected EvInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/EvcsInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/EvcsInput.java index e08829f16..c8f02ed38 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/EvcsInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/EvcsInput.java @@ -284,7 +284,7 @@ public EvcsInput build() { } @Override - protected EvcsInputCopyBuilder childInstance() { + protected EvcsInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/FixedFeedInInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/FixedFeedInInput.java index f3d8d76d9..16ba19dc7 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/FixedFeedInInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/FixedFeedInInput.java @@ -162,7 +162,7 @@ public FixedFeedInInputCopyBuilder cosPhiRated(double cosPhiRated) { } @Override - protected FixedFeedInInputCopyBuilder childInstance() { + protected FixedFeedInInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/HpInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/HpInput.java index edb52b673..ef5bf7fea 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/HpInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/HpInput.java @@ -164,7 +164,7 @@ public HpInputCopyBuilder thermalBus(ThermalBusInput thermalBus) { } @Override - protected HpInputCopyBuilder childInstance() { + protected HpInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/LoadInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/LoadInput.java index 0b3218441..9f320d851 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/LoadInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/LoadInput.java @@ -322,7 +322,7 @@ public LoadInput build() { } @Override - protected LoadInputCopyBuilder childInstance() { + protected LoadInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/PvInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/PvInput.java index 382e449ac..49a68253f 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/PvInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/PvInput.java @@ -336,7 +336,7 @@ public PvInput build() { } @Override - protected PvInputCopyBuilder childInstance() { + protected PvInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/StorageInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/StorageInput.java index a019e7924..26726cb03 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/StorageInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/StorageInput.java @@ -139,7 +139,7 @@ public StorageInputCopyBuilder type(StorageTypeInput type) { } @Override - protected StorageInputCopyBuilder childInstance() { + protected StorageInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/SystemParticipantInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/SystemParticipantInput.java index e05167371..9fa4a00a6 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/SystemParticipantInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/SystemParticipantInput.java @@ -116,8 +116,8 @@ public String toString() { * @since 05.06.20 */ public abstract static class SystemParticipantInputCopyBuilder< - T extends SystemParticipantInputCopyBuilder> - extends AssetInputCopyBuilder { + B extends SystemParticipantInputCopyBuilder> + extends AssetInputCopyBuilder { private NodeInput node; private ReactivePowerCharacteristic qCharacteristics; @@ -128,14 +128,14 @@ protected SystemParticipantInputCopyBuilder(SystemParticipantInput entity) { this.qCharacteristics = entity.getqCharacteristics(); } - public T node(NodeInput node) { + public B node(NodeInput node) { this.node = node; - return childInstance(); + return thisInstance(); } - public T qCharacteristics(ReactivePowerCharacteristic qCharacteristics) { + public B qCharacteristics(ReactivePowerCharacteristic qCharacteristics) { this.qCharacteristics = qCharacteristics; - return childInstance(); + return thisInstance(); } protected NodeInput getNode() { @@ -150,6 +150,6 @@ protected ReactivePowerCharacteristic getqCharacteristics() { public abstract SystemParticipantInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/system/WecInput.java b/src/main/java/edu/ie3/datamodel/models/input/system/WecInput.java index d645824ff..d5c5122d5 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/system/WecInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/system/WecInput.java @@ -163,7 +163,7 @@ public WecInputCopyBuilder marketReaction(boolean marketReaction) { } @Override - protected WecInputCopyBuilder childInstance() { + protected WecInputCopyBuilder thisInstance() { return this; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/thermal/CylindricalStorageInput.java b/src/main/java/edu/ie3/datamodel/models/input/thermal/CylindricalStorageInput.java index 478b8ddf8..672ec754c 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/thermal/CylindricalStorageInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/thermal/CylindricalStorageInput.java @@ -222,7 +222,7 @@ public CylindricalStorageInputCopyBuilder c(ComparableQuantity copy(); } diff --git a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalUnitInput.java b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalUnitInput.java index 1c1c92f6b..ebb911198 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalUnitInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalUnitInput.java @@ -82,8 +82,8 @@ public String toString() { * ThermalUnitInput} */ protected abstract static class ThermalUnitInputCopyBuilder< - T extends ThermalUnitInput.ThermalUnitInputCopyBuilder> - extends AssetInputCopyBuilder { + B extends ThermalUnitInput.ThermalUnitInputCopyBuilder> + extends AssetInputCopyBuilder { private ThermalBusInput thermalBus; @@ -92,9 +92,9 @@ protected ThermalUnitInputCopyBuilder(ThermalUnitInput entity) { this.thermalBus = entity.getThermalBus(); } - public T thermalBus(ThermalBusInput thermalBus) { + public B thermalBus(ThermalBusInput thermalBus) { this.thermalBus = thermalBus; - return childInstance(); + return thisInstance(); } protected ThermalBusInput getThermalBus() { @@ -105,6 +105,6 @@ protected ThermalBusInput getThermalBus() { public abstract ThermalUnitInput build(); @Override - protected abstract T childInstance(); + protected abstract B thisInstance(); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/ContainerNodeUpdateUtil.java b/src/main/java/edu/ie3/datamodel/utils/ContainerNodeUpdateUtil.java index 0baa490de..4778fabea 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ContainerNodeUpdateUtil.java +++ b/src/main/java/edu/ie3/datamodel/utils/ContainerNodeUpdateUtil.java @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.utils; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.models.input.MeasurementUnitInput; import edu.ie3.datamodel.models.input.NodeInput; import edu.ie3.datamodel.models.input.connector.*; @@ -40,7 +41,7 @@ private ContainerNodeUpdateUtil() { * @return a copy of the provided grid with updated nodes as provided */ public static GridContainer updateGridWithNodes( - GridContainer grid, Map oldToNewNodes) { + GridContainer grid, Map oldToNewNodes) throws InvalidGridException { if (grid instanceof JointGridContainer jointGridContainer) { return updateGridWithNodes(jointGridContainer, oldToNewNodes); } else { @@ -66,7 +67,8 @@ public static GridContainer updateGridWithNodes( * @return a copy of the provided grid with updated nodes as provided */ public static JointGridContainer updateGridWithNodes( - JointGridContainer grid, Map oldToNewNodes) { + JointGridContainer grid, Map oldToNewNodes) + throws InvalidGridException { UpdatedEntities updatedEntities = updateEntities( grid.getRawGrid(), grid.getSystemParticipants(), grid.getGraphics(), oldToNewNodes); @@ -99,7 +101,7 @@ public static JointGridContainer updateGridWithNodes( * @return a copy of the provided grid with updated nodes as provided */ public static SubGridContainer updateGridWithNodes( - SubGridContainer grid, Map oldToNewNodes) { + SubGridContainer grid, Map oldToNewNodes) throws InvalidGridException { UpdatedEntities updatedEntities = updateEntities( diff --git a/src/main/java/edu/ie3/datamodel/utils/ContainerUtils.java b/src/main/java/edu/ie3/datamodel/utils/ContainerUtils.java index 6470290f1..bf1eb0615 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ContainerUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/ContainerUtils.java @@ -426,7 +426,8 @@ public static GraphicElements filterForSubnet(GraphicElements input, int subnet) * @return The predominant voltage level in this grid * @throws InvalidGridException If not a single, predominant voltage level can be determined */ - public static VoltageLevel determinePredominantVoltLvl(RawGridElements rawGrid, int subnet) { + public static VoltageLevel determinePredominantVoltLvl(RawGridElements rawGrid, int subnet) + throws InvalidGridException { /* Exclude all nodes, that are at the high voltage side of the transformer */ Set gridNodes = new HashSet<>(rawGrid.getNodes()); gridNodes.removeAll( @@ -502,7 +503,8 @@ public static SubGridTopologyGraph buildSubGridTopologyGraph( String gridName, RawGridElements rawGrid, SystemParticipants systemParticipants, - GraphicElements graphics) { + GraphicElements graphics) + throws InvalidGridException { /* Collect the different sub nets. Through the validation of lines, it is ensured, that no galvanically connected * grid has more than one subnet number assigned */ SortedSet subnetNumbers = determineSubnetNumbers(rawGrid.getNodes()); @@ -540,7 +542,8 @@ private static HashMap buildSubGridContainers( SortedSet subnetNumbers, RawGridElements rawGrid, SystemParticipants systemParticipants, - GraphicElements graphics) { + GraphicElements graphics) + throws InvalidGridException { HashMap subGrids = new HashMap<>(subnetNumbers.size()); for (int subnetNumber : subnetNumbers) { RawGridElements rawGridElements = ContainerUtils.filterForSubnet(rawGrid, subnetNumber); @@ -564,7 +567,8 @@ private static HashMap buildSubGridContainers( * @return An immutable graph of the sub grid topology */ private static SubGridTopologyGraph buildSubGridTopologyGraph( - Map subGrids, RawGridElements rawGridElements) { + Map subGrids, RawGridElements rawGridElements) + throws InvalidGridException { /* Building a mutable graph, that is boxed as immutable later */ DirectedMultigraph mutableGraph = new DirectedMultigraph<>(SubGridGate.class); @@ -777,7 +781,7 @@ private static LinkedList traverseAlongSwitchChain( * @return A joint model */ public static JointGridContainer combineToJointGrid( - Collection subGridContainers) { + Collection subGridContainers) throws InvalidGridException { if (subGridContainers.stream().map(SubGridContainer::getGridName).distinct().count() > 1) throw new InvalidGridException( "You are trying to combine sub grids of different grid models"); @@ -852,7 +856,8 @@ public static JointGridContainer combineToJointGrid( * @param subGridContainer the subgrid container to be altered * @return a copy of the given {@link SubGridContainer} with transformer nodes marked as slack */ - public static SubGridContainer withTrafoNodeAsSlack(final SubGridContainer subGridContainer) { + public static SubGridContainer withTrafoNodeAsSlack(final SubGridContainer subGridContainer) + throws InvalidGridException { // transformer 3w Map oldToNewTrafo3WANodes = new HashMap<>(); diff --git a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java index 7aac61132..018580d20 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java @@ -13,7 +13,7 @@ private ExceptionUtils() { } /** - * Creates a string containing multiple exception messsages. + * Creates a string containing multiple exception messages. * * @param exceptions list of exceptions * @return str containing the messages @@ -21,7 +21,7 @@ private ExceptionUtils() { public static String getMessages(List exceptions) { return exceptions.stream() .map(Throwable::getMessage) - .reduce("", (a, b) -> a + ", " + b) - .replaceFirst(", ", ""); + .reduce("", (a, b) -> a + "\n " + b) + .replaceFirst("\n ", ""); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index 40c4f69ce..0d1c571d5 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -15,32 +15,7 @@ import java.util.stream.Stream; public abstract class Try { - private final T data; - private final E exception; - private final boolean isEmpty; - - // constructor - /** - * Constructor for {@link Try} used when a {@link Success} is created. - * - * @param data that is stored - */ - protected Try(T data) { - this.data = data; - this.exception = null; - this.isEmpty = data == null; - } - - /** - * Constructor for {@link Try} used when a {@link Failure} is created. - * - * @param ex exception that was thrown - */ - private Try(E ex) { - this.data = null; - this.exception = ex; - isEmpty = true; - } + // static utility methods /** * Method to create a {@link Try} object easily. @@ -75,7 +50,7 @@ public static Try of(TrySupplier supplier, */ @SuppressWarnings("unchecked") public static Try ofVoid( - TrySupplier supplier, Class clazz) { + VoidSupplier supplier, Class clazz) { try { supplier.get(); return Success.empty(); @@ -90,70 +65,119 @@ public static Try ofVoid( } /** - * Returns true if this object is a {@link Success} or false if this object is a {@link Failure}. + * Method to create a {@link Try} object easily. + * + * @param failure a {@link Failure} is returned. + * @param exception exception that should be wrapped by a {@link Failure} + * @return a {@link Try} + * @param type of exception */ - public abstract boolean isSuccess(); + public static Try ofVoid( + boolean failure, ExceptionSupplier exception) { + if (failure) { + return Failure.ofVoid(exception.get()); + } else { + return Success.empty(); + } + } /** - * Returns true if this object is a {@link Failure} or false if this object is a {@link Success}. + * Utility method to check a list of {@link VoidSupplier}'s. + * + * @param supplier list of {@link VoidSupplier} + * @param clazz class of the exception + * @return a list of {@link Try} + * @param type of the exception */ - public abstract boolean isFailure(); - - /** Returns true if this object is either a {@link Success} or a {@link Failure}. */ - public boolean isEmpty() { - return isEmpty; + @SafeVarargs + public static List> ofVoid( + Class clazz, VoidSupplier... supplier) { + return Arrays.stream(supplier).map(sup -> Try.ofVoid(sup, clazz)).toList(); } /** - * Method for getting the data. If this object is a {@link Failure} the exception is thrown. + * Method to retrieve the exceptions from all {@link Failure} objects. * - * @return data id this object is a {@link Success} - * @throws E if this object is a {@link Failure} + * @param tries collection of {@link Try} objects + * @return a list of {@link Exception}'s */ - public T getOrThrow() throws E { - if (data != null) { - return data; - } else { - assert exception != null; - throw exception; - } + public static List getExceptions( + Collection> tries) { + return tries.stream().filter(Try::isFailure).map(t -> ((Failure) t).get()).toList(); } /** - * This method will return the stored data if this object is a {@link Success} or the given value. + * Method to scan a collection of {@link Try} objects for {@link Failure}'s. * - * @param value that should be returned if this object is a {@link Failure} - * @return either the stored data or the given value + * @param c collection of {@link Try} objects + * @param typeOfData type of data + * @return a {@link Success} if no {@link Failure}'s are found in the collection + * @param type of data */ - public T getOrElse(T value) { - return data != null ? data : value; + public static Try, FailureException> scanCollection( + Collection> c, Class typeOfData) { + return scanStream(c.stream(), typeOfData.getSimpleName()) + .transformS(stream -> stream.collect(Collectors.toSet())); } - /** Returns an option for data. */ - public Optional getData() { - return data != null ? Optional.of(data) : Optional.empty(); - } + /** + * Method to scan a stream of {@link Try} objects for {@link Failure}'s. + * + * @param stream of {@link Try} objects + * @return a {@link Success} if no {@link Failure}'s are found in the stream + * @param type of data + */ + public static Try, FailureException> scanStream( + Stream> stream, String typeOfData) { + Map>> map = stream.collect(partitioningBy(Try::isSuccess)); - /** Returns an option for an exception. */ - public Optional getException() { - return exception != null ? Optional.of(exception) : Optional.empty(); + List> successes = map.get(true); + List> failures = map.get(false); + + // Both lists should exist in map per definition of partitioningBy + assert successes != null && failures != null; + + if (!failures.isEmpty()) { + E first = ((Failure) failures.get(0)).exception; + + return new Failure<>( + new FailureException( + failures.size() + + " exception(s) occurred within \"" + + typeOfData + + "\" data, one is: " + + first, + first.getCause())); + } else { + return new Success<>(successes.stream().map(t -> ((Success) t).data)); + } } + // methods of try object + /** - * Returns the data. WARNING: This method is for internal usage only and should therefore not be - * called for other purposes. + * Returns true if this object is a {@link Success} or false if this object is a {@link Failure}. */ - T data() { - return data; - } + public abstract boolean isSuccess(); /** - * Returns the exception. WARNING: This method is for internal usage only and should therefore not - * be called for other purposes. + * Returns true if this object is a {@link Failure} or false if this object is a {@link Success}. */ - E exception() { - return exception; - } + public abstract boolean isFailure(); + + /** + * Method for getting the data. If this object is a {@link Failure} the exception is thrown. + * + * @return data id this object is a {@link Success} + * @throws E if this object is a {@link Failure} + */ + public abstract T getOrThrow() throws E; + + /** Returns an option for data. */ + public abstract Optional getData(); + + /** Returns an option for an exception. */ + public abstract Optional getException(); // functional methods @@ -175,11 +199,7 @@ public Try map(Function mapper) { * @return a new {@link Try} object * @param type of the data */ - @SuppressWarnings("unchecked") - public Try flatMap(Function> mapper) { - Try, E> t = transformS(mapper); - return t instanceof Success, ?> success ? success.data() : (Try) t; - } + public abstract Try flatMap(Function> mapper); /** * Method to transform a {@link Try} object. This method should be used, if processing the @@ -189,9 +209,7 @@ public Try flatMap(Function> mapper) { * @return a new {@link Try} object * @param type of data */ - public Try transformS(Function successFunc) { - return isSuccess() ? new Success<>(successFunc.apply(data)) : Failure.of(this.exception); - } + public abstract Try transformS(Function successFunc); /** * Method to transform a {@link Try} object. This method should be used, if only exception should @@ -201,9 +219,8 @@ public Try transformS(Function successFunc) { * @return a new {@link Try} object * @param type of new exception */ - public Try transformF(Function failureFunc) { - return isFailure() ? Failure.of(failureFunc.apply(exception)) : new Success<>(data); - } + public abstract Try transformF( + Function failureFunc); /** * Method to transform a {@link Try} object. This method should be used, if processing the @@ -214,92 +231,76 @@ public Try transformF(Function type of data */ - public Try transform( - Function successFunc, Function failureFunc) { - if (isSuccess()) { - return new Success<>(successFunc.apply(data)); - } else { - return new Failure<>(failureFunc.apply(exception)); + public abstract Try transform( + Function successFunc, Function failureFunc); + + /** Implementation of {@link Try} class. This class is used to present a successful try. */ + public static final class Success extends Try { + private final T data; + + private static final Success emptySuccess = new Success<>(null); + + public Success(T data) { + this.data = data; } - } - /** - * Method to scan a collection of {@link Try} objects for {@link Failure}'s. - * - * @param c collection of {@link Try} objects - * @param typeOfData type of data - * @return a {@link Success} if no {@link Failure}'s are found in the collection - * @param type of data - */ - public static Try, FailureException> scanCollection( - Collection> c, Class typeOfData) { - return scanStream(c.stream(), typeOfData.getSimpleName()) - .transformS(stream -> stream.collect(Collectors.toSet())); - } + @Override + public boolean isSuccess() { + return true; + } - /** - * Method to scan a stream of {@link Try} objects for {@link Failure}'s. - * - * @param stream of {@link Try} objects - * @return a {@link Success} if no {@link Failure}'s are found in the stream - * @param type of data - */ - public static Try, FailureException> scanStream( - Stream> stream, String typeOfData) { - Map>> map = stream.collect(partitioningBy(Try::isSuccess)); + @Override + public boolean isFailure() { + return false; + } - List> successes = map.get(true); - List> failures = map.get(false); + /** Returns true if this object is an empty {@link Success}. */ + public boolean isEmpty() { + return data == null; + } - // Both lists should exist in map per definition of partitioningBy - assert successes != null && failures != null; + @Override + public T getOrThrow() throws E { + return get(); + } - if (!failures.isEmpty()) { - E first = failures.get(0).exception; + @Override + public Optional getData() { + return !isEmpty() ? Optional.of(data) : Optional.empty(); + } - return new Failure<>( - new FailureException( - failures.size() - + " exception(s) occurred within \"" - + typeOfData - + "\" data, one is: " - + first, - first.getCause())); - } else { - return new Success<>(successes.stream().map(t -> t.data)); + @Override + public Optional getException() { + return Optional.empty(); } - } - /** - * Method to retrieve the exceptions from all {@link Failure} objects. - * - * @param tries collection of {@link Try} objects - * @return a list of {@link Exception}'s - */ - public static List getExceptions( - Collection> tries) { - return tries.stream().filter(Try::isFailure).map(t -> ((Failure) t).get()).toList(); - } + @SuppressWarnings("unchecked") + @Override + public Try flatMap(Function> mapper) { + Try, E> t = transformS(mapper); + return t instanceof Success, ?> success ? success.get() : (Try) t; + } - /** Implementation of {@link Try} class. This class is used to present a successful try. */ - public static final class Success extends Try { - public Success(T data) { - super(data); + @Override + public Try transformS(Function successFunc) { + return new Success<>(successFunc.apply(data)); } @Override - public boolean isSuccess() { - return true; + public Try transformF( + Function failureFunc) { + return new Success<>(data); } @Override - public boolean isFailure() { - return false; + public Try transform( + Function successFunc, Function failureFunc) { + return new Success<>(successFunc.apply(data)); } /** Returns the stored data. */ public T get() { - return data(); + return data; } /** @@ -307,15 +308,18 @@ public T get() { * * @param type of exception */ + @SuppressWarnings("unchecked") public static Success empty() { - return new Success<>(null); + return (Success) emptySuccess; } } /** Implementation of {@link Try} class. This class is used to present a failed try. */ public static final class Failure extends Try { + private final E exception; + public Failure(E e) { - super(e); + this.exception = e; } @Override @@ -328,9 +332,47 @@ public boolean isFailure() { return true; } + @Override + public T getOrThrow() throws E { + throw exception; + } + + @Override + public Optional getData() { + return Optional.empty(); + } + + @Override + public Optional getException() { + return exception != null ? Optional.of(exception) : Optional.empty(); + } + + @SuppressWarnings("unchecked") + @Override + public Try flatMap(Function> mapper) { + return (Failure) this; + } + + @Override + public Try transformS(Function successFunc) { + return Failure.of(this.exception); + } + + @Override + public Try transformF( + Function failureFunc) { + return Failure.of(failureFunc.apply(exception)); + } + + @Override + public Try transform( + Function successFunc, Function failureFunc) { + return Failure.of(failureFunc.apply(exception)); + } + /** Returns the thrown exception. */ public E get() { - return exception(); + return exception; } /** @@ -355,18 +397,6 @@ public static Failure of(E exception) { public static Failure ofVoid(E exception) { return new Failure<>(exception); } - - /** - * Method to transform a {@link Failure} into another {@link Failure}. - * - * @param failure given failure - * @return the transformed failure - * @param type before transformation - * @param type after transformation - */ - public static Failure of(Failure failure) { - return new Failure<>(failure.exception()); - } } /** @@ -379,4 +409,24 @@ public static Failure of(Failure failure public interface TrySupplier { T get() throws E; } + + /** + * Supplier for void methods to {@link Try} class. + * + * @param type of exception that could be thrown + */ + @FunctionalInterface + public interface VoidSupplier { + void get() throws E; + } + + /** + * Supplier for exceptions. + * + * @param type of exception that could be thrown + */ + @FunctionalInterface + public interface ExceptionSupplier { + E get(); + } } diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java index bd20a6679..696f4ac9d 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -6,14 +6,26 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; +import edu.ie3.datamodel.exceptions.InvalidGridException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.NodeInput; import edu.ie3.datamodel.models.input.connector.*; import edu.ie3.datamodel.models.input.connector.type.LineTypeInput; import edu.ie3.datamodel.models.input.connector.type.Transformer2WTypeInput; import edu.ie3.datamodel.models.input.connector.type.Transformer3WTypeInput; +import edu.ie3.datamodel.models.input.container.SubGridContainer; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.*; import edu.ie3.util.geo.GeoUtils; import edu.ie3.util.quantities.QuantityUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; import javax.measure.Quantity; +import org.jgrapht.Graph; +import org.jgrapht.alg.connectivity.ConnectivityInspector; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleGraph; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -22,7 +34,7 @@ public class ConnectorValidationUtils extends ValidationUtils { // allowed deviation of coordinates in degree for line position check private static final double ALLOWED_COORDINATE_ERROR = 0.000001d; // allowed deviation of length in meters for line length - private static final double ALLOWED_LENGTH_ERROR = 1d; + private static final double ALLOWED_LENGTH_ERROR = 50d; // allowed deviation of voltage in kV for transformer checks private static final double ALLOWED_VOLTAGE_ERROR = 1d; @@ -38,21 +50,36 @@ private ConnectorValidationUtils() { * the checking task, based on the class of the given object. * * @param connector Connector to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing a {@link InvalidEntityException} or an empty + * Success */ - protected static void check(ConnectorInput connector) { - checkNonNull(connector, "a connector"); - connectsDifferentNodes(connector); + protected static List> check(ConnectorInput connector) { + Try isNull = checkNonNull(connector, "a connector"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + exceptions.add(connectsDifferentNodes(connector)); // Further checks for subclasses - if (LineInput.class.isAssignableFrom(connector.getClass())) checkLine((LineInput) connector); - else if (Transformer2WInput.class.isAssignableFrom(connector.getClass())) - checkTransformer2W((Transformer2WInput) connector); - else if (Transformer3WInput.class.isAssignableFrom(connector.getClass())) - checkTransformer3W((Transformer3WInput) connector); - else if (SwitchInput.class.isAssignableFrom(connector.getClass())) - checkSwitch((SwitchInput) connector); - else throw checkNotImplementedException(connector); + if (LineInput.class.isAssignableFrom(connector.getClass())) { + exceptions.addAll(checkLine((LineInput) connector)); + } else if (Transformer2WInput.class.isAssignableFrom(connector.getClass())) { + exceptions.addAll(checkTransformer2W((Transformer2WInput) connector)); + } else if (Transformer3WInput.class.isAssignableFrom(connector.getClass())) { + exceptions.addAll(checkTransformer3W((Transformer3WInput) connector)); + } else if (SwitchInput.class.isAssignableFrom(connector.getClass())) { + exceptions.add(checkSwitch((SwitchInput) connector)); + } else { + exceptions.add( + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", buildNotImplementedException(connector)))); + } + + return exceptions; } /** @@ -67,14 +94,25 @@ else if (SwitchInput.class.isAssignableFrom(connector.getClass())) * - its coordinates of start and end point equal coordinates of nodes * * @param line Line to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkLine(LineInput line) { - checkLineType(line.getType()); - connectsNodesInDifferentSubnets(line, false); - connectsNodesWithDifferentVoltageLevels(line, false); - detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line); + private static List> checkLine(LineInput line) { + List> exceptions = + new ArrayList<>(checkLineType(line.getType())); + + exceptions.addAll( + Try.ofVoid( + InvalidEntityException.class, + () -> connectsNodesInDifferentSubnets(line, false), + () -> connectsNodesWithDifferentVoltageLevels(line, false), + () -> detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line))); + + /* these two won't throw exceptions and will only log */ coordinatesOfLineEqualCoordinatesOfNodes(line); lineLengthMatchesDistancesBetweenPointsOfLineString(line); + + return exceptions; } /** @@ -88,15 +126,27 @@ private static void checkLine(LineInput line) { * - vRated is greater 0 (Rated voltage) * * @param lineType Line type to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void checkLineType(LineTypeInput lineType) { - checkNonNull(lineType, "a line type"); - detectNegativeQuantities(new Quantity[] {lineType.getB(), lineType.getG()}, lineType); - detectZeroOrNegativeQuantities( - new Quantity[] { - lineType.getvRated(), lineType.getiMax(), lineType.getX(), lineType.getR() - }, - lineType); + protected static List> checkLineType(LineTypeInput lineType) { + Try isNull = checkNonNull(lineType, "a line type"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + return Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {lineType.getB(), lineType.getG()}, lineType), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + lineType.getvRated(), lineType.getiMax(), lineType.getX(), lineType.getR() + }, + lineType)); } /** @@ -109,13 +159,23 @@ protected static void checkLineType(LineTypeInput lineType) { * - its rated voltages match the voltages at the nodes * * @param transformer2W Transformer2W to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkTransformer2W(Transformer2WInput transformer2W) { - checkTransformer2WType(transformer2W.getType()); - checkIfTapPositionIsWithinBounds(transformer2W); - connectsNodesWithDifferentVoltageLevels(transformer2W, true); - connectsNodesInDifferentSubnets(transformer2W, true); - ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W); + private static List> checkTransformer2W( + Transformer2WInput transformer2W) { + List> exceptions = + new ArrayList<>(checkTransformer2WType(transformer2W.getType())); + + exceptions.addAll( + Try.ofVoid( + InvalidEntityException.class, + () -> checkIfTapPositionIsWithinBounds(transformer2W), + () -> connectsNodesWithDifferentVoltageLevels(transformer2W, true), + () -> connectsNodesInDifferentSubnets(transformer2W, true), + () -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); + + return exceptions; } /** @@ -134,26 +194,41 @@ private static void checkTransformer2W(Transformer2WInput transformer2W) { * - minimum tap position is smaller than maximum tap position * * @param transformer2WType Transformer2W type to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void checkTransformer2WType(Transformer2WTypeInput transformer2WType) { - checkNonNull(transformer2WType, "a two winding transformer type"); - detectNegativeQuantities( - new Quantity[] { - transformer2WType.getgM(), transformer2WType.getdPhi(), transformer2WType.getrSc() - }, - transformer2WType); - detectZeroOrNegativeQuantities( - new Quantity[] { - transformer2WType.getsRated(), - transformer2WType.getvRatedA(), - transformer2WType.getvRatedB(), - transformer2WType.getxSc() - }, - transformer2WType); - detectPositiveQuantities(new Quantity[] {transformer2WType.getbM()}, transformer2WType); - checkVoltageMagnitudeChangePerTapPosition(transformer2WType); - checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType); - checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType); + protected static List> checkTransformer2WType( + Transformer2WTypeInput transformer2WType) { + Try isNull = + checkNonNull(transformer2WType, "a two winding transformer type"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + return Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] { + transformer2WType.getgM(), transformer2WType.getdPhi(), transformer2WType.getrSc() + }, + transformer2WType), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + transformer2WType.getsRated(), + transformer2WType.getvRatedA(), + transformer2WType.getvRatedB(), + transformer2WType.getxSc() + }, + transformer2WType), + () -> + detectPositiveQuantities( + new Quantity[] {transformer2WType.getbM()}, transformer2WType), + () -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType), + () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType), + () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType)); } /** @@ -166,23 +241,44 @@ protected static void checkTransformer2WType(Transformer2WTypeInput transformer2 * - its rated voltages match the voltages at the nodes * * @param transformer3W Transformer3W to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkTransformer3W(Transformer3WInput transformer3W) { - checkTransformer3WType(transformer3W.getType()); - checkIfTapPositionIsWithinBounds(transformer3W); + private static List> checkTransformer3W( + Transformer3WInput transformer3W) { + List> exceptions = + new ArrayList<>(checkTransformer3WType(transformer3W.getType())); + + exceptions.add( + Try.ofVoid( + () -> checkIfTapPositionIsWithinBounds(transformer3W), InvalidEntityException.class)); + // Check if transformer connects different voltage levels - if (transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeB().getVoltLvl() - || transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeC().getVoltLvl() - || transformer3W.getNodeB().getVoltLvl() == transformer3W.getNodeC().getVoltLvl()) - throw new InvalidEntityException( - "Transformer connects nodes of the same voltage level", transformer3W); + exceptions.add( + Try.ofVoid( + transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeB().getVoltLvl() + || transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeC().getVoltLvl() + || transformer3W.getNodeB().getVoltLvl() == transformer3W.getNodeC().getVoltLvl(), + () -> + new InvalidEntityException( + "Transformer connects nodes of the same voltage level", transformer3W))); + // Check if transformer connects different subnets - if (transformer3W.getNodeA().getSubnet() == transformer3W.getNodeB().getSubnet() - || transformer3W.getNodeA().getSubnet() == transformer3W.getNodeC().getSubnet() - || transformer3W.getNodeB().getSubnet() == transformer3W.getNodeC().getSubnet()) - throw new InvalidEntityException( - "Transformer connects nodes in the same subnet", transformer3W); - ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W); + exceptions.add( + Try.ofVoid( + transformer3W.getNodeA().getSubnet() == transformer3W.getNodeB().getSubnet() + || transformer3W.getNodeA().getSubnet() == transformer3W.getNodeC().getSubnet() + || transformer3W.getNodeB().getSubnet() == transformer3W.getNodeC().getSubnet(), + () -> + new InvalidEntityException( + "Transformer connects nodes in the same subnet", transformer3W))); + + exceptions.add( + Try.ofVoid( + () -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W), + InvalidEntityException.class)); + + return exceptions; } /** @@ -200,26 +296,47 @@ private static void checkTransformer3W(Transformer3WInput transformer3W) { * - minimum tap position is smaller than maximum tap position
* * @param transformer3WType Transformer type to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void checkTransformer3WType(Transformer3WTypeInput transformer3WType) { - checkNonNull(transformer3WType, "a three winding transformer type"); - detectNegativeQuantities( - new Quantity[] {transformer3WType.getgM(), transformer3WType.getdPhi()}, - transformer3WType); - detectZeroOrNegativeQuantities( - new Quantity[] { - transformer3WType.getsRatedA(), transformer3WType.getsRatedB(), - transformer3WType.getsRatedC(), - transformer3WType.getvRatedA(), transformer3WType.getvRatedB(), - transformer3WType.getvRatedC(), - transformer3WType.getrScA(), transformer3WType.getrScB(), transformer3WType.getrScC(), - transformer3WType.getxScA(), transformer3WType.getxScB(), transformer3WType.getxScC() - }, - transformer3WType); - detectPositiveQuantities(new Quantity[] {transformer3WType.getbM()}, transformer3WType); - checkVoltageMagnitudeChangePerTapPosition(transformer3WType); - checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType); - checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType); + protected static List> checkTransformer3WType( + Transformer3WTypeInput transformer3WType) { + Try isNull = + checkNonNull(transformer3WType, "a three winding transformer type"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + return Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {transformer3WType.getgM(), transformer3WType.getdPhi()}, + transformer3WType), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + transformer3WType.getsRatedA(), + transformer3WType.getsRatedB(), + transformer3WType.getsRatedC(), + transformer3WType.getvRatedA(), + transformer3WType.getvRatedB(), + transformer3WType.getvRatedC(), + transformer3WType.getrScA(), + transformer3WType.getrScB(), + transformer3WType.getrScC(), + transformer3WType.getxScA(), + transformer3WType.getxScB(), + transformer3WType.getxScC() + }, + transformer3WType), + () -> + detectPositiveQuantities( + new Quantity[] {transformer3WType.getbM()}, transformer3WType), + () -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType), + () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType), + () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType)); } /** @@ -227,26 +344,80 @@ protected static void checkTransformer3WType(Transformer3WTypeInput transformer3 * - its connected nodes are in the same voltage level * * @param switchInput Switch to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static void checkSwitch(SwitchInput switchInput) { - if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) - throw new InvalidEntityException("Switch connects two different voltage levels", switchInput); + private static Try checkSwitch(SwitchInput switchInput) { + return Try.ofVoid( + !switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl()), + () -> + new InvalidEntityException( + "Switch connects two different voltage levels", switchInput)); /* Remark: Connecting two different "subnets" is fine, because as of our definition regarding a switchgear in * "upstream" direction of a transformer, all the nodes, that hare within the switch chain, belong to the lower * grid, whilst the "real" upper node is within the upper grid */ } + /** + * Check if all given elements are connected. + * + * @param subGridContainer the subgrid to check the connectivity for + * @return a try object either containing an {@link InvalidGridException} or an empty Success + */ + protected static Try checkConnectivity( + SubGridContainer subGridContainer) { + Graph graph = new SimpleGraph<>(DefaultEdge.class); + + subGridContainer.getRawGrid().getNodes().forEach(node -> graph.addVertex(node.getUuid())); + subGridContainer + .getRawGrid() + .getLines() + .forEach(line -> graph.addEdge(line.getNodeA().getUuid(), line.getNodeB().getUuid())); + subGridContainer + .getRawGrid() + .getTransformer2Ws() + .forEach( + trafo2w -> graph.addEdge(trafo2w.getNodeA().getUuid(), trafo2w.getNodeB().getUuid())); + subGridContainer + .getRawGrid() + .getTransformer3Ws() + .forEach( + trafor3w -> { + graph.addEdge(trafor3w.getNodeA().getUuid(), trafor3w.getNodeInternal().getUuid()); + graph.addEdge(trafor3w.getNodeInternal().getUuid(), trafor3w.getNodeB().getUuid()); + graph.addEdge(trafor3w.getNodeInternal().getUuid(), trafor3w.getNodeC().getUuid()); + }); + subGridContainer + .getRawGrid() + .getSwitches() + .forEach( + switches -> + graph.addEdge(switches.getNodeA().getUuid(), switches.getNodeB().getUuid())); + + ConnectivityInspector inspector = new ConnectivityInspector<>(graph); + + return Try.ofVoid( + !inspector.isConnected(), + () -> + new InvalidGridException( + "The grid with subnetNo " + + subGridContainer.getSubnet() + + " is not connected! Please ensure that all elements are connected correctly!")); + } + /** * Check that a connector connects different nodes * * @param connectorInput connectorInput to validate */ - private static void connectsDifferentNodes(ConnectorInput connectorInput) { - if (connectorInput.getNodeA() == connectorInput.getNodeB()) { - throw new InvalidEntityException( - connectorInput.getClass().getSimpleName() + " connects the same node, but shouldn't", - connectorInput); - } + private static Try connectsDifferentNodes( + ConnectorInput connectorInput) { + return Try.ofVoid( + connectorInput.getNodeA().equals(connectorInput.getNodeB()), + () -> + new InvalidEntityException( + connectorInput.getClass().getSimpleName() + + " connects the same node, but shouldn't", + connectorInput)); } /** @@ -255,7 +426,8 @@ private static void connectsDifferentNodes(ConnectorInput connectorInput) { * @param connectorInput ConnectorInput to validate * @param yes determines if subnets should be equal or not */ - private static void connectsNodesInDifferentSubnets(ConnectorInput connectorInput, boolean yes) { + private static void connectsNodesInDifferentSubnets(ConnectorInput connectorInput, boolean yes) + throws InvalidEntityException { if (yes) { if (connectorInput.getNodeA().getSubnet() == connectorInput.getNodeB().getSubnet()) { throw new InvalidEntityException( @@ -280,7 +452,7 @@ private static void connectsNodesInDifferentSubnets(ConnectorInput connectorInpu * @param yes determines if voltage levels should be equal or not */ private static void connectsNodesWithDifferentVoltageLevels( - ConnectorInput connectorInput, boolean yes) { + ConnectorInput connectorInput, boolean yes) throws InvalidEntityException { if (yes) { if (connectorInput.getNodeA().getVoltLvl().equals(connectorInput.getNodeB().getVoltLvl())) { throw new InvalidEntityException( @@ -311,16 +483,18 @@ private static void coordinatesOfLineEqualCoordinatesOfNodes(LineInput line) { || line.getGeoPosition() .getEndPoint() .isWithinDistance(line.getNodeA().getGeoPosition(), ALLOWED_COORDINATE_ERROR))) - throw new InvalidEntityException( - "Coordinates of start and end point do not match coordinates of connected nodes", line); + logger.warn( + "Coordinates of start and end point do not match coordinates of connected nodes: {}", + line); if (!(line.getGeoPosition() .getStartPoint() .isWithinDistance(line.getNodeB().getGeoPosition(), ALLOWED_COORDINATE_ERROR) || line.getGeoPosition() .getEndPoint() .isWithinDistance(line.getNodeB().getGeoPosition(), ALLOWED_COORDINATE_ERROR))) - throw new InvalidEntityException( - "Coordinates of start and end point do not match coordinates of connected nodes", line); + logger.warn( + "Coordinates of start and end point do not match coordinates of connected nodes: {}", + line); } /** @@ -332,10 +506,13 @@ private static void lineLengthMatchesDistancesBetweenPointsOfLineString(LineInpu // only if not geo positions of both nodes are dummy values if ((line.getNodeA().getGeoPosition() != NodeInput.DEFAULT_GEO_POSITION || line.getNodeB().getGeoPosition() != NodeInput.DEFAULT_GEO_POSITION) - && !QuantityUtil.isEquivalentAbs( - line.getLength(), GeoUtils.calcHaversine(line.getGeoPosition()), ALLOWED_LENGTH_ERROR)) - throw new InvalidEntityException( - "Line length does not equal calculated distances between points building the line", line); + && line.getLength() + .isGreaterThan( + GeoUtils.calcHaversine(line.getGeoPosition()).multiply(ALLOWED_LENGTH_ERROR))) { + logger.warn( + "Line length is more than {}% greater than the calculated distances between points building the line: {}", + ALLOWED_LENGTH_ERROR, line); + } } /** @@ -343,7 +520,8 @@ private static void lineLengthMatchesDistancesBetweenPointsOfLineString(LineInpu * * @param transformer2W Transformer2WInput to validate */ - private static void checkIfTapPositionIsWithinBounds(Transformer2WInput transformer2W) { + private static void checkIfTapPositionIsWithinBounds(Transformer2WInput transformer2W) + throws InvalidEntityException { if (transformer2W.getTapPos() < transformer2W.getType().getTapMin() || transformer2W.getTapPos() > transformer2W.getType().getTapMax()) throw new InvalidEntityException( @@ -356,7 +534,8 @@ private static void checkIfTapPositionIsWithinBounds(Transformer2WInput transfor * * @param transformer3W Transformer3WInput to validate */ - private static void checkIfTapPositionIsWithinBounds(Transformer3WInput transformer3W) { + private static void checkIfTapPositionIsWithinBounds(Transformer3WInput transformer3W) + throws InvalidEntityException { if (transformer3W.getTapPos() < transformer3W.getType().getTapMin() || transformer3W.getTapPos() > transformer3W.getType().getTapMax()) throw new InvalidEntityException( @@ -370,7 +549,7 @@ private static void checkIfTapPositionIsWithinBounds(Transformer3WInput transfor * @param transformer2W Transformer2WInput to validate */ private static void ratedVoltageOfTransformer2WMatchesVoltagesOfNodes( - Transformer2WInput transformer2W) { + Transformer2WInput transformer2W) throws InvalidEntityException { if (!QuantityUtil.isEquivalentAbs( transformer2W.getType().getvRatedA(), transformer2W.getNodeA().getVoltLvl().getNominalVoltage(), @@ -392,7 +571,7 @@ private static void ratedVoltageOfTransformer2WMatchesVoltagesOfNodes( * @param transformer3W Transformer3WInput to validate */ private static void ratedVoltageOfTransformer3WMatchesVoltagesOfNodes( - Transformer3WInput transformer3W) { + Transformer3WInput transformer3W) throws InvalidEntityException { if (!QuantityUtil.isEquivalentAbs( transformer3W.getType().getvRatedA(), transformer3W.getNodeA().getVoltLvl().getNominalVoltage(), @@ -419,7 +598,7 @@ private static void ratedVoltageOfTransformer3WMatchesVoltagesOfNodes( * @param transformer2WType Transformer2WTypeInput to validate */ private static void checkVoltageMagnitudeChangePerTapPosition( - Transformer2WTypeInput transformer2WType) { + Transformer2WTypeInput transformer2WType) throws InvalidEntityException { if (transformer2WType.getdV().isLessThan(Quantities.getQuantity(0d, Units.PERCENT)) || transformer2WType.getdV().isGreaterThan(Quantities.getQuantity(100d, Units.PERCENT))) throw new InvalidEntityException( @@ -434,7 +613,7 @@ private static void checkVoltageMagnitudeChangePerTapPosition( * @param transformer3WType Transformer3WTypeInput to validate */ private static void checkVoltageMagnitudeChangePerTapPosition( - Transformer3WTypeInput transformer3WType) { + Transformer3WTypeInput transformer3WType) throws InvalidEntityException { if (transformer3WType.getdV().isLessThan(Quantities.getQuantity(0d, Units.PERCENT)) || transformer3WType.getdV().isGreaterThan(Quantities.getQuantity(100d, Units.PERCENT))) throw new InvalidEntityException( @@ -448,7 +627,7 @@ private static void checkVoltageMagnitudeChangePerTapPosition( * @param transformer2WType Transformer2WTypeInput to validate */ private static void checkMinimumTapPositionIsLowerThanMaximumTapPosition( - Transformer2WTypeInput transformer2WType) { + Transformer2WTypeInput transformer2WType) throws InvalidEntityException { if (transformer2WType.getTapMax() < transformer2WType.getTapMin()) throw new InvalidEntityException( "Minimum tap position must be lower than maximum tap position", transformer2WType); @@ -460,7 +639,7 @@ private static void checkMinimumTapPositionIsLowerThanMaximumTapPosition( * @param transformer3WType Transformer3WTypeInput to validate */ private static void checkMinimumTapPositionIsLowerThanMaximumTapPosition( - Transformer3WTypeInput transformer3WType) { + Transformer3WTypeInput transformer3WType) throws InvalidEntityException { if (transformer3WType.getTapMax() < transformer3WType.getTapMin()) throw new InvalidEntityException( "Minimum tap position must be lower than maximum tap position", transformer3WType); @@ -472,7 +651,7 @@ private static void checkMinimumTapPositionIsLowerThanMaximumTapPosition( * @param transformer2WType Transformer3WTypeInput to validate */ private static void checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition( - Transformer2WTypeInput transformer2WType) { + Transformer2WTypeInput transformer2WType) throws InvalidEntityException { if (transformer2WType.getTapNeutr() < transformer2WType.getTapMin() || transformer2WType.getTapNeutr() > transformer2WType.getTapMax()) throw new InvalidEntityException( @@ -486,7 +665,7 @@ private static void checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition( * @param transformer3WType Transformer3WTypeInput to validate */ private static void checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition( - Transformer3WTypeInput transformer3WType) { + Transformer3WTypeInput transformer3WType) throws InvalidEntityException { if (transformer3WType.getTapNeutr() < transformer3WType.getTapMin() || transformer3WType.getTapNeutr() > transformer3WType.getTapMax()) throw new InvalidEntityException( diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java index d97615b5a..e47eadf61 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -9,6 +9,9 @@ import edu.ie3.datamodel.models.input.graphics.GraphicInput; import edu.ie3.datamodel.models.input.graphics.LineGraphicInput; import edu.ie3.datamodel.models.input.graphics.NodeGraphicInput; +import edu.ie3.datamodel.utils.Try; +import java.util.ArrayList; +import java.util.List; public class GraphicValidationUtils extends ValidationUtils { @@ -26,19 +29,33 @@ private GraphicValidationUtils() { * fulfill the checking task, based on the class of the given object. * * @param graphicInput GraphicInput to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void check(GraphicInput graphicInput) { - checkNonNull(graphicInput, "a graphic input"); - if (graphicInput.getGraphicLayer() == null) - throw new InvalidEntityException( - "Graphic Layer of graphic element is not defined", graphicInput); + protected static List> check(GraphicInput graphicInput) { + Try isNull = checkNonNull(graphicInput, "a graphic input"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + graphicInput.getGraphicLayer() == null, + () -> + new InvalidEntityException( + "Graphic Layer of graphic element is not defined", graphicInput))); // Further checks for subclasses - if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) - checkLineGraphicInput((LineGraphicInput) graphicInput); - if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) - checkNodeGraphicInput((NodeGraphicInput) graphicInput); + if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { + exceptions.add(checkLineGraphicInput((LineGraphicInput) graphicInput)); + } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { + exceptions.add(checkNodeGraphicInput((NodeGraphicInput) graphicInput)); + } + + return exceptions; } /** @@ -47,10 +64,13 @@ protected static void check(GraphicInput graphicInput) { * * @param lineGraphicInput LineGraphicInput to validate */ - private static void checkLineGraphicInput(LineGraphicInput lineGraphicInput) { - if (lineGraphicInput.getPath() == null) - throw new InvalidEntityException( - "Path of line graphic element is not defined", lineGraphicInput); + private static Try checkLineGraphicInput( + LineGraphicInput lineGraphicInput) { + return Try.ofVoid( + lineGraphicInput.getPath() == null, + () -> + new InvalidEntityException( + "Path of line graphic element is not defined", lineGraphicInput)); } /** @@ -60,8 +80,10 @@ private static void checkLineGraphicInput(LineGraphicInput lineGraphicInput) { * * @param nodeGraphicInput NodeGraphicInput to validate */ - private static void checkNodeGraphicInput(NodeGraphicInput nodeGraphicInput) { - if (nodeGraphicInput.getPoint() == null) - throw new InvalidEntityException("Point of node graphic is not defined", nodeGraphicInput); + private static Try checkNodeGraphicInput( + NodeGraphicInput nodeGraphicInput) { + return Try.ofVoid( + nodeGraphicInput.getPoint() == null, + () -> new InvalidEntityException("Point of node graphic is not defined", nodeGraphicInput)); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java index a25141711..9f2447d0b 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -7,6 +7,8 @@ import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.InvalidGridException; +import edu.ie3.datamodel.exceptions.UnsafeEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.AssetInput; import edu.ie3.datamodel.models.input.MeasurementUnitInput; import edu.ie3.datamodel.models.input.NodeInput; @@ -14,8 +16,11 @@ import edu.ie3.datamodel.models.input.connector.LineInput; import edu.ie3.datamodel.models.input.connector.Transformer3WInput; import edu.ie3.datamodel.models.input.container.*; +import edu.ie3.datamodel.models.input.graphics.GraphicInput; import edu.ie3.datamodel.models.input.system.SystemParticipantInput; import edu.ie3.datamodel.utils.ContainerUtils; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.*; import java.util.*; import java.util.stream.Stream; @@ -38,25 +43,45 @@ private GridContainerValidationUtils() { * Checks a complete grid data container * * @param gridContainer Grid model to check + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void check(GridContainer gridContainer) { - checkNonNull(gridContainer, "grid container"); + protected static List> check( + GridContainer gridContainer) { + Try isNull = checkNonNull(gridContainer, "grid container"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(gridContainer.allEntitiesAsList())); - if (exceptionString.isPresent()) { - throw new InvalidGridException( - duplicateUuidsString(gridContainer.getClass().getSimpleName(), exceptionString)); + exceptions.add( + Try.ofVoid( + exceptionString.isPresent(), + () -> + new InvalidGridException( + duplicateUuidsString( + gridContainer.getClass().getSimpleName(), exceptionString)))); + + exceptions.addAll(checkRawGridElements(gridContainer.getRawGrid())); + exceptions.addAll( + checkSystemParticipants( + gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes())); + exceptions.addAll( + checkGraphicElements( + gridContainer.getGraphics(), + gridContainer.getRawGrid().getNodes(), + gridContainer.getRawGrid().getLines())); + + if (gridContainer instanceof SubGridContainer subGridContainer) { + exceptions.add(ConnectorValidationUtils.checkConnectivity(subGridContainer)); } - checkRawGridElements(gridContainer.getRawGrid()); - checkSystemParticipants( - gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes()); - checkGraphicElements( - gridContainer.getGraphics(), - gridContainer.getRawGrid().getNodes(), - gridContainer.getRawGrid().getLines()); + return exceptions; } /** @@ -64,18 +89,29 @@ protected static void check(GridContainer gridContainer) { * as the fact, that none of the assets is connected to a node, that is not in the set of nodes. * * @param rawGridElements Raw grid elements - * @throws InvalidGridException If something is wrong + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void checkRawGridElements(RawGridElements rawGridElements) { - checkNonNull(rawGridElements, "raw grid elements"); + protected static List> checkRawGridElements( + RawGridElements rawGridElements) { + Try isNull = checkNonNull(rawGridElements, "raw grid elements"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(rawGridElements.allEntitiesAsList())); - if (exceptionString.isPresent()) { - throw new InvalidGridException( - duplicateUuidsString(rawGridElements.getClass().getSimpleName(), exceptionString)); - } + exceptions.add( + Try.ofVoid( + exceptionString.isPresent(), + () -> + new InvalidGridException( + duplicateUuidsString( + rawGridElements.getClass().getSimpleName(), exceptionString)))); /* Checking nodes */ Set nodes = rawGridElements.getNodes(); @@ -86,8 +122,8 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getLines() .forEach( line -> { - checkNodeAvailability(line, nodes); - ConnectorValidationUtils.check(line); + exceptions.add(checkNodeAvailability(line, nodes)); + exceptions.addAll(ConnectorValidationUtils.check(line)); }); /* Checking two winding transformers */ @@ -95,8 +131,8 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getTransformer2Ws() .forEach( transformer -> { - checkNodeAvailability(transformer, nodes); - ConnectorValidationUtils.check(transformer); + exceptions.add(checkNodeAvailability(transformer, nodes)); + exceptions.addAll(ConnectorValidationUtils.check(transformer)); }); /* Checking three winding transformers */ @@ -104,8 +140,8 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getTransformer3Ws() .forEach( transformer -> { - checkNodeAvailability(transformer, nodes); - ConnectorValidationUtils.check(transformer); + exceptions.add(checkNodeAvailability(transformer, nodes)); + exceptions.addAll(ConnectorValidationUtils.check(transformer)); }); /* Checking switches @@ -127,8 +163,8 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getSwitches() .forEach( switcher -> { - checkNodeAvailability(switcher, validSwitchNodes); - ConnectorValidationUtils.check(switcher); + exceptions.add(checkNodeAvailability(switcher, validSwitchNodes)); + exceptions.addAll(ConnectorValidationUtils.check(switcher)); }); /* Checking measurement units */ @@ -136,9 +172,33 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getMeasurementUnits() .forEach( measurement -> { - checkNodeAvailability(measurement, nodes); - MeasurementUnitValidationUtils.check(measurement); + exceptions.add(checkNodeAvailability(measurement, nodes)); + exceptions.add(MeasurementUnitValidationUtils.check(measurement)); }); + + exceptions.addAll(checkRawGridTypeIds(rawGridElements)); + + return exceptions; + } + + /** + * Checks the validity of type ids of every entity. + * + * @param rawGridElements the raw grid elements + * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty + * Success + */ + protected static List> checkRawGridTypeIds( + RawGridElements rawGridElements) { + List> exceptions = new ArrayList<>(); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getNodes())); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getLines())); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getTransformer2Ws())); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getTransformer3Ws())); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getSwitches())); + exceptions.addAll(ValidationUtils.checkIds(rawGridElements.getMeasurementUnits())); + + return exceptions; } /** @@ -147,86 +207,94 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { * * @param systemParticipants The system participants * @param nodes Set of already known nodes + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void checkSystemParticipants( + protected static List> checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { - checkNonNull(systemParticipants, "system participants"); + Try isNull = + checkNonNull(systemParticipants, "system participants"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = ValidationUtils.checkForDuplicateUuids( new HashSet<>(systemParticipants.allEntitiesAsList())); - if (exceptionString.isPresent()) { - throw new InvalidGridException( - duplicateUuidsString(systemParticipants.getClass().getSimpleName(), exceptionString)); - } - - systemParticipants - .getBmPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - systemParticipants - .getChpPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - /* TODO: Electric vehicle charging systems are currently only dummy implementation. if this has changed, the whole - * method can be aggregated */ - - systemParticipants - .getFixedFeedIns() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - systemParticipants - .getHeatPumps() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + exceptions.add( + Try.ofVoid( + exceptionString.isPresent(), + () -> + new InvalidGridException( + duplicateUuidsString( + systemParticipants.getClass().getSimpleName(), exceptionString)))); + + exceptions.addAll(checkSystemParticipants(systemParticipants.getBmPlants(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getChpPlants(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getEvCS(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getFixedFeedIns(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getHeatPumps(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getLoads(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getPvPlants(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getStorages(), nodes)); + exceptions.addAll(checkSystemParticipants(systemParticipants.getWecPlants(), nodes)); + exceptions.addAll(checkSystemParticipantsTypeIds(systemParticipants)); + + return exceptions; + } - systemParticipants - .getLoads() - .forEach( + /** + * Checks the validity of specific system participant. Moreover, it checks, if the systems are + * connected to a node that is not in the provided set + * + * @param participants a set of specific system participants + * @param nodes Set of already known nodes + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success + */ + protected static List> checkSystemParticipants( + Set participants, Set nodes) { + return participants.stream() + .map( entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + List> exceptions = new ArrayList<>(); - systemParticipants - .getPvPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + exceptions.add(checkNodeAvailability(entity, nodes)); + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - systemParticipants - .getStorages() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + return exceptions; + }) + .flatMap(List::stream) + .toList(); + } - systemParticipants - .getWecPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + /** + * Checks the validity of type ids of every entity. + * + * @param systemParticipants the system participants + * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty + * Success + */ + protected static List> checkSystemParticipantsTypeIds( + SystemParticipants systemParticipants) { + List> exceptions = new ArrayList<>(); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getBmPlants())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getChpPlants())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getEvCS())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getEvs())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getFixedFeedIns())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getHeatPumps())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getLoads())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getPvPlants())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getStorages())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getWecPlants())); + exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getEmSystems())); + + return exceptions; } /** @@ -235,112 +303,121 @@ protected static void checkSystemParticipants( * @param graphicElements Elements to check * @param nodes Already known and checked nodes * @param lines Already known and checked lines + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void checkGraphicElements( + protected static List> checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { - checkNonNull(graphicElements, "graphic elements"); + Try isNull = checkNonNull(graphicElements, "graphic elements"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = checkForDuplicateUuids(new HashSet<>(graphicElements.allEntitiesAsList())); - if (exceptionString.isPresent()) { - throw new InvalidGridException( - duplicateUuidsString(graphicElements.getClass().getSimpleName(), exceptionString)); - } + exceptions.add( + Try.ofVoid( + exceptionString.isPresent(), + () -> + new InvalidGridException( + duplicateUuidsString( + graphicElements.getClass().getSimpleName(), exceptionString)))); graphicElements .getNodeGraphics() .forEach( graphic -> { - GraphicValidationUtils.check(graphic); - if (!nodes.contains(graphic.getNode())) - throw new InvalidEntityException( - "The node graphic with uuid '" - + graphic.getUuid() - + "' refers to node with uuid '" - + graphic.getNode().getUuid() - + "', that is not among the provided ones.", - graphic); + exceptions.addAll(GraphicValidationUtils.check(graphic)); + exceptions.add( + Try.ofVoid( + !nodes.contains(graphic.getNode()), + () -> + buildGraphicExceptionMessage( + graphic, "node", graphic.getNode().getUuid()))); }); graphicElements .getLineGraphics() .forEach( graphic -> { - GraphicValidationUtils.check(graphic); - if (!lines.contains(graphic.getLine())) - throw new InvalidEntityException( - "The line graphic with uuid '" - + graphic.getUuid() - + "' refers to line with uuid '" - + graphic.getLine().getUuid() - + "', that is not among the provided ones.", - graphic); + exceptions.addAll(GraphicValidationUtils.check(graphic)); + exceptions.add( + Try.ofVoid( + !lines.contains(graphic.getLine()), + () -> + buildGraphicExceptionMessage( + graphic, "line", graphic.getLine().getUuid()))); }); - } - - /** - * Checks, if the nodes of the {@link ConnectorInput} are in the collection of provided, already - * determined nodes - * - * @param connector Connector to examine - * @param nodes Permissible, already known nodes - */ - private static void checkNodeAvailability(ConnectorInput connector, Collection nodes) { - if (!nodes.containsAll(Arrays.asList(connector.getNodeA(), connector.getNodeB()))) - throw getMissingNodeException(connector); - } - /** - * Checks, if the nodes of the {@link Transformer3WInput} are in the collection of provided, - * already determined nodes - * - * @param transformer Transformer to examine - * @param nodes Permissible, already known nodes - */ - private static void checkNodeAvailability( - Transformer3WInput transformer, Collection nodes) { - if (!nodes.containsAll( - Arrays.asList(transformer.getNodeA(), transformer.getNodeB(), transformer.getNodeC()))) - throw getMissingNodeException(transformer); + return exceptions; } /** - * Checks, if the node of the {@link SystemParticipantInput} are in the collection of provided, - * already determined nodes + * Checks if the node(s) of the given {@link AssetInput} are in the collection of provided already + * determined nodes. * - * @param participant Connector to examine - * @param nodes Permissible, already known nodes + * @param input asset to examine + * @param nodes permissible, already known nodes + * @return either an {@link InvalidGridException} wrapped in a {@link Failure} or an empty {@link + * Success} */ - private static void checkNodeAvailability( - SystemParticipantInput participant, Collection nodes) { - if (!nodes.contains(participant.getNode())) throw getMissingNodeException(participant); - } + private static Try checkNodeAvailability( + AssetInput input, Collection nodes) { + boolean available; + + if (input instanceof Transformer3WInput transformer) { + available = + !nodes.containsAll( + Arrays.asList( + transformer.getNodeA(), transformer.getNodeB(), transformer.getNodeC())); + } else if (input instanceof ConnectorInput connector) { + available = !nodes.containsAll(Arrays.asList(connector.getNodeA(), connector.getNodeB())); + } else if (input instanceof SystemParticipantInput participant) { + available = !nodes.contains(participant.getNode()); + } else if (input instanceof MeasurementUnitInput measurementUnit) { + available = !nodes.contains(measurementUnit.getNode()); + } else { + return Failure.ofVoid( + new InvalidGridException( + "Checking the node availability of" + + input.getClass().getSimpleName() + + " is not implemented.")); + } - /** - * Checks, if the node of the {@link MeasurementUnitInput} are in the collection of provided, - * already determined nodes - * - * @param measurementUnit Connector to examine - * @param nodes Permissible, already known nodes - */ - private static void checkNodeAvailability( - MeasurementUnitInput measurementUnit, Collection nodes) { - if (!nodes.contains(measurementUnit.getNode())) throw getMissingNodeException(measurementUnit); + return Try.ofVoid( + available, + () -> + new InvalidGridException( + input.getClass().getSimpleName() + + " " + + input + + " is connected to a node that is not in the set of nodes.")); } /** - * Builds an exception, that announces, that the given input is connected to a node, that is not - * in the set of nodes provided. + * Creates a {@link InvalidEntityException} for graphic inputs. * - * @param input Input model - * @return Exception for a missing node + * @param graphic input + * @param type of the graphic + * @param asset uuid of the referred asset + * @return a {@link Failure} */ - private static InvalidGridException getMissingNodeException(AssetInput input) { - return new InvalidGridException( - input.getClass().getSimpleName() - + " " - + input - + " is connected to a node that is not in the set of nodes."); + private static InvalidEntityException buildGraphicExceptionMessage( + GraphicInput graphic, String type, UUID asset) { + return new InvalidEntityException( + "The " + + type + + " graphic with uuid '" + + graphic.getUuid() + + "' refers to " + + type + + " with uuid '" + + asset + + "', that is not a,ong the provided ones.", + graphic); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java index 6486dd1ad..318cfd13f 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -5,8 +5,11 @@ */ package edu.ie3.datamodel.utils.validation; +import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.UnsafeEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.MeasurementUnitInput; +import edu.ie3.datamodel.utils.Try; public class MeasurementUnitValidationUtils extends ValidationUtils { @@ -21,14 +24,23 @@ private MeasurementUnitValidationUtils() { * - any values are measured * * @param measurementUnit Measurement unit to validate + * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static void check(MeasurementUnitInput measurementUnit) { - checkNonNull(measurementUnit, "a measurement unit"); - if (!measurementUnit.getP() - && !measurementUnit.getQ() - && !measurementUnit.getVAng() - && !measurementUnit.getVMag()) - throw new UnsafeEntityException( - "Measurement Unit does not measure any values", measurementUnit); + protected static Try check( + MeasurementUnitInput measurementUnit) { + Try isNull = checkNonNull(measurementUnit, "a measurement unit"); + + if (isNull.isFailure()) { + return isNull; + } + + return Try.ofVoid( + !measurementUnit.getP() + && !measurementUnit.getQ() + && !measurementUnit.getVAng() + && !measurementUnit.getVMag(), + () -> + new UnsafeEntityException( + "Measurement Unit does not measure any values", measurementUnit)); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java index 8aa3c545b..37f948c95 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -5,12 +5,14 @@ */ package edu.ie3.datamodel.utils.validation; -import edu.ie3.datamodel.exceptions.InvalidEntityException; -import edu.ie3.datamodel.exceptions.UnsafeEntityException; -import edu.ie3.datamodel.exceptions.VoltageLevelException; +import edu.ie3.datamodel.exceptions.*; import edu.ie3.datamodel.models.StandardUnits; import edu.ie3.datamodel.models.input.NodeInput; import edu.ie3.datamodel.models.voltagelevels.VoltageLevel; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.Failure; +import java.util.ArrayList; +import java.util.List; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -30,34 +32,61 @@ private NodeValidationUtils() { * - geoPosition is not null * * @param node Node to validate + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void check(NodeInput node) { - checkNonNull(node, "a node"); + protected static List> check(NodeInput node) { + Try isNull = checkNonNull(node, "a node"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + try { checkVoltageLevel(node.getVoltLvl()); } catch (VoltageLevelException e) { - throw new InvalidEntityException("Node has invalid voltage level", node); + exceptions.add( + new Failure<>(new InvalidEntityException("Node has invalid voltage level", node))); + } catch (InvalidEntityException invalidEntityException) { + exceptions.add(new Failure<>(invalidEntityException)); } - if (node.getvTarget() - .isLessThanOrEqualTo(Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) - throw new InvalidEntityException("Target voltage (p.u.) is not a positive value", node); - else if (node.getvTarget() - .isGreaterThan(Quantities.getQuantity(2, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) - throw new UnsafeEntityException("Target voltage (p.u.) might be too high", node); - if (node.getSubnet() <= 0) - throw new InvalidEntityException("Subnet can't be zero or negative", node); - if (node.getGeoPosition() == null) - throw new InvalidEntityException("GeoPosition of node is null", node); + + exceptions.add( + Try.ofVoid( + node.getvTarget() + .isLessThanOrEqualTo( + Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE)), + () -> + new InvalidEntityException("Target voltage (p.u.) is not a positive value", node))); + exceptions.add( + Try.ofVoid( + node.getvTarget() + .isGreaterThan(Quantities.getQuantity(2, StandardUnits.TARGET_VOLTAGE_MAGNITUDE)), + () -> new UnsafeEntityException("Target voltage (p.u.) might be too high", node))); + exceptions.add( + Try.ofVoid( + node.getSubnet() <= 0, + () -> new InvalidEntityException("Subnet can't be zero or negative", node))); + exceptions.add( + Try.ofVoid( + node.getGeoPosition() == null, + () -> new InvalidEntityException("GeoPosition of node is null", node))); + + return exceptions; } /** * Validates a voltage level * * @param voltageLevel Element to validate + * @throws InvalidEntityException If the given voltage level is null * @throws VoltageLevelException If nominal voltage is not apparent or not a positive value */ - private static void checkVoltageLevel(VoltageLevel voltageLevel) throws VoltageLevelException { - checkNonNull(voltageLevel, "a voltage level"); + private static void checkVoltageLevel(VoltageLevel voltageLevel) + throws InvalidEntityException, VoltageLevelException { + checkNonNull(voltageLevel, "a voltage level").getOrThrow(); if (voltageLevel.getNominalVoltage() == null) throw new VoltageLevelException( "The nominal voltage of voltage level " + voltageLevel + " is null"); diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java index dfa317819..b2e0bc896 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -9,9 +9,14 @@ import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.NotImplementedException; +import edu.ie3.datamodel.exceptions.TryException; import edu.ie3.datamodel.models.input.InputEntity; import edu.ie3.datamodel.models.input.system.*; import edu.ie3.datamodel.models.input.system.type.*; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.Failure; +import java.util.ArrayList; +import java.util.List; import javax.measure.Quantity; import javax.measure.quantity.Dimensionless; import tech.units.indriya.ComparableQuantity; @@ -34,35 +39,59 @@ private SystemParticipantValidationUtils() { * fulfill the checking task, based on the class of the given object. * * @param systemParticipant systemParticipant to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void check(SystemParticipantInput systemParticipant) { - checkNonNull(systemParticipant, "a system participant"); - if (systemParticipant.getqCharacteristics() == null) - throw new InvalidEntityException( - "Reactive power characteristics of system participant is not defined", systemParticipant); + protected static List> check( + SystemParticipantInput systemParticipant) { + Try isNull = + checkNonNull(systemParticipant, "a system participant"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + systemParticipant.getqCharacteristics() == null, + () -> + new InvalidEntityException( + "Reactive power characteristics of system participant is not defined", + systemParticipant))); // Further checks for subclasses - if (BmInput.class.isAssignableFrom(systemParticipant.getClass())) - checkBm((BmInput) systemParticipant); - else if (ChpInput.class.isAssignableFrom(systemParticipant.getClass())) - checkChp((ChpInput) systemParticipant); - else if (EvInput.class.isAssignableFrom(systemParticipant.getClass())) - checkEv((EvInput) systemParticipant); - else if (FixedFeedInInput.class.isAssignableFrom(systemParticipant.getClass())) - checkFixedFeedIn((FixedFeedInInput) systemParticipant); - else if (HpInput.class.isAssignableFrom(systemParticipant.getClass())) - checkHp((HpInput) systemParticipant); - else if (LoadInput.class.isAssignableFrom(systemParticipant.getClass())) - checkLoad((LoadInput) systemParticipant); - else if (PvInput.class.isAssignableFrom(systemParticipant.getClass())) - checkPv((PvInput) systemParticipant); - else if (StorageInput.class.isAssignableFrom(systemParticipant.getClass())) - checkStorage((StorageInput) systemParticipant); - else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) - checkWec((WecInput) systemParticipant); - else if (EvcsInput.class.isAssignableFrom(systemParticipant.getClass())) checkEvcs(); - else throw checkNotImplementedException(systemParticipant); + if (BmInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkBm((BmInput) systemParticipant)); + } else if (ChpInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkChp((ChpInput) systemParticipant)); + } else if (EvInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkEv((EvInput) systemParticipant)); + } else if (FixedFeedInInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkFixedFeedIn((FixedFeedInInput) systemParticipant)); + } else if (HpInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkHp((HpInput) systemParticipant)); + } else if (LoadInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkLoad((LoadInput) systemParticipant)); + } else if (PvInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkPv((PvInput) systemParticipant)); + } else if (StorageInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkStorage((StorageInput) systemParticipant)); + } else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.addAll(checkWec((WecInput) systemParticipant)); + } else if (EvcsInput.class.isAssignableFrom(systemParticipant.getClass())) { + exceptions.add( + Try.ofVoid(SystemParticipantValidationUtils::checkEvcs, NotImplementedException.class) + .transformF(e -> new InvalidEntityException(e.getMessage(), e.getCause()))); + } else { + exceptions.add( + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", buildNotImplementedException(systemParticipant)))); + } + + return exceptions; } /** @@ -77,37 +106,75 @@ else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) * fulfill the checking task, based on the class of the given object. * * @param systemParticipantTypeInput systemParticipant Type to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static void checkType(SystemParticipantTypeInput systemParticipantTypeInput) { - checkNonNull(systemParticipantTypeInput, "a system participant type"); - if ((systemParticipantTypeInput.getCapex() == null) - || (systemParticipantTypeInput.getOpex() == null) - || (systemParticipantTypeInput.getsRated() == null)) - throw new InvalidEntityException( - "At least one of capex, opex, or sRated is null", systemParticipantTypeInput); - detectNegativeQuantities( - new Quantity[] { - systemParticipantTypeInput.getCapex(), - systemParticipantTypeInput.getOpex(), - systemParticipantTypeInput.getsRated() - }, - systemParticipantTypeInput); - checkRatedPowerFactor(systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated()); - - if (BmTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkBmType((BmTypeInput) systemParticipantTypeInput); - else if (ChpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkChpType((ChpTypeInput) systemParticipantTypeInput); - else if (EvTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkEvType((EvTypeInput) systemParticipantTypeInput); - else if (HpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkHpType((HpTypeInput) systemParticipantTypeInput); - else if (StorageTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkStorageType((StorageTypeInput) systemParticipantTypeInput); - else if (WecTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) - checkWecType((WecTypeInput) systemParticipantTypeInput); - else throw checkNotImplementedException(systemParticipantTypeInput); + protected static List> checkType( + SystemParticipantTypeInput systemParticipantTypeInput) { + Try isNull = + checkNonNull(systemParticipantTypeInput, "a system participant type"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + (systemParticipantTypeInput.getCapex() == null) + || (systemParticipantTypeInput.getOpex() == null) + || (systemParticipantTypeInput.getsRated() == null), + () -> + new InvalidEntityException( + "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); + + try { + exceptions.add( + Try.ofVoid( + () -> + detectNegativeQuantities( + new Quantity[] { + systemParticipantTypeInput.getCapex(), + systemParticipantTypeInput.getOpex(), + systemParticipantTypeInput.getsRated() + }, + systemParticipantTypeInput), + InvalidEntityException.class)); + } catch (TryException e) { + Throwable wronglyCaught = e.getCause(); + exceptions.add( + Failure.ofVoid(new InvalidEntityException(wronglyCaught.getMessage(), wronglyCaught))); + } + + exceptions.add( + Try.ofVoid( + () -> + checkRatedPowerFactor( + systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated()), + InvalidEntityException.class)); + + if (BmTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.addAll(checkBmType((BmTypeInput) systemParticipantTypeInput)); + } else if (ChpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.addAll(checkChpType((ChpTypeInput) systemParticipantTypeInput)); + } else if (EvTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.add(checkEvType((EvTypeInput) systemParticipantTypeInput)); + } else if (HpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.add(checkHpType((HpTypeInput) systemParticipantTypeInput)); + } else if (StorageTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.addAll(checkStorageType((StorageTypeInput) systemParticipantTypeInput)); + } else if (WecTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + exceptions.addAll(checkWecType((WecTypeInput) systemParticipantTypeInput)); + } else { + exceptions.add( + new Failure<>( + new InvalidEntityException( + buildNotImplementedException(systemParticipantTypeInput).getMessage(), + systemParticipantTypeInput))); + } + + return exceptions; } /** @@ -116,9 +183,11 @@ else if (WecTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass * properties
* * @param bmInput BmInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkBm(BmInput bmInput) { - checkType(bmInput.getType()); + private static List> checkBm(BmInput bmInput) { + return checkType(bmInput.getType()); } /** @@ -127,10 +196,18 @@ private static void checkBm(BmInput bmInput) { * - its efficiency of assets inverter is between 0% and 100% * * @param bmTypeInput BmTypeInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkBmType(BmTypeInput bmTypeInput) { - detectNegativeQuantities(new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput); - isBetweenZeroAndHundredPercent(bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter"); + private static List> checkBmType(BmTypeInput bmTypeInput) { + return Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput), + () -> + isBetweenZeroAndHundredPercent( + bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter")); } /** @@ -139,9 +216,11 @@ private static void checkBmType(BmTypeInput bmTypeInput) { * properties * * @param chpInput ChpInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkChp(ChpInput chpInput) { - checkType(chpInput.getType()); + private static List> checkChp(ChpInput chpInput) { + return checkType(chpInput.getType()); } /** @@ -152,13 +231,22 @@ private static void checkChp(ChpInput chpInput) { * - its needed self-consumption is not negative * * @param chpTypeInput ChpTypeInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkChpType(ChpTypeInput chpTypeInput) { - detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput); - detectZeroOrNegativeQuantities(new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput); - isBetweenZeroAndHundredPercent(chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency"); - isBetweenZeroAndHundredPercent( - chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency"); + private static List> checkChpType(ChpTypeInput chpTypeInput) { + return Try.ofVoid( + InvalidEntityException.class, + () -> detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput), + () -> + isBetweenZeroAndHundredPercent( + chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency"), + () -> + isBetweenZeroAndHundredPercent( + chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency")); } /** @@ -167,9 +255,11 @@ private static void checkChpType(ChpTypeInput chpTypeInput) { * properties * * @param evInput EvInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkEv(EvInput evInput) { - checkType(evInput.getType()); + private static List> checkEv(EvInput evInput) { + return checkType(evInput.getType()); } /** @@ -178,10 +268,14 @@ private static void checkEv(EvInput evInput) { * - its energy consumption per driven kilometre is positive * * @param evTypeInput EvTypeInput to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static void checkEvType(EvTypeInput evTypeInput) { - detectZeroOrNegativeQuantities( - new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, evTypeInput); + private static Try checkEvType(EvTypeInput evTypeInput) { + return Try.ofVoid( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, evTypeInput), + InvalidEntityException.class); } /** @@ -190,10 +284,17 @@ private static void checkEvType(EvTypeInput evTypeInput) { * - its rated power factor is between 0 and 1 * * @param fixedFeedInInput FixedFeedInInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkFixedFeedIn(FixedFeedInInput fixedFeedInInput) { - detectNegativeQuantities(new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput); - checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated()); + private static List> checkFixedFeedIn( + FixedFeedInInput fixedFeedInInput) { + return Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput), + () -> checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated())); } /** @@ -202,9 +303,11 @@ private static void checkFixedFeedIn(FixedFeedInInput fixedFeedInInput) { * properties * * @param hpInput HpInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkHp(HpInput hpInput) { - checkType(hpInput.getType()); + private static List> checkHp(HpInput hpInput) { + return checkType(hpInput.getType()); } /** @@ -212,9 +315,14 @@ private static void checkHp(HpInput hpInput) { * - its rated thermal power is positive * * @param hpTypeInput HpTypeInput to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static void checkHpType(HpTypeInput hpTypeInput) { - detectZeroOrNegativeQuantities(new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput); + private static Try checkHpType(HpTypeInput hpTypeInput) { + return Try.ofVoid( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput), + InvalidEntityException.class); } /** @@ -225,13 +333,29 @@ private static void checkHpType(HpTypeInput hpTypeInput) { * - its rated power factor is between 0 and 1 * * @param loadInput LoadInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkLoad(LoadInput loadInput) { - if (loadInput.getLoadProfile() == null) - throw new InvalidEntityException("No standard load profile defined for load", loadInput); - detectNegativeQuantities( - new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, loadInput); - checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()); + private static List> checkLoad(LoadInput loadInput) { + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + loadInput.getLoadProfile() == null, + () -> + new InvalidEntityException( + "No standard load profile defined for load", loadInput))); + + exceptions.addAll( + Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, + loadInput), + () -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); + + return exceptions; } /** @@ -244,14 +368,20 @@ private static void checkLoad(LoadInput loadInput) { * - its rated power factor is between 0 and 1 * * @param pvInput PvInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkPv(PvInput pvInput) { - detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput); - checkAlbedo(pvInput); - checkAzimuth(pvInput); - isBetweenZeroAndHundredPercent(pvInput, pvInput.getEtaConv(), "Efficiency of the converter"); - checkElevationAngle(pvInput); - checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated()); + private static List> checkPv(PvInput pvInput) { + return Try.ofVoid( + InvalidEntityException.class, + () -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput), + () -> checkAlbedo(pvInput), + () -> checkAzimuth(pvInput), + () -> + isBetweenZeroAndHundredPercent( + pvInput, pvInput.getEtaConv(), "Efficiency of the converter"), + () -> checkElevationAngle(pvInput), + () -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated())); } /** @@ -259,7 +389,7 @@ private static void checkPv(PvInput pvInput) { * * @param pvInput PvInput to validate */ - private static void checkAlbedo(PvInput pvInput) { + private static void checkAlbedo(PvInput pvInput) throws InvalidEntityException { if (pvInput.getAlbedo() < 0d || pvInput.getAlbedo() > 1d) throw new InvalidEntityException( "Albedo of the plant's surrounding of " @@ -273,7 +403,7 @@ private static void checkAlbedo(PvInput pvInput) { * * @param pvInput PvInput to validate */ - private static void checkAzimuth(PvInput pvInput) { + private static void checkAzimuth(PvInput pvInput) throws InvalidEntityException { if (pvInput.getAzimuth().isLessThan(Quantities.getQuantity(-90d, AZIMUTH)) || pvInput.getAzimuth().isGreaterThan(Quantities.getQuantity(90d, AZIMUTH))) throw new InvalidEntityException( @@ -288,7 +418,7 @@ private static void checkAzimuth(PvInput pvInput) { * * @param pvInput PvInput to validate */ - private static void checkElevationAngle(PvInput pvInput) { + private static void checkElevationAngle(PvInput pvInput) throws InvalidEntityException { if (pvInput.getElevationAngle().isLessThan(Quantities.getQuantity(0d, SOLAR_ELEVATION_ANGLE)) || pvInput .getElevationAngle() @@ -306,9 +436,11 @@ private static void checkElevationAngle(PvInput pvInput) { * type properties * * @param storageInput StorageInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkStorage(StorageInput storageInput) { - checkType(storageInput.getType()); + private static List> checkStorage(StorageInput storageInput) { + return checkType(storageInput.getType()); } /** @@ -322,25 +454,47 @@ private static void checkStorage(StorageInput storageInput) { * - its permissible hours of full use is not negative * * @param storageTypeInput StorageTypeInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkStorageType(StorageTypeInput storageTypeInput) { - if (storageTypeInput.getLifeCycle() < 0) - throw new InvalidEntityException( - "Permissible amount of life cycles of the storage type must be zero or positive", - storageTypeInput); - isBetweenZeroAndHundredPercent( - storageTypeInput, storageTypeInput.getEta(), "Efficiency of the electrical converter"); - isBetweenZeroAndHundredPercent( - storageTypeInput, storageTypeInput.getDod(), "Maximum permissible depth of discharge"); - detectNegativeQuantities( - new Quantity[] { - storageTypeInput.getpMax(), - storageTypeInput.getActivePowerGradient(), - storageTypeInput.getLifeTime() - }, - storageTypeInput); - detectZeroOrNegativeQuantities( - new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput); + private static List> checkStorageType( + StorageTypeInput storageTypeInput) { + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + storageTypeInput.getLifeCycle() < 0, + () -> + new InvalidEntityException( + "Permissible amount of life cycles of the storage type must be zero or positive", + storageTypeInput))); + + exceptions.addAll( + Try.ofVoid( + InvalidEntityException.class, + () -> + isBetweenZeroAndHundredPercent( + storageTypeInput, + storageTypeInput.getEta(), + "Efficiency of the electrical converter"), + () -> + isBetweenZeroAndHundredPercent( + storageTypeInput, + storageTypeInput.getDod(), + "Maximum permissible depth of discharge"), + () -> + detectNegativeQuantities( + new Quantity[] { + storageTypeInput.getpMax(), + storageTypeInput.getActivePowerGradient(), + storageTypeInput.getLifeTime() + }, + storageTypeInput), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput))); + + return exceptions; } /** @@ -349,9 +503,11 @@ private static void checkStorageType(StorageTypeInput storageTypeInput) { * properties * * @param wecInput WecInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkWec(WecInput wecInput) { - checkType(wecInput.getType()); + private static List> checkWec(WecInput wecInput) { + return checkType(wecInput.getType()); } /** @@ -361,12 +517,19 @@ private static void checkWec(WecInput wecInput) { * - its height of the rotor hub is not negative * * @param wecTypeInput WecTypeInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkWecType(WecTypeInput wecTypeInput) { - isBetweenZeroAndHundredPercent( - wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter"); - detectNegativeQuantities( - new Quantity[] {wecTypeInput.getRotorArea(), wecTypeInput.getHubHeight()}, wecTypeInput); + private static List> checkWecType(WecTypeInput wecTypeInput) { + return Try.ofVoid( + InvalidEntityException.class, + () -> + isBetweenZeroAndHundredPercent( + wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter"), + () -> + detectNegativeQuantities( + new Quantity[] {wecTypeInput.getRotorArea(), wecTypeInput.getHubHeight()}, + wecTypeInput)); } /** Validates a EvcsInput */ @@ -383,7 +546,8 @@ private static void checkEvcs() { * @param input entity to validate * @param cosPhiRated rated power factor to check */ - private static void checkRatedPowerFactor(InputEntity input, double cosPhiRated) { + private static void checkRatedPowerFactor(InputEntity input, double cosPhiRated) + throws InvalidEntityException { if (cosPhiRated < 0d || cosPhiRated > 1d) throw new InvalidEntityException( "Rated power factor of " + input.getClass().getSimpleName() + " must be between 0 and 1", @@ -398,7 +562,8 @@ private static void checkRatedPowerFactor(InputEntity input, double cosPhiRated) * @param value value of entity to check */ private static void isBetweenZeroAndHundredPercent( - InputEntity input, ComparableQuantity value, String string) { + InputEntity input, ComparableQuantity value, String string) + throws InvalidEntityException { if (value.isLessThan(Quantities.getQuantity(0d, Units.PERCENT)) || value.isGreaterThan(Quantities.getQuantity(100d, Units.PERCENT))) throw new InvalidEntityException( diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java index e968d210e..8dd2b39f0 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -5,8 +5,14 @@ */ package edu.ie3.datamodel.utils.validation; +import edu.ie3.datamodel.exceptions.FailedValidationException; import edu.ie3.datamodel.exceptions.InvalidEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.thermal.*; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.Failure; +import java.util.ArrayList; +import java.util.List; import javax.measure.Quantity; public class ThermalUnitValidationUtils extends ValidationUtils { @@ -23,17 +29,32 @@ private ThermalUnitValidationUtils() { * the checking task, based on the class of the given object. * * @param thermalUnitInput ThermalUnitInput to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static void check(ThermalUnitInput thermalUnitInput) { - checkNonNull(thermalUnitInput, "a thermal unit"); + protected static List> check( + ThermalUnitInput thermalUnitInput) { + Try isNull = checkNonNull(thermalUnitInput, "a thermal unit"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); // Further checks for subclasses - if (ThermalSinkInput.class.isAssignableFrom(thermalUnitInput.getClass())) - checkThermalSink((ThermalSinkInput) thermalUnitInput); - else if (ThermalStorageInput.class.isAssignableFrom(thermalUnitInput.getClass())) - checkThermalStorage((ThermalStorageInput) thermalUnitInput); - else throw checkNotImplementedException(thermalUnitInput); + if (ThermalSinkInput.class.isAssignableFrom(thermalUnitInput.getClass())) { + exceptions.addAll(checkThermalSink((ThermalSinkInput) thermalUnitInput)); + } else if (ThermalStorageInput.class.isAssignableFrom(thermalUnitInput.getClass())) { + exceptions.addAll(checkThermalStorage((ThermalStorageInput) thermalUnitInput)); + } else { + exceptions.add( + new Failure<>( + new FailedValidationException( + buildNotImplementedException(thermalUnitInput).getMessage()))); + } + + return exceptions; } /** @@ -43,15 +64,30 @@ else if (ThermalStorageInput.class.isAssignableFrom(thermalUnitInput.getClass()) * the checking task, based on the class of the given object. * * @param thermalSinkInput ThermalSinkInput to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - private static void checkThermalSink(ThermalSinkInput thermalSinkInput) { - checkNonNull(thermalSinkInput, "a thermal sink"); + private static List> checkThermalSink( + ThermalSinkInput thermalSinkInput) { + Try isNull = checkNonNull(thermalSinkInput, "a thermal sink"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); // Further checks for subclasses - if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) - checkThermalHouse((ThermalHouseInput) thermalSinkInput); - else throw checkNotImplementedException(thermalSinkInput); + if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) { + exceptions.addAll(checkThermalHouse((ThermalHouseInput) thermalSinkInput)); + } else { + exceptions.add( + new Failure<>( + new FailedValidationException( + buildNotImplementedException(thermalSinkInput).getMessage()))); + } + + return exceptions; } /** @@ -61,15 +97,31 @@ private static void checkThermalSink(ThermalSinkInput thermalSinkInput) { * the checking task, based on the class of the given object. * * @param thermalStorageInput ThermalStorageInput to validate - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - private static void checkThermalStorage(ThermalStorageInput thermalStorageInput) { - checkNonNull(thermalStorageInput, "a thermal storage"); + private static List> checkThermalStorage( + ThermalStorageInput thermalStorageInput) { + Try isNull = + checkNonNull(thermalStorageInput, "a thermal storage"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); // Further checks for subclasses - if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) - checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput); - else throw checkNotImplementedException(thermalStorageInput); + if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) { + exceptions.addAll(checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput)); + } else { + exceptions.add( + new Failure<>( + new FailedValidationException( + buildNotImplementedException(thermalStorageInput).getMessage()))); + } + + return exceptions; } /** @@ -81,22 +133,42 @@ private static void checkThermalStorage(ThermalStorageInput thermalStorageInput) * - its target temperature lies between the upper und lower limit temperatures * * @param thermalHouseInput ThermalHouseInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkThermalHouse(ThermalHouseInput thermalHouseInput) { - checkNonNull(thermalHouseInput, "a thermal house"); - detectNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput); - detectZeroOrNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput); + private static List> checkThermalHouse( + ThermalHouseInput thermalHouseInput) { + Try isNull = checkNonNull(thermalHouseInput, "a thermal house"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = + new ArrayList<>( + Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput))); + if (thermalHouseInput .getLowerTemperatureLimit() .isGreaterThan(thermalHouseInput.getTargetTemperature()) || thermalHouseInput .getUpperTemperatureLimit() - .isLessThan(thermalHouseInput.getTargetTemperature())) - throw new InvalidEntityException( - "Target temperature must be higher than lower temperature limit and lower than upper temperature limit", - thermalHouseInput); + .isLessThan(thermalHouseInput.getTargetTemperature())) { + exceptions.add( + new Failure<>( + new InvalidEntityException( + "Target temperature must be higher than lower temperature limit and lower than upper temperature limit", + thermalHouseInput))); + } + + return exceptions; } /** @@ -109,27 +181,53 @@ private static void checkThermalHouse(ThermalHouseInput thermalHouseInput) { * - its specific heat capacity is positive * * @param cylindricalStorageInput CylindricalStorageInput to validate + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static void checkCylindricalStorage(CylindricalStorageInput cylindricalStorageInput) { - checkNonNull(cylindricalStorageInput, "a cylindrical storage"); + private static List> checkCylindricalStorage( + CylindricalStorageInput cylindricalStorageInput) { + Try isNull = + checkNonNull(cylindricalStorageInput, "a cylindrical storage"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + // Check if inlet temperature is higher/equal to outlet temperature - if (cylindricalStorageInput.getInletTemp().isLessThan(cylindricalStorageInput.getReturnTemp())) - throw new InvalidEntityException( - "Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", - cylindricalStorageInput); + exceptions.add( + Try.ofVoid( + cylindricalStorageInput + .getInletTemp() + .isLessThan(cylindricalStorageInput.getReturnTemp()), + () -> + new InvalidEntityException( + "Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", + cylindricalStorageInput))); // Check if minimum permissible storage volume is lower than overall available storage volume - if (cylindricalStorageInput - .getStorageVolumeLvlMin() - .isGreaterThan(cylindricalStorageInput.getStorageVolumeLvl())) - throw new InvalidEntityException( - "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", - cylindricalStorageInput); - detectZeroOrNegativeQuantities( - new Quantity[] { - cylindricalStorageInput.getStorageVolumeLvl(), - cylindricalStorageInput.getStorageVolumeLvlMin(), - cylindricalStorageInput.getC() - }, - cylindricalStorageInput); + exceptions.add( + Try.ofVoid( + cylindricalStorageInput + .getStorageVolumeLvlMin() + .isGreaterThan(cylindricalStorageInput.getStorageVolumeLvl()), + () -> + new InvalidEntityException( + "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", + cylindricalStorageInput))); + + exceptions.add( + Try.ofVoid( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + cylindricalStorageInput.getStorageVolumeLvl(), + cylindricalStorageInput.getStorageVolumeLvlMin(), + cylindricalStorageInput.getC() + }, + cylindricalStorageInput), + InvalidEntityException.class)); + + return exceptions; } } diff --git a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java index a0fbe3848..c09607a0d 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -20,15 +20,20 @@ import edu.ie3.datamodel.models.input.system.SystemParticipantInput; import edu.ie3.datamodel.models.input.system.type.*; import edu.ie3.datamodel.models.input.thermal.ThermalUnitInput; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.measure.Quantity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Basic Sanity validation tools for entities */ public class ValidationUtils { + protected static final Logger logger = LoggerFactory.getLogger(ValidationUtils.class); /** Private Constructor as this class is not meant to be instantiated */ protected ValidationUtils() { @@ -42,7 +47,7 @@ protected ValidationUtils() { * @param obj Object, that cannot be checked * @return Exception with predefined error string */ - protected static NotImplementedException checkNotImplementedException(Object obj) { + protected static NotImplementedException buildNotImplementedException(Object obj) { return new NotImplementedException( String.format( "Cannot validate object of class '%s', as no routine is implemented.", @@ -54,18 +59,33 @@ protected static NotImplementedException checkNotImplementedException(Object obj * fulfill the checking task, based on the class of the given object. * * @param obj Object to check - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in */ - public static void check(Object obj) { - checkNonNull(obj, "an object"); - if (AssetInput.class.isAssignableFrom(obj.getClass())) checkAsset((AssetInput) obj); - else if (GridContainer.class.isAssignableFrom(obj.getClass())) - GridContainerValidationUtils.check((GridContainer) obj); - else if (GraphicInput.class.isAssignableFrom(obj.getClass())) - GraphicValidationUtils.check((GraphicInput) obj); - else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) - checkAssetType((AssetTypeInput) obj); - else throw checkNotImplementedException(obj); + public static void check(Object obj) throws ValidationException { + checkNonNull(obj, "an object").getOrThrow(); + + List> exceptions = new ArrayList<>(); + + if (AssetInput.class.isAssignableFrom(obj.getClass())) { + exceptions.addAll(checkAsset((AssetInput) obj)); + } else if (GridContainer.class.isAssignableFrom(obj.getClass())) { + exceptions.addAll(GridContainerValidationUtils.check((GridContainer) obj)); + } else if (GraphicInput.class.isAssignableFrom(obj.getClass())) { + exceptions.addAll(GraphicValidationUtils.check((GraphicInput) obj)); + } else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) { + exceptions.addAll(checkAssetType((AssetTypeInput) obj)); + } else { + exceptions.add( + new Failure<>( + new FailedValidationException(buildNotImplementedException(obj).getMessage()))); + } + + List list = + exceptions.stream() + .filter(Try::isFailure) + .map(t -> ((Failure) t).get()) + .toList(); + + Try.ofVoid(!list.isEmpty(), () -> new FailedValidationException(list)).getOrThrow(); } /** @@ -78,44 +98,71 @@ else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) * the checking task, based on the class of the given object. * * @param assetInput AssetInput to check - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing a {@link ValidationException} or an empty + * Success */ - private static void checkAsset(AssetInput assetInput) { - checkNonNull(assetInput, "an asset"); - if (assetInput.getId() == null) throw new InvalidEntityException("No ID assigned", assetInput); - if (assetInput.getOperationTime() == null) - throw new InvalidEntityException("Operation time of the asset is not defined", assetInput); - // Check if start time and end time are not null and start time is before end time - if (assetInput.getOperationTime().isLimited()) { - assetInput - .getOperationTime() - .getEndDate() - .ifPresent( - endDate -> - assetInput - .getOperationTime() - .getStartDate() - .ifPresent( - startDate -> { - if (endDate.isBefore(startDate)) - throw new InvalidEntityException( - "Operation start time of the asset has to be before end time", - assetInput); - })); + private static List> checkAsset(AssetInput assetInput) { + Try isNull = checkNonNull(assetInput, "an asset"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + assetInput.getId() == null, + () -> new InvalidEntityException("No ID assigned", assetInput))); + + if (assetInput.getOperationTime() == null) { + exceptions.add( + Failure.ofVoid( + new InvalidEntityException( + "Operation time of the asset is not defined", assetInput))); + } else { + // Check if start time and end time are not null and start time is before end time + if (assetInput.getOperationTime().isLimited()) { + assetInput + .getOperationTime() + .getEndDate() + .ifPresent( + endDate -> + assetInput + .getOperationTime() + .getStartDate() + .ifPresent( + startDate -> { + if (endDate.isBefore(startDate)) + exceptions.add( + new Failure<>( + new InvalidEntityException( + "Operation start time of the asset has to be before end time", + assetInput))); + })); + } } // Further checks for subclasses if (NodeInput.class.isAssignableFrom(assetInput.getClass())) - NodeValidationUtils.check((NodeInput) assetInput); + exceptions.addAll(NodeValidationUtils.check((NodeInput) assetInput)); else if (ConnectorInput.class.isAssignableFrom(assetInput.getClass())) - ConnectorValidationUtils.check((ConnectorInput) assetInput); + exceptions.addAll(ConnectorValidationUtils.check((ConnectorInput) assetInput)); else if (MeasurementUnitInput.class.isAssignableFrom(assetInput.getClass())) - MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput); + exceptions.add(MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput)); else if (SystemParticipantInput.class.isAssignableFrom(assetInput.getClass())) - SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput); + exceptions.addAll( + SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput)); else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) - ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput); - else throw checkNotImplementedException(assetInput); + exceptions.addAll(ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput)); + else { + exceptions.add( + new Failure<>( + new FailedValidationException( + buildNotImplementedException(assetInput).getMessage()))); + } + + return exceptions; } /** @@ -125,39 +172,97 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) * the checking task, based on the class of the given object. * * @param assetTypeInput AssetTypeInput to check - * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in + * @return a list of try objects either containing a {@link ValidationException} or an empty + * Success */ - private static void checkAssetType(AssetTypeInput assetTypeInput) { - checkNonNull(assetTypeInput, "an asset type"); - if (assetTypeInput.getUuid() == null) - throw new InvalidEntityException("No UUID assigned", assetTypeInput); - if (assetTypeInput.getId() == null) - throw new InvalidEntityException("No ID assigned", assetTypeInput); + private static List> checkAssetType( + AssetTypeInput assetTypeInput) { + Try isNull = checkNonNull(assetTypeInput, "an asset type"); + + if (isNull.isFailure()) { + return List.of(isNull); + } + + List> exceptions = new ArrayList<>(); + + exceptions.add( + Try.ofVoid( + assetTypeInput.getUuid() == null, + () -> new InvalidEntityException("No UUID assigned", assetTypeInput))); + exceptions.add( + Try.ofVoid( + assetTypeInput.getId() == null, + () -> new InvalidEntityException("No ID assigned", assetTypeInput))); // Further checks for subclasses if (LineTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput); + exceptions.addAll(ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput)); else if (Transformer2WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput); + exceptions.addAll( + ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput)); else if (Transformer3WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput); + exceptions.addAll( + ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput)); else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput); + exceptions.addAll( + SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput)); else { - throw checkNotImplementedException(assetTypeInput); + exceptions.add( + new Failure<>( + new FailedValidationException( + buildNotImplementedException(assetTypeInput).getMessage()))); } + + return exceptions; + } + + /** + * Checks the validity of the ids for a given set of {@link AssetInput}. + * + * @param inputs a set of asset inputs + * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty + * Success + */ + protected static List> checkIds( + Set inputs) { + List ids = new ArrayList<>(); + List> exceptions = new ArrayList<>(); + + inputs.forEach( + input -> { + String id = input.getId(); + if (!ids.contains(id)) { + ids.add(id); + } else { + exceptions.add( + new Failure<>( + new UnsafeEntityException( + "There is already an entity with the id " + id, input))); + } + }); + + return exceptions; } /** - * Checks, if the given object is null. If so, an {@link InvalidEntityException} is thrown. + * Checks, if the given object is null. If so, an {@link InvalidEntityException} wrapped in a + * {@link Failure} is returned. * * @param obj Object to check * @param expectedDescription Further description, of what has been expected. + * @return either an {@link InvalidEntityException} wrapped in a {@link Failure} or an empty + * {@link Success} */ - protected static void checkNonNull(Object obj, String expectedDescription) { - if (obj == null) - throw new InvalidEntityException( - "Expected " + expectedDescription + ", but got nothing. :-(", new NullPointerException()); + protected static Try checkNonNull( + Object obj, String expectedDescription) { + return Try.ofVoid( + obj == null, + () -> + new InvalidEntityException( + "Validation not possible because received object was null. Expected " + + expectedDescription + + ", but got nothing. :-(", + new NullPointerException())); } /** @@ -167,7 +272,8 @@ protected static void checkNonNull(Object obj, String expectedDescription) { * @param quantities Array of quantities to check * @param entity Unique entity holding the malformed quantities */ - protected static void detectNegativeQuantities(Quantity[] quantities, UniqueEntity entity) { + protected static void detectNegativeQuantities(Quantity[] quantities, UniqueEntity entity) + throws InvalidEntityException { Predicate> predicate = quantity -> quantity.getValue().doubleValue() < 0d; detectMalformedQuantities( quantities, entity, predicate, "The following quantities have to be zero or positive"); @@ -181,7 +287,7 @@ protected static void detectNegativeQuantities(Quantity[] quantities, UniqueE * @param entity Unique entity holding the malformed quantities */ protected static void detectZeroOrNegativeQuantities( - Quantity[] quantities, UniqueEntity entity) { + Quantity[] quantities, UniqueEntity entity) throws InvalidEntityException { Predicate> predicate = quantity -> quantity.getValue().doubleValue() <= 0d; detectMalformedQuantities( quantities, entity, predicate, "The following quantities have to be positive"); @@ -192,7 +298,8 @@ protected static void detectZeroOrNegativeQuantities( * @param quantities Array of quantities to check * @param entity Unique entity holding the malformed quantities */ - protected static void detectPositiveQuantities(Quantity[] quantities, UniqueEntity entity) { + protected static void detectPositiveQuantities(Quantity[] quantities, UniqueEntity entity) + throws InvalidEntityException { Predicate> predicate = quantity -> quantity.getValue().doubleValue() > 0d; detectMalformedQuantities( quantities, entity, predicate, "The following quantities have to be negative"); @@ -208,7 +315,8 @@ protected static void detectPositiveQuantities(Quantity[] quantities, UniqueE * @param msg Message prefix to use for the exception message: [msg]: [malformedQuantities] */ protected static void detectMalformedQuantities( - Quantity[] quantities, UniqueEntity entity, Predicate> predicate, String msg) { + Quantity[] quantities, UniqueEntity entity, Predicate> predicate, String msg) + throws InvalidEntityException { String malformedQuantities = Arrays.stream(quantities) .filter(predicate) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/LineGraphicInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/LineGraphicInputFactoryTest.groovy index 235a5e277..047237f7b 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/LineGraphicInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/LineGraphicInputFactoryTest.groovy @@ -45,8 +45,8 @@ class LineGraphicInputFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert path == getGeometry(parameter["path"]) assert graphicLayer == parameter["graphiclayer"] @@ -71,8 +71,8 @@ class LineGraphicInputFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert path == GridAndGeoUtils.buildSafeLineString(getGeometry(parameter["path"]) as LineString) } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/NodeGraphicInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/NodeGraphicInputFactoryTest.groovy index 0eb4502bc..b6aac3179 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/NodeGraphicInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/graphics/NodeGraphicInputFactoryTest.groovy @@ -46,8 +46,8 @@ class NodeGraphicInputFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert point == getGeometry(parameter["point"]) assert path == getGeometry(parameter["path"]) @@ -75,8 +75,8 @@ class NodeGraphicInputFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert path == GridAndGeoUtils.buildSafeLineString(getGeometry(parameter["path"]) as LineString) } where: diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy index 8be1628c1..424ad10ec 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy @@ -45,8 +45,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == operatorInput @@ -71,8 +71,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == operatorInput @@ -104,8 +104,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -131,8 +131,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert !operationTime.startDate.present assert operationTime.endDate.present @@ -159,8 +159,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -185,8 +185,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED @@ -209,8 +209,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -235,8 +235,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert !operationTime.startDate.present assert operationTime.endDate.present @@ -262,8 +262,8 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -289,7 +289,7 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe then: input.failure - input.exception().cause.message == + input.exception.get().cause.message == "The provided fields [operatesfrom, operatesuntil, uuid] with data \n" + "{operatesfrom -> 2019-01-01T00:00:00+01:00[Europe/Berlin],\n" + "operatesuntil -> 2019-12-31T00:00:00+01:00[Europe/Berlin],\n" + @@ -307,7 +307,7 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe } @Override - UniqueEntityBuilder copy() { + AssetInputCopyBuilder copy() { throw new NotImplementedException( "Copying of " + this.getClass().simpleName + " entities is not supported yet!") } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/CylindricalStorageInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/CylindricalStorageInputFactoryTest.groovy index a83225f58..cf75e1188 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/CylindricalStorageInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/CylindricalStorageInputFactoryTest.groovy @@ -45,8 +45,8 @@ class CylindricalStorageInputFactoryTest extends Specification implements Facto then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/LineInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/LineInputFactoryTest.groovy index c30fbe0a9..067353976 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/LineInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/LineInputFactoryTest.groovy @@ -62,8 +62,8 @@ class LineInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -113,8 +113,8 @@ class LineInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -164,8 +164,8 @@ class LineInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert geoPosition == GridAndGeoUtils.buildSafeLineString(getGeometry(parameter["geoposition"]) as LineString) } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/MeasurementUnitInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/MeasurementUnitInputFactoryTest.groovy index c588255a6..d1c669d2c 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/MeasurementUnitInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/MeasurementUnitInputFactoryTest.groovy @@ -43,8 +43,8 @@ class MeasurementUnitInputFactoryTest extends Specification implements FactoryTe then: input.success - input.data().getClass() == inputClass - ((MeasurementUnitInput) input.data()).with { + input.data.get().getClass() == inputClass + ((MeasurementUnitInput) input.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/NodeInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/NodeInputFactoryTest.groovy index 04223ecb9..f9f28cafe 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/NodeInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/NodeInputFactoryTest.groovy @@ -51,8 +51,8 @@ class NodeInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - ((NodeInput) input.data()).with { + input.data.get().getClass() == inputClass + ((NodeInput) input.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/OperatorInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/OperatorInputFactoryTest.groovy index 2cdf3c0e0..9a85edab5 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/OperatorInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/OperatorInputFactoryTest.groovy @@ -37,8 +37,8 @@ class OperatorInputFactoryTest extends Specification { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/SwitchInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/SwitchInputFactoryTest.groovy index 8a84c68fa..9c862e663 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/SwitchInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/SwitchInputFactoryTest.groovy @@ -45,8 +45,8 @@ class SwitchInputFactoryTest extends Specification implements FactoryTestHelper then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalBusInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalBusInputFactoryTest.groovy index d639fdc9e..9ef17d5d4 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalBusInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalBusInputFactoryTest.groovy @@ -41,8 +41,8 @@ class ThermalBusInputFactoryTest extends Specification implements FactoryTestHel then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalHouseInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalHouseInputFactoryTest.groovy index 0e6546626..82c0e7843 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalHouseInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/ThermalHouseInputFactoryTest.groovy @@ -45,8 +45,8 @@ class ThermalHouseInputFactoryTest extends Specification implements FactoryTestH then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer2WInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer2WInputFactoryTest.groovy index e99acca8e..260f1bedd 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer2WInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer2WInputFactoryTest.groovy @@ -49,8 +49,8 @@ class Transformer2WInputFactoryTest extends Specification implements FactoryTest then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer3WInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer3WInputFactoryTest.groovy index a2a73912c..5a1d7b9c0 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer3WInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/Transformer3WInputFactoryTest.groovy @@ -46,8 +46,8 @@ class Transformer3WInputFactoryTest extends Specification implements FactoryTes then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/BmInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/BmInputFactoryTest.groovy index 75461033a..04d9e40b7 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/BmInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/BmInputFactoryTest.groovy @@ -56,8 +56,8 @@ class BmInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/ChpInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/ChpInputFactoryTest.groovy index 537e63a84..373da8d5b 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/ChpInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/ChpInputFactoryTest.groovy @@ -57,8 +57,8 @@ class ChpInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EmInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EmInputFactoryTest.groovy index ea130b6de..ba8ae0d84 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EmInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EmInputFactoryTest.groovy @@ -54,8 +54,8 @@ class EmInputFactoryTest extends Specification { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -99,8 +99,8 @@ class EmInputFactoryTest extends Specification { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -139,8 +139,8 @@ class EmInputFactoryTest extends Specification { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.empty assert operationTime.endDate.empty diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvInputFactoryTest.groovy index 9ce6086ca..2d8b5c0d0 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvInputFactoryTest.groovy @@ -52,8 +52,8 @@ class EvInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvcsInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvcsInputFactoryTest.groovy index 4142a6305..4f3412e23 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvcsInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/EvcsInputFactoryTest.groovy @@ -62,8 +62,8 @@ class EvcsInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -111,7 +111,7 @@ class EvcsInputFactoryTest extends Specification implements FactoryTestHelper { then: input.failure - input.exception().cause.message == "Exception while trying to parse field \"type\" with supposed int value \"-- invalid --\"" + input.exception.get().cause.message == "Exception while trying to parse field \"type\" with supposed int value \"-- invalid --\"" } def "A EvcsInputFactory should fail when passing an invalid EvcsLocationType"() { @@ -139,6 +139,6 @@ class EvcsInputFactoryTest extends Specification implements FactoryTestHelper { then: input.failure - input.exception().cause.message == "Exception while trying to parse field \"locationtype\" with supposed int value \"-- invalid --\"" + input.exception.get().cause.message == "Exception while trying to parse field \"locationtype\" with supposed int value \"-- invalid --\"" } } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/FixedFeedInInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/FixedFeedInInputFactoryTest.groovy index 98404d821..fa7184b4b 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/FixedFeedInInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/FixedFeedInInputFactoryTest.groovy @@ -53,8 +53,8 @@ class FixedFeedInInputFactoryTest extends Specification implements FactoryTestHe then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) @@ -90,7 +90,7 @@ class FixedFeedInInputFactoryTest extends Specification implements FactoryTestHe then: input.failure - input.exception().cause.message == "The provided fields [cosphirated, id, srated, uuid] with data \n" + + input.exception.get().cause.message == "The provided fields [cosphirated, id, srated, uuid] with data \n" + "{cosphirated -> 4,\n" + "id -> TestID,\n" + "srated -> 3,\n" + diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/HpInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/HpInputFactoryTest.groovy index e82a0e04f..47316ab03 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/HpInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/HpInputFactoryTest.groovy @@ -54,8 +54,8 @@ class HpInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/LoadInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/LoadInputFactoryTest.groovy index 40c177453..cede6ac6b 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/LoadInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/LoadInputFactoryTest.groovy @@ -56,8 +56,8 @@ class LoadInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime == OperationTime.notLimited() assert operator == OperatorInput.NO_OPERATOR_ASSIGNED diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/PvInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/PvInputFactoryTest.groovy index 431765355..4fffbba20 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/PvInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/PvInputFactoryTest.groovy @@ -61,8 +61,8 @@ class PvInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/StorageInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/StorageInputFactoryTest.groovy index 6522aa7b2..da40b333d 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/StorageInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/StorageInputFactoryTest.groovy @@ -52,8 +52,8 @@ class StorageInputFactoryTest extends Specification implements FactoryTestHelper then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert operationTime.startDate.present assert operationTime.startDate.get() == ZonedDateTime.parse(parameter["operatesfrom"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/WecInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/WecInputFactoryTest.groovy index 88076ca7a..cd432e1f5 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/WecInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/input/participant/WecInputFactoryTest.groovy @@ -53,8 +53,8 @@ class WecInputFactoryTest extends Specification implements FactoryTestHelper { then: input.success - input.data().getClass() == inputClass - input.data().with { + input.data.get().getClass() == inputClass + input.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert !operationTime.startDate.present assert operationTime.endDate.present diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/ConnectorResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/ConnectorResultFactoryTest.groovy index caa2a74be..d22c8abac 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/ConnectorResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/ConnectorResultFactoryTest.groovy @@ -57,8 +57,8 @@ class ConnectorResultFactoryTest extends Specification implements FactoryTestHel then: result.success - result.data().getClass() == resultingModelClass - ((ConnectorResult) result.data()).with { + result.data.get().getClass() == resultingModelClass + ((ConnectorResult) result.data.get()).with { assert time == TIME_UTIL.toZonedDateTime(parameter["time"]) assert inputModel == UUID.fromString(parameter["inputModel"]) assert iAAng == getQuant(parameter["iaang"], StandardUnits.ELECTRIC_CURRENT_ANGLE) @@ -67,12 +67,12 @@ class ConnectorResultFactoryTest extends Specification implements FactoryTestHel assert iBMag == getQuant(parameter["ibmag"], StandardUnits.ELECTRIC_CURRENT_MAGNITUDE) } - if (result.data().getClass() == Transformer2WResult) { - assert ((Transformer2WResult) result.data()).tapPos == Integer.parseInt(parameter["tappos"]) + if (result.data.get().getClass() == Transformer2WResult) { + assert ((Transformer2WResult) result.data.get()).tapPos == Integer.parseInt(parameter["tappos"]) } - if (result.data().getClass() == Transformer3WResult) { - Transformer3WResult transformer3WResult = ((Transformer3WResult) result.data()) + if (result.data.get().getClass() == Transformer3WResult) { + Transformer3WResult transformer3WResult = ((Transformer3WResult) result.data.get()) assert transformer3WResult.tapPos == Integer.parseInt(parameter["tappos"]) assert transformer3WResult.iCAng == getQuant(parameter["icang"], StandardUnits.ELECTRIC_CURRENT_ANGLE) assert transformer3WResult.iCMag == getQuant(parameter["icmag"], StandardUnits.ELECTRIC_CURRENT_MAGNITUDE) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/FlexOptionsResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/FlexOptionsResultFactoryTest.groovy index bf5399dab..c46eabaea 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/FlexOptionsResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/FlexOptionsResultFactoryTest.groovy @@ -40,8 +40,8 @@ class FlexOptionsResultFactoryTest extends Specification implements FactoryTestH then: result.success - result.data().getClass() == FlexOptionsResult - ((FlexOptionsResult) result.data()).with { + result.data.get().getClass() == FlexOptionsResult + ((FlexOptionsResult) result.data.get()).with { assert pRef == getQuant(parameter["pref"], StandardUnits.ACTIVE_POWER_RESULT) assert pMin == getQuant(parameter["pmin"], StandardUnits.ACTIVE_POWER_RESULT) assert pMax == getQuant(parameter["pmax"], StandardUnits.ACTIVE_POWER_RESULT) @@ -65,7 +65,7 @@ class FlexOptionsResultFactoryTest extends Specification implements FactoryTestH then: input.failure - input.exception().cause.message == "The provided fields [inputModel, pmin, pref, time] with data \n" + + input.exception.get().cause.message == "The provided fields [inputModel, pmin, pref, time] with data \n" + "{inputModel -> 91ec3bcf-1897-4d38-af67-0bf7c9fa73c7,\n" + "pmin -> -1,\n" + "pref -> 2,\n" + diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/NodeResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/NodeResultFactoryTest.groovy index dbabd1376..9dbc4e294 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/NodeResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/NodeResultFactoryTest.groovy @@ -39,8 +39,8 @@ class NodeResultFactoryTest extends Specification implements FactoryTestHelper { then: result.success - result.data().getClass() == NodeResult - ((NodeResult) result.data()).with { + result.data.get().getClass() == NodeResult + ((NodeResult) result.data.get()).with { assert vMag == getQuant(parameter["vmag"], StandardUnits.VOLTAGE_MAGNITUDE) assert vAng == getQuant(parameter["vang"], StandardUnits.VOLTAGE_ANGLE) assert time == TIME_UTIL.toZonedDateTime(parameter["time"]) @@ -62,7 +62,7 @@ class NodeResultFactoryTest extends Specification implements FactoryTestHelper { then: input.failure - input.exception().cause.message == "The provided fields [inputModel, time, vmag] with data \n" + + input.exception.get().cause.message == "The provided fields [inputModel, time, vmag] with data \n" + "{inputModel -> 91ec3bcf-1897-4d38-af67-0bf7c9fa73c7,\n" + "time -> 2020-01-30 17:26:44,\n" + "vmag -> 2} are invalid for instance of NodeResult. \n" + diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/SwitchResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/SwitchResultFactoryTest.groovy index ddb9f64ba..ff05a4ff8 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/SwitchResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/SwitchResultFactoryTest.groovy @@ -39,8 +39,8 @@ class SwitchResultFactoryTest extends Specification implements FactoryTestHelper then: result.success - result.data().getClass() == SwitchResult - ((SwitchResult) result.data()).with { + result.data.get().getClass() == SwitchResult + ((SwitchResult) result.data.get()).with { assert time == TIME_UTIL.toZonedDateTime(parameter["time"]) assert inputModel == UUID.fromString(parameter["inputModel"]) assert closed == Boolean.parseBoolean(parameter["closed"]) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/SystemParticipantResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/SystemParticipantResultFactoryTest.groovy index 758c1a61c..5ca875cda 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/SystemParticipantResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/SystemParticipantResultFactoryTest.groovy @@ -60,8 +60,8 @@ class SystemParticipantResultFactoryTest extends Specification implements Factor then: result.success - result.data().getClass() == resultingModelClass - ((SystemParticipantResult) result.data()).with { + result.data.get().getClass() == resultingModelClass + ((SystemParticipantResult) result.data.get()).with { assert p == getQuant(parameter["p"], StandardUnits.ACTIVE_POWER_RESULT) assert q == getQuant(parameter["q"], StandardUnits.REACTIVE_POWER_RESULT) assert time == TIME_UTIL.toZonedDateTime(parameter["time"]) @@ -69,19 +69,19 @@ class SystemParticipantResultFactoryTest extends Specification implements Factor } if (modelClass == EvResult) { - assert (((EvResult) result.data()).soc == getQuant(parameter["soc"], Units.PERCENT)) + assert (((EvResult) result.data.get()).soc == getQuant(parameter["soc"], Units.PERCENT)) } if (modelClass == StorageResult) { - assert (((StorageResult) result.data()).soc == getQuant(parameter["soc"], Units.PERCENT)) + assert (((StorageResult) result.data.get()).soc == getQuant(parameter["soc"], Units.PERCENT)) } if (modelClass == HpResult) { - assert(((HpResult) result.data()).getqDot() == getQuant(parameter["qDot"], StandardUnits.Q_DOT_RESULT)) + assert(((HpResult) result.data.get()).getqDot() == getQuant(parameter["qDot"], StandardUnits.Q_DOT_RESULT)) } if (modelClass == ChpResult) { - assert(((ChpResult) result.data()).getqDot() == getQuant(parameter["qDot"], StandardUnits.Q_DOT_RESULT)) + assert(((ChpResult) result.data.get()).getqDot() == getQuant(parameter["qDot"], StandardUnits.Q_DOT_RESULT)) } where: @@ -114,8 +114,8 @@ class SystemParticipantResultFactoryTest extends Specification implements Factor then: result.success - result.data().getClass() == StorageResult - ((StorageResult) result.data()).with { + result.data.get().getClass() == StorageResult + ((StorageResult) result.data.get()).with { assert p == getQuant(parameter["p"], StandardUnits.ACTIVE_POWER_RESULT) assert q == getQuant(parameter["q"], StandardUnits.REACTIVE_POWER_RESULT) assert soc == getQuant(parameter["soc"], Units.PERCENT) @@ -137,7 +137,7 @@ class SystemParticipantResultFactoryTest extends Specification implements Factor then: result.failure - result.exception().cause.message == "The provided fields [inputModel, q, time] with data \n" + + result.exception.get().cause.message == "The provided fields [inputModel, q, time] with data \n" + "{inputModel -> 91ec3bcf-1777-4d38-af67-0bf7c9fa73c7,\n" + "q -> 2,\n" + "time -> 2020-01-30 17:26:44} are invalid for instance of WecResult. \n" + diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/result/ThermalResultFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/result/ThermalResultFactoryTest.groovy index 811bf5202..3e9456fe2 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/result/ThermalResultFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/result/ThermalResultFactoryTest.groovy @@ -45,8 +45,8 @@ class ThermalResultFactoryTest extends Specification implements FactoryTestHelpe then: result.success - result.data().getClass() == CylindricalStorageResult - ((CylindricalStorageResult) result.data()).with { + result.data.get().getClass() == CylindricalStorageResult + ((CylindricalStorageResult) result.data.get()).with { assert time == TIME_UTIL.toZonedDateTime(parameter.get("time")) assert inputModel == UUID.fromString(parameter.get("inputModel")) assert qDot == Quantities.getQuantity(Double.parseDouble(parameter.get("qDot")), StandardUnits.HEAT_DEMAND) @@ -69,8 +69,8 @@ class ThermalResultFactoryTest extends Specification implements FactoryTestHelpe then: result.success - result.data().getClass() == ThermalHouseResult - ((ThermalHouseResult) result.data()).with { + result.data.get().getClass() == ThermalHouseResult + ((ThermalHouseResult) result.data.get()).with { assert time == TIME_UTIL.toZonedDateTime(parameter.get("time")) assert inputModel == UUID.fromString(parameter.get("inputModel")) assert qDot == Quantities.getQuantity(Double.parseDouble(parameter.get("qDot")), StandardUnits.HEAT_DEMAND) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/CosmoIdCoordinateFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/CosmoIdCoordinateFactoryTest.groovy index 3ab508f2c..117999ce4 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/CosmoIdCoordinateFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/CosmoIdCoordinateFactoryTest.groovy @@ -68,7 +68,7 @@ class CosmoIdCoordinateFactoryTest extends Specification { then: actual.failure - actual.exception().cause.message.startsWith("The provided fields [id, latrot, longrot, tid] with data \n{id -> 106580,\nlatrot" + + actual.exception.get().cause.message.startsWith("The provided fields [id, latrot, longrot, tid] with data \n{id -> 106580,\nlatrot" + " -> -10,\nlongrot -> -6.8125,\ntid -> 1} are invalid for instance of Pair.") } @@ -91,7 +91,7 @@ class CosmoIdCoordinateFactoryTest extends Specification { then: actual.success - actual.data().with { + actual.data.get().with { assert it.key == expectedPair.key assert it.value.equalsExact(expectedPair.value, 1E-6) } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/IconIdCoordinateFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/IconIdCoordinateFactoryTest.groovy index 23af78bf0..b40b44387 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/IconIdCoordinateFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/timeseries/IconIdCoordinateFactoryTest.groovy @@ -58,7 +58,7 @@ class IconIdCoordinateFactoryTest extends Specification { then: actual.failure - actual.exception().cause.message.startsWith("The provided fields [coordinatetype, id, latitude] with data \n{coordinatetype -> " + + actual.exception.get().cause.message.startsWith("The provided fields [coordinatetype, id, latitude] with data \n{coordinatetype -> " + "ICON,\nid -> 477295,\nlatitude -> 52.312} are invalid for instance of Pair. ") } @@ -77,7 +77,7 @@ class IconIdCoordinateFactoryTest extends Specification { then: actual.success - actual.data().with { + actual.data.get().with { assert it.key == expectedPair.key assert it.value.equalsExact(expectedPair.value, 1E-6) } diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/LineTypeInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/LineTypeInputFactoryTest.groovy index 4c47f1f19..0248bf204 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/LineTypeInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/LineTypeInputFactoryTest.groovy @@ -44,8 +44,8 @@ class LineTypeInputFactoryTest extends Specification implements FactoryTestHelpe then: typeInput.success - typeInput.data().getClass() == typeInputClass - typeInput.data().with { + typeInput.data.get().getClass() == typeInputClass + typeInput.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert b == getQuant(parameter["b"], StandardUnits.SUSCEPTANCE_PER_LENGTH) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/SystemParticipantTypeInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/SystemParticipantTypeInputFactoryTest.groovy index 81a9b74db..b5f40c2ac 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/SystemParticipantTypeInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/SystemParticipantTypeInputFactoryTest.groovy @@ -60,9 +60,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((EvTypeInput) typeInput.data()).with { + ((EvTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -95,9 +95,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((HpTypeInput) typeInput.data()).with { + ((HpTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -129,9 +129,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((BmTypeInput) typeInput.data()).with { + ((BmTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -167,9 +167,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((WecTypeInput) typeInput.data()).with { + ((WecTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -214,9 +214,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((ChpTypeInput) typeInput.data()).with { + ((ChpTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -257,9 +257,9 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - ((StorageTypeInput) typeInput.data()).with { + ((StorageTypeInput) typeInput.data.get()).with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert capex == getQuant(parameter["capex"], StandardUnits.CAPEX) @@ -300,7 +300,7 @@ class SystemParticipantTypeInputFactoryTest extends Specification implements Fac then: input.failure - input.exception().cause.message == "The provided fields [capex, cosPhiRated, dod, estorage, eta, id, lifetime, opex, pmax, pmin, srated, uuid] with data \n" + + input.exception.get().cause.message == "The provided fields [capex, cosPhiRated, dod, estorage, eta, id, lifetime, opex, pmax, pmin, srated, uuid] with data \n" + "{capex -> 3,\n" + "cosPhiRated -> 6,\n" + "dod -> 10,\n" + diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer2WTypeInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer2WTypeInputFactoryTest.groovy index 0561bf3d2..848de5662 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer2WTypeInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer2WTypeInputFactoryTest.groovy @@ -51,9 +51,9 @@ class Transformer2WTypeInputFactoryTest extends Specification implements Factory then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - typeInput.data().with { + typeInput.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert rSc == getQuant(parameter["rsc"], StandardUnits.RESISTANCE) diff --git a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer3WTypeInputFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer3WTypeInputFactoryTest.groovy index 039b9eeeb..d01862624 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer3WTypeInputFactoryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/factory/typeinput/Transformer3WTypeInputFactoryTest.groovy @@ -57,9 +57,9 @@ class Transformer3WTypeInputFactoryTest extends Specification implements Factory then: typeInput.success - typeInput.data().getClass() == typeInputClass + typeInput.data.get().getClass() == typeInputClass - typeInput.data().with { + typeInput.data.get().with { assert uuid == UUID.fromString(parameter["uuid"]) assert id == parameter["id"] assert sRatedA == getQuant(parameter["srateda"], StandardUnits.S_RATED) diff --git a/src/test/groovy/edu/ie3/datamodel/io/source/EntitySourceTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/source/EntitySourceTest.groovy index 48247e0bb..b2881dbdf 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/source/EntitySourceTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/source/EntitySourceTest.groovy @@ -101,6 +101,6 @@ class EntitySourceTest extends Specification { then: noExceptionThrown() // no NPE should be thrown thermalBusInputEntity.success - thermalBusInputEntity.data().operator.id == OperatorInput.NO_OPERATOR_ASSIGNED.id // operator id should be set accordingly + thermalBusInputEntity.data.get().operator.id == OperatorInput.NO_OPERATOR_ASSIGNED.id // operator id should be set accordingly } } diff --git a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvGraphicSourceTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvGraphicSourceTest.groovy index 5376773bb..38f15b346 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvGraphicSourceTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvGraphicSourceTest.groovy @@ -63,7 +63,7 @@ class CsvGraphicSourceTest extends Specification implements CsvTestDataMeta { graphicElements.failure graphicElements.data == Optional.empty() - Exception ex = graphicElements.exception() + Exception ex = graphicElements.exception.get() ex.class == SourceException ex.message.startsWith("edu.ie3.datamodel.exceptions.FailureException: 2 exception(s) occurred within \"LineInput\" data, one is: edu.ie3.datamodel.exceptions.FactoryException: edu.ie3.datamodel.exceptions.SourceException: Failure due to: Skipping LineInput with uuid") } @@ -135,7 +135,7 @@ class CsvGraphicSourceTest extends Specification implements CsvTestDataMeta { res.success == isPresent if (isPresent) { - def value = res.data() + def value = res.data.get() assert value == new NodeGraphicInputEntityData([ "uuid" : "09aec636-791b-45aa-b981-b14edf171c4c", @@ -171,7 +171,7 @@ class CsvGraphicSourceTest extends Specification implements CsvTestDataMeta { res.success == isPresent if (isPresent) { - def value = res.data() + def value = res.data.get() assert value == new LineGraphicInputEntityData(["uuid" : "ece86139-3238-4a35-9361-457ecb4258b0", "graphic_layer": "main", diff --git a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy index c43886fcc..5049b4bb7 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy @@ -65,7 +65,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" connectorDataOption.success - connectorDataOption.data().with { + connectorDataOption.data.get().with { assert fieldsToValues == expectedFieldsToAttributes assert targetClass == SwitchInput assert nodeA == rgtd.nodeA @@ -171,11 +171,11 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } - actualSet.stream().map { it.data() }.toList().containsAll(expectedSet) + actualSet.stream().map { it.data.get() }.toList().containsAll(expectedSet) } def "The CsvRawGridSource is able to add a type to untyped ConnectorInputEntityData correctly"() { @@ -264,7 +264,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actual.success - actual.data() == expectedTypedEntityData + actual.data.get() == expectedTypedEntityData } def "The CsvRawGridSource is able to identify ConnectorInputEntityData data with non matching type requirements correctly"() { @@ -371,11 +371,11 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } actualSet.stream().map { - it.data() + it.data.get() }.toList().containsAll(expectedSet) } @@ -424,7 +424,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actual.success - actual.data() == expected + actual.data.get() == expected } def "The CsvRawGridSource is NOT able to add the third node for a three winding transformer, if it is not available"() { @@ -497,36 +497,35 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { rgtd.nodeC ] - def expectedSet = [ - new Transformer3WInputEntityData([ - "uuid" : "cc327469-7d56-472b-a0df-edbb64f90e8f", - "id" : "3w_test", - "operator" : "8f9682df-0744-4b58-a122-f0dc730f6510", - "operatesFrom" : "2020-03-24 15:11:31", - "operatesUntil" : "2020-03-24 15:11:31", - "parallelDevices" : "1", - "tapPos" : "0", - "autoTap" : "true" - ], - Transformer3WInput, - rgtd.nodeA, - rgtd.nodeB, - rgtd.nodeC, - rgtd.transformerTypeAtoBtoC), - null - ] + def expected = new Transformer3WInputEntityData([ + "uuid" : "cc327469-7d56-472b-a0df-edbb64f90e8f", + "id" : "3w_test", + "operator" : "8f9682df-0744-4b58-a122-f0dc730f6510", + "operatesFrom" : "2020-03-24 15:11:31", + "operatesUntil" : "2020-03-24 15:11:31", + "parallelDevices" : "1", + "tapPos" : "0", + "autoTap" : "true" + ], + Transformer3WInput, + rgtd.nodeA, + rgtd.nodeB, + rgtd.nodeC, + rgtd.transformerTypeAtoBtoC) when: "the sources tries to add nodes" def actualSet = source.buildTransformer3WEntityData(inputStream, availableNodes).collect(Collectors.toSet()) + def successes = actualSet.stream().filter { + it.success + }.toList() + def failures = actualSet.stream().filter { + it.failure + }.toList() then: "everything is fine" - actualSet.size() == expectedSet.size() - actualSet.forEach { - it.success - } - actualSet.stream().map { - it.data() - }.toList().containsAll(expectedSet) + actualSet.size() == 2 + successes.get(0).data.get() == expected + failures.get(0).exception.get().class == SourceException } def "The CsvRawGridSource is able to load all nodes from file"() { diff --git a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvSystemParticipantSourceTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvSystemParticipantSourceTest.groovy index 3bc2e0aef..43b2764a2 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvSystemParticipantSourceTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvSystemParticipantSourceTest.groovy @@ -90,7 +90,7 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat systemParticipants.failure systemParticipants.data == Optional.empty() - Exception ex = systemParticipants.exception() + Exception ex = systemParticipants.exception.get() ex.class == SystemParticipantsException ex.message.startsWith("11 error(s) occurred while initializing system participants. " + "edu.ie3.datamodel.exceptions.FailureException: 1 exception(s) occurred within \"FixedFeedInInput\" data, one is: " + @@ -199,10 +199,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def heatPumps = Try.of(() -> csvSystemParticipantSource.getHeatPumps(nodes as Set, operators as Set, types as Set, thermalBuses as Set), SourceException) if (heatPumps.success) { - heatPumps.data().size() == resultingSize - heatPumps.data() == resultingSet as Set + heatPumps.data.get().size() == resultingSize + heatPumps.data.get() == resultingSet as Set } else { - heatPumps.exception().class == SourceException + heatPumps.exception.get().class == SourceException } where: @@ -229,10 +229,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def chpUnits = Try.of(() -> csvSystemParticipantSource.getChpPlants(nodes as Set, operators as Set, types as Set, thermalBuses as Set, thermalStorages as Set), SourceException) if (chpUnits.success) { - chpUnits.data().size() == resultingSize - chpUnits.data() == resultingSet as Set + chpUnits.data.get().size() == resultingSize + chpUnits.data.get() == resultingSet as Set } else { - chpUnits.exception().class == SourceException + chpUnits.exception.get().class == SourceException } where: @@ -263,10 +263,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getEvs(nodes as Set, operators as Set, types as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -292,10 +292,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getWecPlants(nodes as Set, operators as Set, types as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -321,10 +321,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getStorages(nodes as Set, operators as Set, types as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -350,10 +350,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getBmPlants(nodes as Set, operators as Set, types as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -379,10 +379,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getEvCS(nodes as Set, operators as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -407,10 +407,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getLoads(nodes as Set, operators as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -435,10 +435,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getPvPlants(nodes as Set, operators as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -463,10 +463,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getFixedFeedIns(nodes as Set, operators as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: @@ -495,10 +495,10 @@ class CsvSystemParticipantSourceTest extends Specification implements CsvTestDat def sysParts = Try.of(() -> csvSystemParticipantSource.getEmSystems(nodes as Set, operators as Set), SourceException) if (sysParts.success) { - sysParts.data().size() == resultingSize - sysParts.data() == resultingSet as Set + sysParts.data.get().size() == resultingSize + sysParts.data.get() == resultingSet as Set } else { - sysParts.exception().class == SourceException + sysParts.exception.get().class == SourceException } where: diff --git a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesSourceTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesSourceTest.groovy index 177b3c15e..5eaaa914e 100644 --- a/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesSourceTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesSourceTest.groovy @@ -47,7 +47,7 @@ class CsvTimeSeriesSourceTest extends Specification implements CsvTestDataMeta { then: actual.success - actual.data() == expected + actual.data.get() == expected } def "The factory method in csv time series source refuses to build time series with unsupported column type"() { diff --git a/src/test/groovy/edu/ie3/datamodel/models/input/graphics/GraphicInputTest.groovy b/src/test/groovy/edu/ie3/datamodel/models/input/graphics/GraphicInputTest.groovy index 07f0672c2..f7225fcbc 100644 --- a/src/test/groovy/edu/ie3/datamodel/models/input/graphics/GraphicInputTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/models/input/graphics/GraphicInputTest.groovy @@ -17,6 +17,11 @@ class GraphicInputTest extends Specification { DummyGraphicObject(UUID uuid, String graphicLayer, LineString path) { super(uuid, graphicLayer, path) } + + @Override + GraphicInputCopyBuilder copy() { + throw new UnsupportedOperationException("This is a dummy class") + } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index 86d545fc4..4a0ff0762 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy @@ -18,7 +18,9 @@ class TryTest extends Specification { then: actual.success - actual.data() == "success" + actual.data.get() == "success" + actual.orThrow == "success" + actual.exception == Optional.empty() } def "A failing method can be applied to a try object"() { @@ -29,8 +31,9 @@ class TryTest extends Specification { then: actual.failure - actual.exception().class == SourceException - actual.exception().message == "Exception thrown." + actual.data == Optional.empty() + actual.exception.get().class == SourceException + actual.exception.get().message == "Exception thrown." } def "A failure is returned if an expected exception type is thrown when using #of()"() { @@ -80,16 +83,6 @@ class TryTest extends Specification { actual.exception.get() == exception } - def "A failure is returned when using Failure#of() with a failure"() { - when: - def exception = new SourceException("source exception") - Try actual = Try.Failure.of(new Try.Failure(exception)) - - then: - actual.failure - actual.exception.get() == exception - } - def "A failure is returned if an expected exception type is thrown when using Try#ofVoid()"() { when: def exception = new SourceException("source exception") @@ -117,13 +110,70 @@ class TryTest extends Specification { cause.message == "source exception" } + def "A Try object can be creates by a boolean and an exception"() { + when: + def ex = new FailureException("failure") + def actual = Try.ofVoid(bool, () -> ex) + + then: + actual.failure == expected + + if (expected) { + actual.exception.get() == ex + } + + where: + bool || expected + true || true + false || false + } + + def "A list of Tries is returned when applying a multiple VoidSupplier to Try#ofVoid()"() { + given: + Try.VoidSupplier one = () -> { + throw new FailureException("failure 1") + } + Try.VoidSupplier two = () -> { + throw new FailureException("failure 2") + } + + when: + List> failures = Try.ofVoid(FailureException, one, two) + + then: + failures.size() == 2 + failures.every { + it.failure + } + } + + def "A TryException is thrown if an unexpected exception type is thrown when using Try#ofVoid() with multiple VoidSuppliers"() { + given: + Try.VoidSupplier one = () -> { + throw new FailureException("failure") + } + Try.VoidSupplier two = () -> { + throw new SourceException("source exception") + } + + when: + Try.ofVoid(FailureException, one, two) + + then: + Exception ex = thrown() + ex.class == TryException + Throwable cause = ex.cause + cause.class == SourceException + cause.message == "source exception" + } + def "A void method can be applied to a try object"() { when: Try actual = Try.ofVoid(() -> null, Exception) then: actual.success - actual.empty + ((Try.Success) actual).empty actual.data.empty } @@ -156,7 +206,6 @@ class TryTest extends Specification { expect: empty.success empty.data == Optional.empty() - empty.empty } def "A scan for exceptions should work as expected when failures are included"() { @@ -173,7 +222,7 @@ class TryTest extends Specification { then: scan.failure - scan.exception().message == "1 exception(s) occurred within \"String\" data, one is: java.lang.Exception: exception" + scan.exception.get().message == "1 exception(s) occurred within \"String\" data, one is: java.lang.Exception: exception" } def "A scan for exceptions should work as expected when no failures are included"() { @@ -189,7 +238,7 @@ class TryTest extends Specification { then: scan.success - scan.data().size() == 3 + scan.data.get().size() == 3 } def "The getOrThrow method should work as expected"() { @@ -205,34 +254,33 @@ class TryTest extends Specification { ex.message == "source exception" } - def "The getOrElse method should work as expected"() { - given: - Try success = new Try.Success<>("success") - Try failure = new Try.Failure<>(new SourceException("exception")) - - when: - String successResult = success.getOrElse("else") - String failureResult = failure.getOrElse("else") - - then: - successResult == "success" - failureResult == "else" - } - def "A Try objects transformation should work as correctly for successes"() { given: Try success = new Try.Success<>("5") + SourceException exc = new SourceException("source exception") when: - Try first = success.transformS(str -> Integer.parseInt(str) ) - Try second = success.transform(str -> Integer.parseInt(str), ex -> new Exception(ex) ) + Try transformS = success.transformS(str -> Integer.parseInt(str) ) + Try map = success.map(str -> Integer.parseInt(str) ) + Try transformF = success.transformF(ex -> new Exception(ex) ) + Try transform = success.transform(str -> Integer.parseInt(str), ex -> new Exception(ex) ) + Try flatMapS = success.flatMap(str -> new Try.Success(Integer.parseInt(str)) ) + Try flatMapF = success.flatMap(str -> new Try.Failure(exc) ) then: - first.success - second.success - - first.data() == 5 - second.data() == 5 + transformS.success + map.success + transformF.success + transform.success + flatMapS.success + flatMapF.failure + + transformS.data.get() == 5 + map.data.get() == 5 + transformF.data.get() == "5" + transform.data.get() == 5 + flatMapS.data.get() == 5 + flatMapF.exception.get() == exc } def "A Try objects transformation should work as correctly for failures"() { @@ -240,15 +288,27 @@ class TryTest extends Specification { Try failure = new Try.Failure<>(new SourceException("")) when: - Try first = failure.transformS(str -> Integer.parseInt(str) ) - Try second = failure.transform(str -> Integer.parseInt(str), ex -> new Exception(ex) ) + Try transformS = failure.transformS(str -> Integer.parseInt(str) ) + Try map = failure.map(str -> Integer.parseInt(str) ) + Try transformF = failure.transformF(ex -> new Exception(ex) ) + Try transform = failure.transform(str -> Integer.parseInt(str), ex -> new Exception(ex) ) + Try flatMapS = failure.flatMap(str -> new Try.Success(Integer.parseInt(str)) ) + Try flatMapF = failure.flatMap(str -> new Try.Failure(new SourceException("not returned")) ) then: - first.failure - second.failure - - first.exception().class == SourceException - second.exception().class == Exception + transformS.failure + map.failure + transformF.failure + transform.failure + flatMapS.failure + flatMapF.failure + + transformS.exception.get().class == SourceException + map.exception.get().class == SourceException + transformF.exception.get().class == Exception + transform.exception.get().class == Exception + flatMapS.exception.get() == failure.get() + flatMapF.exception.get() == failure.get() } def "All exceptions of a collection of try objects should be returned"() { diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy index 2ef09e125..97a2ff4a8 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -6,30 +6,25 @@ package edu.ie3.datamodel.utils.validation import static edu.ie3.datamodel.models.StandardUnits.* -import static edu.ie3.util.quantities.PowerSystemUnits.* +import static tech.units.indriya.unit.Units.METRE +import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.models.input.connector.LineInput import edu.ie3.datamodel.models.input.connector.type.Transformer2WTypeInput import edu.ie3.datamodel.models.input.connector.type.Transformer3WTypeInput import edu.ie3.datamodel.models.input.system.characteristic.OlmCharacteristicInput import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils -import org.locationtech.jts.geom.LineString -import tech.units.indriya.ComparableQuantity - -import javax.measure.quantity.Angle -import javax.measure.quantity.Dimensionless -import javax.measure.quantity.ElectricConductance -import javax.measure.quantity.ElectricPotential -import javax.measure.quantity.ElectricResistance -import javax.measure.quantity.Power - -import edu.ie3.datamodel.exceptions.InvalidEntityException +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import edu.ie3.util.geo.GeoUtils import org.locationtech.jts.geom.Coordinate +import org.locationtech.jts.geom.LineString import spock.lang.Specification +import tech.units.indriya.ComparableQuantity import tech.units.indriya.quantity.Quantities +import javax.measure.quantity.* + class ConnectorValidationUtilsTest extends Specification { def "Instantiating a ConnectorValidationUtil leads to an exception"() { @@ -69,22 +64,20 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkLine() recognizes all potential errors for a line"() { when: - ConnectorValidationUtils.check(invalidLine) + List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidLine || expectedException - GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeG).build() || new InvalidEntityException("LineInput connects the same node, but shouldn't", invalidLine) - GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeF.copy().subnet(5).build()).build() || new InvalidEntityException("LineInput connects different subnets, but shouldn't", invalidLine) - GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeF.copy().voltLvl(GermanVoltageLevelUtils.MV_10KV).build()).build() || new InvalidEntityException("LineInput connects different voltage levels, but shouldn't", invalidLine) - GridTestData.lineFtoG.copy().length(Quantities.getQuantity(0d, METRE)).build() || new InvalidEntityException("The following quantities have to be positive: 0.0 km", invalidLine) - GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeF.copy().geoPosition(testCoordinate).build()).build() || new InvalidEntityException("Coordinates of start and end point do not match coordinates of connected nodes", invalidLine) - GridTestData.lineFtoG.copy().nodeB(GridTestData.nodeG.copy().geoPosition(testCoordinate).build()).build() || new InvalidEntityException("Coordinates of start and end point do not match coordinates of connected nodes", invalidLine) - invalidLineLengthNotMatchingCoordinateDistances || new InvalidEntityException("Line length does not equal calculated distances between points building the line", invalidLine) + invalidLine || expectedSize || expectedException + GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeG).build() || 1 || new InvalidEntityException("LineInput connects the same node, but shouldn't", invalidLine) + GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeF.copy().subnet(5).build()).build() || 1 || new InvalidEntityException("LineInput connects different subnets, but shouldn't", invalidLine) + GridTestData.lineFtoG.copy().nodeA(GridTestData.nodeF.copy().voltLvl(GermanVoltageLevelUtils.MV_10KV).build()).build() || 1 || new InvalidEntityException("LineInput connects different voltage levels, but shouldn't", invalidLine) + GridTestData.lineFtoG.copy().length(Quantities.getQuantity(0d, METRE)).build() || 1 || new InvalidEntityException("The following quantities have to be positive: 0.0 km", invalidLine) } def "Smoke Test: Correct line type throws no exception"() { @@ -113,19 +106,20 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2W recognizes all potential errors for a transformer2W"() { when: - ConnectorValidationUtils.check(invalidTransformer2W) + List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidTransformer2W || expectedException - GridTestData.transformerBtoD.copy().tapPos(100).build() || new InvalidEntityException("Tap position of Transformer2WInput is outside of bounds", invalidTransformer2W) - GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().voltLvl(GermanVoltageLevelUtils.HV).build()).build() || new InvalidEntityException("Transformer2WInput connects the same voltage level, but shouldn't", invalidTransformer2W) - GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().subnet(2).build()).build() || new InvalidEntityException("Transformer2WInput connects the same subnet, but shouldn't", invalidTransformer2W) - GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().voltLvl(GermanVoltageLevelUtils.MV_30KV).build()).build() || new InvalidEntityException("Rated voltages of Transformer2WInput do not equal voltage levels at the nodes", invalidTransformer2W) + invalidTransformer2W || expectedSize || expectedException + GridTestData.transformerBtoD.copy().tapPos(100).build() || 1 || new InvalidEntityException("Tap position of Transformer2WInput is outside of bounds", invalidTransformer2W) + GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().voltLvl(GermanVoltageLevelUtils.HV).build()).build() || 2 || new InvalidEntityException("Transformer2WInput connects the same voltage level, but shouldn't", invalidTransformer2W) + GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().subnet(2).build()).build() || 1 || new InvalidEntityException("Transformer2WInput connects the same subnet, but shouldn't", invalidTransformer2W) + GridTestData.transformerBtoD.copy().nodeB(GridTestData.nodeD.copy().voltLvl(GermanVoltageLevelUtils.MV_30KV).build()).build() || 1 || new InvalidEntityException("Rated voltages of Transformer2WInput do not equal voltage levels at the nodes", invalidTransformer2W) } def "Smoke Test: Correct transformer2W type throws no exception"() { @@ -162,8 +156,7 @@ class ConnectorValidationUtilsTest extends Specification { then: Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + ex.message.contains(expectedException.message) where: invalidTransformer2WType || expectedException @@ -185,19 +178,19 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3W recognizes all potential errors for a transformer3W"() { when: - ConnectorValidationUtils.check(invalidTransformer3W) + List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() - ex.class == expectedException.class + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: - invalidTransformer3W || expectedException - GridTestData.transformerAtoBtoC.copy().tapPos(100).build() || new InvalidEntityException("Tap position of Transformer3WInput is outside of bounds", invalidTransformer3W) - GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().voltLvl(GermanVoltageLevelUtils.HV).build()).build() || new InvalidEntityException("Transformer connects nodes of the same voltage level", invalidTransformer3W) - GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().subnet(2).build()).build() || new InvalidEntityException("Transformer connects nodes in the same subnet", invalidTransformer3W) - GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().voltLvl(GermanVoltageLevelUtils.MV_30KV).build()).build() || new InvalidEntityException("Rated voltages of Transformer3WInput do not equal voltage levels at the nodes", invalidTransformer3W) + invalidTransformer3W || expectedSize || expectedException + GridTestData.transformerAtoBtoC.copy().tapPos(100).build() || 1 || new InvalidEntityException("Tap position of Transformer3WInput is outside of bounds", invalidTransformer3W) + GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().voltLvl(GermanVoltageLevelUtils.HV).build()).build() || 2 || new InvalidEntityException("Transformer connects nodes of the same voltage level", invalidTransformer3W) + GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().subnet(2).build()).build() || 1 || new InvalidEntityException("Transformer connects nodes in the same subnet", invalidTransformer3W) + GridTestData.transformerAtoBtoC.copy().nodeA(GridTestData.nodeA.copy().voltLvl(GermanVoltageLevelUtils.MV_30KV).build()).build() || 1 || new InvalidEntityException("Rated voltages of Transformer3WInput do not equal voltage levels at the nodes", invalidTransformer3W) } def "Smoke Test: Correct transformer3W type throws no exception"() { @@ -229,8 +222,7 @@ class ConnectorValidationUtilsTest extends Specification { then: Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + ex.message.contains(expectedException.message) where: invalidTransformer3WType || expectedException @@ -252,15 +244,15 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkSwitch recognizes all potential errors for a switch"() { when: - ConnectorValidationUtils.check(invalidSwitch) + List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() - ex.class == expectedException.class + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: - invalidSwitch || expectedException - GridTestData.switchAtoB || new InvalidEntityException("Switch connects two different voltage levels", invalidSwitch) + invalidSwitch || expectedSize || expectedException + GridTestData.switchAtoB || 1 || new InvalidEntityException("Switch connects two different voltage levels", invalidSwitch) } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy similarity index 58% rename from src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy rename to src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy index 085dda21e..899c6279f 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy @@ -1,5 +1,5 @@ /* - * © 2021. TU Dortmund University, + * © 2023. TU Dortmund University, * Institute of Energy Systems, Energy Efficiency and Energy Economics, * Research group Distribution grid planning and operation */ @@ -9,10 +9,17 @@ import edu.ie3.datamodel.models.input.AssetInput import java.time.ZonedDateTime -class InvalidAssetInput extends AssetInput { +class DummyAssetInput extends AssetInput { + DummyAssetInput(String id) { + super(UUID.randomUUID(), id) + } + + static DummyAssetInput valid(String id) { + return new DummyAssetInput(id) + } - InvalidAssetInput() { - super(UUID.randomUUID(), "invalid_asset") + static DummyAssetInput invalid() { + return new DummyAssetInput("invalid_asset") } @Override @@ -21,7 +28,7 @@ class InvalidAssetInput extends AssetInput { } @Override - UniqueEntityBuilder copy() { + AssetInputCopyBuilder copy() { throw new UnsupportedOperationException("This is a dummy class") } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy index 19a5264d7..aefd2825b 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy @@ -6,6 +6,7 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import spock.lang.Specification @@ -29,43 +30,46 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.check() recognizes all potential errors for a graphic input"() { when: - GraphicValidationUtils.check(invalidGraphicInput) + List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidGraphicInput || expectedException - GridTestData.lineGraphicCtoD.copy().graphicLayer(null).build() || new InvalidEntityException("Graphic Layer of graphic element is not defined", invalidGraphicInput) + invalidGraphicInput || expectedSize || expectedException + GridTestData.lineGraphicCtoD.copy().graphicLayer(null).build() || 1 || new InvalidEntityException("Graphic Layer of graphic element is not defined", invalidGraphicInput) } def "GraphicValidationUtils.checkLineGraphicInput() recognizes all potential errors for a line graphic input"() { when: - GraphicValidationUtils.check(invalidLineGraphicInput) + List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidLineGraphicInput || expectedException - GridTestData.lineGraphicCtoD.copy().path(null).build() || new InvalidEntityException("Path of line graphic element is not defined", invalidLineGraphicInput) + invalidLineGraphicInput || expectedSize || expectedException + GridTestData.lineGraphicCtoD.copy().path(null).build() || 1 || new InvalidEntityException("Path of line graphic element is not defined", invalidLineGraphicInput) } def "GraphicValidationUtils.checkNodeGraphicInput() recognizes all potential errors for a line graphic input"() { when: - GraphicValidationUtils.check(invalidNodeGraphicInput) + List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidNodeGraphicInput || expectedException - GridTestData.nodeGraphicC.copy().point(null).build() || new InvalidEntityException("Point of node graphic is not defined", invalidNodeGraphicInput) + invalidNodeGraphicInput || expectedSize || expectedException + GridTestData.nodeGraphicC.copy().point(null).build() || 1 || new InvalidEntityException("Point of node graphic is not defined", invalidNodeGraphicInput) } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidSystemParticipantInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidSystemParticipantInput.groovy index 737c40d38..9aee7acf6 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidSystemParticipantInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidSystemParticipantInput.groovy @@ -22,7 +22,7 @@ class InvalidSystemParticipantInput extends SystemParticipantInput { } @Override - SystemParticipantInputCopyBuilder copy() { + SystemParticipantInputCopyBuilder copy() { throw new UnsupportedOperationException("This is a dummy class") } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy index 8daa30362..39ea3ec89 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy @@ -6,6 +6,8 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.UnsafeEntityException +import edu.ie3.datamodel.exceptions.ValidationException +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import spock.lang.Specification @@ -24,10 +26,11 @@ class MeasurementUnitValidationUtilsTest extends Specification { def "MeasurementUnitValidationUtils.check() recognizes all potential errors for a measurement unit"() { when: - MeasurementUnitValidationUtils.check(invalidMeasurementUnit) + Try exception = MeasurementUnitValidationUtils.check(invalidMeasurementUnit) then: - Exception ex = thrown() + exception.failure + Exception ex = exception.exception.get() ex.class == expectedException.class ex.message == expectedException.message diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy index f77752eb3..f17b2ae3e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -8,12 +8,13 @@ package edu.ie3.datamodel.utils.validation import static edu.ie3.util.quantities.PowerSystemUnits.KILOVOLT import static edu.ie3.util.quantities.PowerSystemUnits.PU +import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.exceptions.UnsafeEntityException +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.voltagelevels.CommonVoltageLevel -import edu.ie3.util.interval.RightOpenInterval - -import edu.ie3.datamodel.exceptions.InvalidEntityException +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData +import edu.ie3.util.interval.RightOpenInterval import spock.lang.Specification import tech.units.indriya.quantity.Quantities @@ -24,39 +25,40 @@ class NodeValidationUtilsTest extends Specification { def node = GridTestData.nodeA when: - NodeValidationUtils.check(node) + List> tries = NodeValidationUtils.check(node) then: - noExceptionThrown() + tries.every { it.success } } def "The check method recognizes all potential errors for a node"() { when: - NodeValidationUtils.check(invalidNode) + List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidNode || expectedException - GridTestData.nodeA.copy().voltLvl(null).build() || new InvalidEntityException("Expected a voltage level, but got nothing. :-(", new NullPointerException()) + invalidNode || expectedSize || expectedException + GridTestData.nodeA.copy().voltLvl(null).build() || 1 || new InvalidEntityException("Validation not possible because received object was null. Expected a voltage level, but got nothing. :-(", new NullPointerException()) GridTestData.nodeA.copy().voltLvl(new CommonVoltageLevel( "null", null, new HashSet<>(Arrays.asList("null")), new RightOpenInterval<>( - Quantities.getQuantity(380d, KILOVOLT), Quantities.getQuantity(560d, KILOVOLT)))).build() || new InvalidEntityException("Node has invalid voltage level", invalidNode) + Quantities.getQuantity(380d, KILOVOLT), Quantities.getQuantity(560d, KILOVOLT)))).build() || 1 || new InvalidEntityException("Node has invalid voltage level", invalidNode) GridTestData.nodeA.copy().voltLvl(new CommonVoltageLevel( "zero volt", Quantities.getQuantity(0d, KILOVOLT), new HashSet<>(Arrays.asList("zero volt")), new RightOpenInterval<>( - Quantities.getQuantity(380d, KILOVOLT), Quantities.getQuantity(560d, KILOVOLT)))).build() || new InvalidEntityException("Node has invalid voltage level", invalidNode) - GridTestData.nodeA.copy().subnet(0).build() || new InvalidEntityException("Subnet can't be zero or negative", invalidNode) - GridTestData.nodeA.copy().geoPosition(null).build() || new InvalidEntityException("GeoPosition of node is null", invalidNode) - GridTestData.nodeA.copy().vTarget(Quantities.getQuantity(0d, PU)).build() || new InvalidEntityException("Target voltage (p.u.) is not a positive value", invalidNode) - GridTestData.nodeA.copy().vTarget(Quantities.getQuantity(2.1d, PU)).build() || new UnsafeEntityException("Target voltage (p.u.) might be too high", invalidNode) + Quantities.getQuantity(380d, KILOVOLT), Quantities.getQuantity(560d, KILOVOLT)))).build() || 1 || new InvalidEntityException("Node has invalid voltage level", invalidNode) + GridTestData.nodeA.copy().subnet(0).build() || 1 || new InvalidEntityException("Subnet can't be zero or negative", invalidNode) + GridTestData.nodeA.copy().geoPosition(null).build() || 1 || new InvalidEntityException("GeoPosition of node is null", invalidNode) + GridTestData.nodeA.copy().vTarget(Quantities.getQuantity(0d, PU)).build() || 1 || new InvalidEntityException("Target voltage (p.u.) is not a positive value", invalidNode) + GridTestData.nodeA.copy().vTarget(Quantities.getQuantity(2.1d, PU)).build() || 1 || new UnsafeEntityException("Target voltage (p.u.) might be too high", invalidNode) } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy index 85e796d99..6f9cc47aa 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -10,6 +10,7 @@ import edu.ie3.datamodel.exceptions.NotImplementedException import edu.ie3.datamodel.models.input.NodeInput import edu.ie3.datamodel.models.input.system.characteristic.WecCharacteristicInput import edu.ie3.datamodel.models.input.system.type.* +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.SystemParticipantTestData import edu.ie3.util.quantities.interfaces.Currency import edu.ie3.util.quantities.interfaces.DimensionlessRate @@ -47,16 +48,17 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.check() recognizes all potential errors for a system participant"() { when: - SystemParticipantValidationUtils.check(invalidSystemParticipant) + List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidSystemParticipant || expectedException - SystemParticipantTestData.bmInput.copy().qCharacteristics(null).build() || new InvalidEntityException("Reactive power characteristics of system participant is not defined", invalidSystemParticipant) + invalidSystemParticipant || expectedSize || expectedException + SystemParticipantTestData.bmInput.copy().qCharacteristics(null).build() || 1 || new InvalidEntityException("Reactive power characteristics of system participant is not defined", invalidSystemParticipant) } // Common data for all system participant types @@ -99,7 +101,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -138,17 +141,18 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkBmType() recognizes all potential errors for a biomass power plant type"() { when: - SystemParticipantValidationUtils.check(invalidBmType) + ValidationUtils.check(invalidBmType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message where: - invalidBmType || expectedException - new BmTypeInput(uuid, id, capex, opex, Quantities.getQuantity(-25, ACTIVE_POWER_GRADIENT), sRated, cosPhiRated, etaConv) || new InvalidEntityException("The following quantities have to be zero or positive: -25 %/h", invalidBmType) - new BmTypeInput(uuid, id, capex, opex, activePowerGradient, sRated, cosPhiRated, Quantities.getQuantity(1000d, PERCENT)) || new InvalidEntityException("Efficiency of inverter of BmTypeInput must be between 0% and 100%", invalidBmType) + invalidBmType || expectedException + new BmTypeInput(uuid, id, capex, opex, Quantities.getQuantity(-25, ACTIVE_POWER_GRADIENT), sRated, cosPhiRated, etaConv) || new InvalidEntityException("The following quantities have to be zero or positive: -25 %/h", invalidBmType) + new BmTypeInput(uuid, id, capex, opex, activePowerGradient, sRated, cosPhiRated, Quantities.getQuantity(1000d, PERCENT)) || new InvalidEntityException("Efficiency of inverter of BmTypeInput must be between 0% and 100%", invalidBmType) } // CHP @@ -182,7 +186,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidChpType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -225,7 +230,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidEvType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -249,17 +255,18 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkFixedFeedIn() recognizes all potential errors for an a Fixed Feed-In"() { when: - SystemParticipantValidationUtils.check(invalidFixedFeedIn) + List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidFixedFeedIn || expectedException - SystemParticipantTestData.fixedFeedInInput.copy().sRated(Quantities.getQuantity(-100d, ACTIVE_POWER_IN)).build() || new InvalidEntityException("The following quantities have to be zero or positive: -100 kVA", invalidFixedFeedIn) - SystemParticipantTestData.fixedFeedInInput.copy().cosPhiRated(-1d).build() || new InvalidEntityException("Rated power factor of FixedFeedInInput must be between 0 and 1", invalidFixedFeedIn) + invalidFixedFeedIn || expectedSize || expectedException + SystemParticipantTestData.fixedFeedInInput.copy().sRated(Quantities.getQuantity(-100d, ACTIVE_POWER_IN)).build() || 1 || new InvalidEntityException("The following quantities have to be zero or positive: -100 kVA", invalidFixedFeedIn) + SystemParticipantTestData.fixedFeedInInput.copy().cosPhiRated(-1d).build() || 1 || new InvalidEntityException("Rated power factor of FixedFeedInInput must be between 0 and 1", invalidFixedFeedIn) } // HP @@ -293,7 +300,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidHpType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -317,18 +325,19 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkLoad() recognizes all potential errors for a load"() { when: - SystemParticipantValidationUtils.check(invalidLoad) + List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidLoad || expectedException - SystemParticipantTestData.loadInput.copy().loadprofile(null).build() || new InvalidEntityException("No standard load profile defined for load", invalidLoad) - SystemParticipantTestData.loadInput.copy().sRated(Quantities.getQuantity(-25d, ACTIVE_POWER_IN)).eConsAnnual(Quantities.getQuantity(-4000, ENERGY_IN)).build() || new InvalidEntityException("The following quantities have to be zero or positive: -25 kVA, -4000 kWh", invalidLoad) - SystemParticipantTestData.loadInput.copy().cosPhiRated(2).build() || new InvalidEntityException("Rated power factor of LoadInput must be between 0 and 1", invalidLoad) + invalidLoad || expectedSize || expectedException + SystemParticipantTestData.loadInput.copy().loadprofile(null).build() || 1 || new InvalidEntityException("No standard load profile defined for load", invalidLoad) + SystemParticipantTestData.loadInput.copy().sRated(Quantities.getQuantity(-25d, ACTIVE_POWER_IN)).eConsAnnual(Quantities.getQuantity(-4000, ENERGY_IN)).build() || 1 || new InvalidEntityException("The following quantities have to be zero or positive: -25 kVA, -4000 kWh", invalidLoad) + SystemParticipantTestData.loadInput.copy().cosPhiRated(2).build() || 1 || new InvalidEntityException("Rated power factor of LoadInput must be between 0 and 1", invalidLoad) } // PV @@ -346,21 +355,22 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkPV() recognizes all potential errors for a PV"() { when: - SystemParticipantValidationUtils.check(invalidPV) + List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidPV || expectedException - SystemParticipantTestData.pvInput.copy().sRated(Quantities.getQuantity(-25d, ACTIVE_POWER_IN)).build() || new InvalidEntityException("The following quantities have to be zero or positive: -25 kVA", invalidPV) - SystemParticipantTestData.pvInput.copy().albedo(2).build() || new InvalidEntityException("Albedo of the plant's surrounding of PvInput must be between 0 and 1", invalidPV) - SystemParticipantTestData.pvInput.copy().azimuth(Quantities.getQuantity(-100d, AZIMUTH)).build() || new InvalidEntityException("Azimuth angle of PvInput must be between -90° (east) and 90° (west)", invalidPV) - SystemParticipantTestData.pvInput.copy().etaConv(Quantities.getQuantity(110d, EFFICIENCY)).build() || new InvalidEntityException("Efficiency of the converter of PvInput must be between 0% and 100%", invalidPV) - SystemParticipantTestData.pvInput.copy().elevationAngle(Quantities.getQuantity(100d, SOLAR_ELEVATION_ANGLE)).build() || new InvalidEntityException("Tilted inclination from horizontal of PvInput must be between 0° and 90°", invalidPV) - SystemParticipantTestData.pvInput.copy().cosPhiRated(2).build() || new InvalidEntityException("Rated power factor of PvInput must be between 0 and 1", invalidPV) + invalidPV || expectedSize || expectedException + SystemParticipantTestData.pvInput.copy().sRated(Quantities.getQuantity(-25d, ACTIVE_POWER_IN)).build() || 1 || new InvalidEntityException("The following quantities have to be zero or positive: -25 kVA", invalidPV) + SystemParticipantTestData.pvInput.copy().albedo(2).build() || 1 || new InvalidEntityException("Albedo of the plant's surrounding of PvInput must be between 0 and 1", invalidPV) + SystemParticipantTestData.pvInput.copy().azimuth(Quantities.getQuantity(-100d, AZIMUTH)).build() || 1 || new InvalidEntityException("Azimuth angle of PvInput must be between -90° (east) and 90° (west)", invalidPV) + SystemParticipantTestData.pvInput.copy().etaConv(Quantities.getQuantity(110d, EFFICIENCY)).build() || 1 || new InvalidEntityException("Efficiency of the converter of PvInput must be between 0% and 100%", invalidPV) + SystemParticipantTestData.pvInput.copy().elevationAngle(Quantities.getQuantity(100d, SOLAR_ELEVATION_ANGLE)).build() || 1 || new InvalidEntityException("Tilted inclination from horizontal of PvInput must be between 0° and 90°", invalidPV) + SystemParticipantTestData.pvInput.copy().cosPhiRated(2).build() || 1 || new InvalidEntityException("Rated power factor of PvInput must be between 0 and 1", invalidPV) } // Storage @@ -394,7 +404,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidStorageType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -438,7 +449,8 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidWecType) then: - Exception ex = thrown() + Throwable topEx = thrown() + Throwable ex = topEx.cause ex.class == expectedException.class ex.message == expectedException.message @@ -455,10 +467,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipant = new InvalidSystemParticipantInput(node) when: - SystemParticipantValidationUtils.check(invalidParticipant) + List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter { it -> it.failure }.toList() then: - def e = thrown(NotImplementedException) + def e = exceptions.get(0).exception.get().cause e.message == "Cannot validate object of class 'InvalidSystemParticipantInput', as no routine is implemented." } @@ -470,8 +482,9 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidParticipantInput) then: - def e = thrown(NotImplementedException) - e.message == "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." + Throwable topEx = thrown() + Throwable e = topEx.cause + e.message.contains "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." } def "Checking electric vehicle charging stations leads to an exception"() { diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy index e2a4a43f3..5b991a565 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy @@ -6,11 +6,13 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.OperationTime import edu.ie3.datamodel.models.StandardUnits import edu.ie3.datamodel.models.input.OperatorInput import edu.ie3.datamodel.models.input.thermal.CylindricalStorageInput import edu.ie3.datamodel.models.input.thermal.ThermalHouseInput +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.SystemParticipantTestData import edu.ie3.test.common.ThermalUnitInputTestData import edu.ie3.util.TimeUtil @@ -64,20 +66,21 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkThermalHouse() recognizes all potential errors for a thermal house"() { when: - ThermalUnitValidationUtils.check(invalidThermalHouse) + List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidThermalHouse || expectedException - new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(-10, StandardUnits.THERMAL_TRANSMISSION), ethCapa, TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || new InvalidEntityException("The following quantities have to be zero or positive: -10 kW/K", invalidThermalHouse) - new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, Quantities.getQuantity(0, StandardUnits.HEAT_CAPACITY), TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || new InvalidEntityException("The following quantities have to be positive: 0 kWh/K", invalidThermalHouse) - new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, Quantities.getQuantity(0, StandardUnits.TEMPERATURE), UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) - new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, TARGET_TEMPERATURE, Quantities.getQuantity(0, StandardUnits.TEMPERATURE), LOWER_TEMPERATURE_LIMIT) || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) - new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, Quantities.getQuantity(30, StandardUnits.TEMPERATURE)) || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) + invalidThermalHouse || expectedSize || expectedException + new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(-10, StandardUnits.THERMAL_TRANSMISSION), ethCapa, TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || 1 || new InvalidEntityException("The following quantities have to be zero or positive: -10 kW/K", invalidThermalHouse) + new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, Quantities.getQuantity(0, StandardUnits.HEAT_CAPACITY), TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || 1 || new InvalidEntityException("The following quantities have to be positive: 0 kWh/K", invalidThermalHouse) + new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, Quantities.getQuantity(0, StandardUnits.TEMPERATURE), UPPER_TEMPERATURE_LIMIT, LOWER_TEMPERATURE_LIMIT) || 1 || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) + new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, TARGET_TEMPERATURE, Quantities.getQuantity(0, StandardUnits.TEMPERATURE), LOWER_TEMPERATURE_LIMIT) || 1 || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) + new ThermalHouseInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, thermalConductance, ethCapa, TARGET_TEMPERATURE, UPPER_TEMPERATURE_LIMIT, Quantities.getQuantity(30, StandardUnits.TEMPERATURE)) || 1 || new InvalidEntityException("Target temperature must be higher than lower temperature limit and lower than upper temperature limit", invalidThermalHouse) } // Thermal Cylindrical Storage @@ -95,17 +98,18 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkCylindricalStorage() recognizes all potential errors for a thermal cylindrical storage"() { when: - ThermalUnitValidationUtils.check(invalidCylindricalStorage) + List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter { it -> it.failure }.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message where: - invalidCylindricalStorage || expectedException - new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, storageVolumeLvl, storageVolumeLvlMin, Quantities.getQuantity(100, StandardUnits.TEMPERATURE), Quantities.getQuantity(200, StandardUnits.TEMPERATURE), c) || new InvalidEntityException("Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", invalidCylindricalStorage) - new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(100, StandardUnits.VOLUME), Quantities.getQuantity(200, StandardUnits.VOLUME), inletTemp, returnTemp, c) || new InvalidEntityException("Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", invalidCylindricalStorage) - new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(-100, StandardUnits.VOLUME), Quantities.getQuantity(-200, StandardUnits.VOLUME), inletTemp, returnTemp, Quantities.getQuantity(-1.05, StandardUnits.SPECIFIC_HEAT_CAPACITY)) || new InvalidEntityException("The following quantities have to be positive: -100 ㎥, -200 ㎥, -1.05 kWh/K*m³", invalidCylindricalStorage) + invalidCylindricalStorage || expectedSize || expectedException + new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, storageVolumeLvl, storageVolumeLvlMin, Quantities.getQuantity(100, StandardUnits.TEMPERATURE), Quantities.getQuantity(200, StandardUnits.TEMPERATURE), c) || 1 || new InvalidEntityException("Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", invalidCylindricalStorage) + new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(100, StandardUnits.VOLUME), Quantities.getQuantity(200, StandardUnits.VOLUME), inletTemp, returnTemp, c) || 1 || new InvalidEntityException("Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", invalidCylindricalStorage) + new CylindricalStorageInput(thermalUnitUuid, id, operator, operationTime, SystemParticipantTestData.thermalBus, Quantities.getQuantity(-100, StandardUnits.VOLUME), Quantities.getQuantity(-200, StandardUnits.VOLUME), inletTemp, returnTemp, Quantities.getQuantity(-1.05, StandardUnits.SPECIFIC_HEAT_CAPACITY)) || 1 || new InvalidEntityException("The following quantities have to be positive: -100 ㎥, -200 ㎥, -1.05 kWh/K*m³", invalidCylindricalStorage) } } diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy index 8c9a4c59b..26c43982d 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -5,21 +5,23 @@ */ package edu.ie3.datamodel.utils.validation -import static edu.ie3.datamodel.models.StandardUnits.CONDUCTANCE_PER_LENGTH -import static edu.ie3.datamodel.models.StandardUnits.ELECTRIC_CURRENT_MAGNITUDE -import static edu.ie3.datamodel.models.StandardUnits.RATED_VOLTAGE_MAGNITUDE -import static edu.ie3.datamodel.models.StandardUnits.SUSCEPTANCE_PER_LENGTH +import static edu.ie3.datamodel.models.StandardUnits.* +import static edu.ie3.datamodel.utils.validation.DummyAssetInput.invalid +import static edu.ie3.datamodel.utils.validation.DummyAssetInput.valid import static edu.ie3.util.quantities.PowerSystemUnits.OHM_PER_KILOMETRE import static edu.ie3.util.quantities.PowerSystemUnits.PU -import edu.ie3.datamodel.exceptions.NotImplementedException - +import edu.ie3.datamodel.exceptions.FailedValidationException import edu.ie3.datamodel.exceptions.InvalidEntityException +import edu.ie3.datamodel.exceptions.UnsafeEntityException +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.OperationTime +import edu.ie3.datamodel.models.input.AssetInput import edu.ie3.datamodel.models.input.NodeInput import edu.ie3.datamodel.models.input.OperatorInput import edu.ie3.datamodel.models.input.connector.type.LineTypeInput import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import edu.ie3.util.TimeUtil import edu.ie3.util.quantities.interfaces.SpecificConductance @@ -110,12 +112,11 @@ class ValidationUtilsTest extends Specification { then: Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + ex.message.contains(expectedException.message) where: invalidObject || expectedException - new Coordinate(10, 10) || new NotImplementedException("Cannot validate object of class '" + invalidObject.getClass().getSimpleName() + "', as no routine is implemented.") + new Coordinate(10, 10) || new FailedValidationException("Cannot validate object of class '" + invalidObject.class.simpleName + "', as no routine is implemented.") } def "The validation check method recognizes all potential errors for an asset"() { @@ -124,8 +125,7 @@ class ValidationUtilsTest extends Specification { then: Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + ex.message.contains(expectedException.message) where: invalidAsset || expectedException @@ -171,7 +171,7 @@ class ValidationUtilsTest extends Specification { then: InvalidEntityException ex = thrown() - ex.message == "Entity is invalid because of: The following quantities have to be zero or positive: -1 µS/km [LineTypeInput{uuid=3bed3eb3-9790-4874-89b5-a5434d408088, id=lineType_AtoB, b=-1 µS/km, g=0.0 µS/km, r=0.437 Ω/km, x=0.356 Ω/km, iMax=300 A, vRated=20 kV}]" + ex.message == "Entity is invalid because of: \nThe following quantities have to be zero or positive: -1 µS/km [LineTypeInput{uuid=3bed3eb3-9790-4874-89b5-a5434d408088, id=lineType_AtoB, b=-1 µS/km, g=0.0 µS/km, r=0.437 Ω/km, x=0.356 Ω/km, iMax=300 A, vRated=20 kV}]" } def "The check for zero or negative entities should work as expected"() { @@ -208,19 +208,20 @@ class ValidationUtilsTest extends Specification { then: InvalidEntityException ex = thrown() - ex.message == "Entity is invalid because of: The following quantities have to be positive: 0.0 µS/km [LineTypeInput{uuid=3bed3eb3-9790-4874-89b5-a5434d408088, id=lineType_AtoB, b=0.0 µS/km, g=0.0 µS/km, r=0.437 Ω/km, x=0.356 Ω/km, iMax=300 A, vRated=20 kV}]" + ex.message == "Entity is invalid because of: \nThe following quantities have to be positive: 0.0 µS/km [LineTypeInput{uuid=3bed3eb3-9790-4874-89b5-a5434d408088, id=lineType_AtoB, b=0.0 µS/km, g=0.0 µS/km, r=0.437 Ω/km, x=0.356 Ω/km, iMax=300 A, vRated=20 kV}]" } def "Checking an unsupported asset leads to an exception"() { given: - def invalidAsset = new InvalidAssetInput() + def invalidAsset = invalid() when: - ValidationUtils.checkAsset(invalidAsset) + List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter { it -> it.failure }.toList() then: - def e = thrown(NotImplementedException) - e.message == "Cannot validate object of class 'InvalidAssetInput', as no routine is implemented." + exceptions.size() == 1 + def e = exceptions.get(0).exception.get() + e.message.contains("Cannot validate object of class 'DummyAssetInput', as no routine is implemented.") } def "Checking an unsupported asset type leads to an exception"() { @@ -228,11 +229,12 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput() when: - ValidationUtils.checkAssetType(invalidAssetType) + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter { it -> it.failure }.toList() then: - def e = thrown(NotImplementedException) - e.message == "Cannot validate object of class 'InvalidAssetTypeInput', as no routine is implemented." + exceptions.size() == 1 + def e = exceptions.get(0).exception.get() + e.message.contains("Cannot validate object of class 'InvalidAssetTypeInput', as no routine is implemented.") } def "Checking an asset type input without an id leads to an exception"() { @@ -240,10 +242,42 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput(UUID.randomUUID(), null) when: - ValidationUtils.checkAssetType(invalidAssetType) + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter { it -> it.failure }.toList() + + then: + exceptions.size() == 2 + def e = exceptions.get(0).exception.get() + e.message.startsWith("Entity is invalid because of: \nNo ID assigned [AssetTypeInput") + } + + def "Checking if asset input ids are unique"() { + given: + Set validAssetIds = [ + valid("first"), + valid("second"), + valid("third") + ] + + when: + List> exceptions = ValidationUtils.checkIds(validAssetIds) + + then: + exceptions.every { ex -> ex.success } + } + + def "Duplicate asset input ids leads to an exception"() { + given: + Set invalidAssetIds = [ + invalid(), + invalid() + ] + + when: + List> exceptions = ValidationUtils.checkIds(invalidAssetIds) then: - def e = thrown(InvalidEntityException) - e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") + exceptions.size() == 1 + exceptions.get(0).failure + exceptions.get(0).exception.get().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") } }