From 58ca672a99fb0d8374ff0cd1abaa195e0b934408 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Mon, 6 Mar 2023 12:54:49 +0100 Subject: [PATCH 01/39] Improving. --- .../exceptions/FailedValidationException.java | 16 + .../ie3/datamodel/utils/ExceptionUtils.java | 14 + .../validation/ConnectorValidationUtils.java | 396 +++++++++++---- .../validation/GraphicValidationUtils.java | 4 +- .../GridContainerValidationUtils.java | 456 ++++++++++++------ .../MeasurementUnitValidationUtils.java | 23 +- .../SystemParticipantValidationUtils.java | 4 +- .../utils/validation/ValidationUtils.java | 3 + 8 files changed, 674 insertions(+), 242 deletions(-) create mode 100644 src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java 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..c1e530c7d --- /dev/null +++ b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java @@ -0,0 +1,16 @@ +/* + * © 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; + +public class FailedValidationException extends ValidationException { + public FailedValidationException(String s) { + super(s); + } + + public FailedValidationException(String s, Throwable throwable) { + super(s, throwable); + } +} diff --git a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java index f5ccbd991..76acc2b09 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.utils; +import java.util.ArrayList; import java.util.List; public class ExceptionUtils { @@ -20,4 +21,17 @@ public static String getMessages(List exceptions) { .map(Throwable::getMessage) .reduce(firstInList.getMessage(), (a, b) -> a + ", " + b); } + + /** + * Creates a new {@link Exception} for multiple given exceptions. The new exception contains all + * messages of the given exceptions. + * + * @param exceptions list of exceptions + * @return new exceptions + */ + public static Exception getExceptions(List exceptions) { + ArrayList list = new ArrayList<>(exceptions); + String messages = getMessages(list); + return new Exception(messages); + } } 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..b9d7f4065 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -6,13 +6,21 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; +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.utils.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; import edu.ie3.util.geo.GeoUtils; import edu.ie3.util.quantities.QuantityUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import javax.measure.Quantity; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -22,7 +30,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; @@ -40,19 +48,46 @@ private ConnectorValidationUtils() { * @param connector Connector to validate * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in */ - protected static void check(ConnectorInput connector) { - checkNonNull(connector, "a connector"); - connectsDifferentNodes(connector); + protected static Try check(ConnectorInput connector) { + try { + checkNonNull(connector, "a connector"); + } catch (Exception e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + connector + "} was null", e)); + } + + Try diffNodes = + Try.apply(() -> connectsDifferentNodes(connector)); + Try con; // 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())) { + con = checkLine((LineInput) connector); + } else if (Transformer2WInput.class.isAssignableFrom(connector.getClass())) { + con = checkTransformer2W((Transformer2WInput) connector); + } else if (Transformer3WInput.class.isAssignableFrom(connector.getClass())) { + con = checkTransformer3W((Transformer3WInput) connector); + } else if (SwitchInput.class.isAssignableFrom(connector.getClass())) { + con = checkSwitch((SwitchInput) connector); + } else { + con = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(connector))); + } + + List exceptions = + Stream.of(diffNodes, con).filter(Try::isFailure).map(Try::getException).toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -68,13 +103,29 @@ else if (SwitchInput.class.isAssignableFrom(connector.getClass())) * * @param line Line to validate */ - private static void checkLine(LineInput line) { - checkLineType(line.getType()); - connectsNodesInDifferentSubnets(line, false); - connectsNodesWithDifferentVoltageLevels(line, false); - detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line); - coordinatesOfLineEqualCoordinatesOfNodes(line); - lineLengthMatchesDistancesBetweenPointsOfLineString(line); + private static Try checkLine(LineInput line) { + List exceptions = + Stream.of( + Try.apply(() -> checkLineType(line.getType())), + Try.apply(() -> connectsNodesInDifferentSubnets(line, false)), + Try.apply(() -> connectsNodesWithDifferentVoltageLevels(line, false)), + Try.apply( + () -> + detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line)), + Try.apply(() -> coordinatesOfLineEqualCoordinatesOfNodes(line)), + Try.apply(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -89,14 +140,43 @@ private static void checkLine(LineInput line) { * * @param lineType Line type to validate */ - 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 Try checkLineType(LineTypeInput lineType) { + try { + checkNonNull(lineType, "a line type"); + } catch (Exception e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + lineType + "} was null", e)); + } + + List exceptions = + Stream.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {lineType.getB(), lineType.getG()}, lineType)), + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + lineType.getvRated(), + lineType.getiMax(), + lineType.getX(), + lineType.getR() + }, + lineType))) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -110,12 +190,27 @@ protected static void checkLineType(LineTypeInput lineType) { * * @param transformer2W Transformer2W to validate */ - private static void checkTransformer2W(Transformer2WInput transformer2W) { - checkTransformer2WType(transformer2W.getType()); - checkIfTapPositionIsWithinBounds(transformer2W); - connectsNodesWithDifferentVoltageLevels(transformer2W, true); - connectsNodesInDifferentSubnets(transformer2W, true); - ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W); + private static Try checkTransformer2W( + Transformer2WInput transformer2W) { + List exceptions = + Stream.of( + Try.apply(() -> checkTransformer2WType(transformer2W.getType())), + Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer2W)), + Try.apply(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true)), + Try.apply(() -> connectsNodesInDifferentSubnets(transformer2W, true)), + Try.apply(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -135,25 +230,62 @@ private static void checkTransformer2W(Transformer2WInput transformer2W) { * * @param transformer2WType Transformer2W type to validate */ - 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 Try checkTransformer2WType( + Transformer2WTypeInput transformer2WType) { + try { + checkNonNull(transformer2WType, "a two winding transformer type"); + } catch (Exception e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + transformer2WType + + "} was null", + e)); + } + + List exceptions = + Stream.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] { + transformer2WType.getgM(), + transformer2WType.getdPhi(), + transformer2WType.getrSc() + }, + transformer2WType)), + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + transformer2WType.getsRated(), + transformer2WType.getvRatedA(), + transformer2WType.getvRatedB(), + transformer2WType.getxSc() + }, + transformer2WType)), + Try.apply( + () -> + detectPositiveQuantities( + new Quantity[] {transformer2WType.getbM()}, transformer2WType)), + Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), + Try.apply( + () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), + Try.apply( + () -> + checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -167,22 +299,48 @@ protected static void checkTransformer2WType(Transformer2WTypeInput transformer2 * * @param transformer3W Transformer3W to validate */ - private static void checkTransformer3W(Transformer3WInput transformer3W) { - checkTransformer3WType(transformer3W.getType()); - checkIfTapPositionIsWithinBounds(transformer3W); + private static Try checkTransformer3W( + Transformer3WInput transformer3W) { + List exceptions = + new ArrayList<>( + Stream.of( + Try.apply(() -> checkTransformer3WType(transformer3W.getType())), + Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer3W))) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + // 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); + || transformer3W.getNodeB().getVoltLvl() == transformer3W.getNodeC().getVoltLvl()) { + exceptions.add( + 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); + || transformer3W.getNodeB().getSubnet() == transformer3W.getNodeC().getSubnet()) { + exceptions.add( + new InvalidEntityException( + "Transformer connects nodes in the same subnet", transformer3W)); + } + + Try ratedVoltage = + Try.apply(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W)); + if (ratedVoltage.isFailure()) { + exceptions.add(ratedVoltage.getException()); + } + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -201,25 +359,68 @@ private static void checkTransformer3W(Transformer3WInput transformer3W) { * * @param transformer3WType Transformer type to validate */ - 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 Try checkTransformer3WType( + Transformer3WTypeInput transformer3WType) { + try { + checkNonNull(transformer3WType, "a three winding transformer type"); + } catch (Exception e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + transformer3WType + + "} was null", + e)); + } + + List exceptions = + Stream.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] { + transformer3WType.getgM(), transformer3WType.getdPhi() + }, + transformer3WType)), + Try.apply( + () -> + 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)), + Try.apply( + () -> + detectPositiveQuantities( + new Quantity[] {transformer3WType.getbM()}, transformer3WType)), + Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), + Try.apply( + () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), + Try.apply( + () -> + checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -228,9 +429,13 @@ protected static void checkTransformer3WType(Transformer3WTypeInput transformer3 * * @param switchInput Switch to validate */ - 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) { + if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) { + return new Failure<>( + new InvalidEntityException("Switch connects two different voltage levels", switchInput)); + } else { + return Success.empty(); + } /* 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 */ @@ -311,16 +516,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.debug( + "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.debug( + "Coordinates of start and end point do not match coordinates of connected nodes: " + + line); } /** @@ -332,10 +539,15 @@ 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.debug( + "Line length is more than " + + ALLOWED_LENGTH_ERROR + + "% greater than the calculated distances between points building the line: " + + line); + } } /** 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..24e414dbd 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -6,9 +6,11 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; 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.options.Try; public class GraphicValidationUtils extends ValidationUtils { @@ -28,7 +30,7 @@ private GraphicValidationUtils() { * @param graphicInput GraphicInput to validate * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in */ - protected static void check(GraphicInput graphicInput) { + protected static Try check(GraphicInput graphicInput) { checkNonNull(graphicInput, "a graphic input"); if (graphicInput.getGraphicLayer() == null) throw new InvalidEntityException( 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..c942f4837 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -5,8 +5,10 @@ */ package edu.ie3.datamodel.utils.validation; +import edu.ie3.datamodel.exceptions.FailedValidationException; import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.InvalidGridException; +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; @@ -16,6 +18,10 @@ import edu.ie3.datamodel.models.input.container.*; import edu.ie3.datamodel.models.input.system.SystemParticipantInput; import edu.ie3.datamodel.utils.ContainerUtils; +import edu.ie3.datamodel.utils.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; import java.util.*; import java.util.stream.Stream; @@ -50,13 +56,17 @@ protected static void check(GridContainer gridContainer) { duplicateUuidsString(gridContainer.getClass().getSimpleName(), exceptionString)); } - checkRawGridElements(gridContainer.getRawGrid()); - checkSystemParticipants( - gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes()); - checkGraphicElements( - gridContainer.getGraphics(), - gridContainer.getRawGrid().getNodes(), - gridContainer.getRawGrid().getLines()); + Try rawGridElements = + checkRawGridElements(gridContainer.getRawGrid()); + + Try systemParticipants = + checkSystemParticipants( + gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes()); + Try graphicElements = + checkGraphicElements( + gridContainer.getGraphics(), + gridContainer.getRawGrid().getNodes(), + gridContainer.getRawGrid().getLines()); } /** @@ -66,15 +76,26 @@ protected static void check(GridContainer gridContainer) { * @param rawGridElements Raw grid elements * @throws InvalidGridException If something is wrong */ - protected static void checkRawGridElements(RawGridElements rawGridElements) { - checkNonNull(rawGridElements, "raw grid elements"); + protected static Try checkRawGridElements( + RawGridElements rawGridElements) { + try { + checkNonNull(rawGridElements, "raw grid elements"); + } catch (ValidationException e) { + return new Failure<>( + new FailedValidationException( + "Validation not possible because received object {" + rawGridElements + "} was null", + e)); + } + + 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( + new InvalidGridException( + duplicateUuidsString(rawGridElements.getClass().getSimpleName(), exceptionString))); } /* Checking nodes */ @@ -82,31 +103,52 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { nodes.forEach(NodeValidationUtils::check); /* Checking lines */ - rawGridElements - .getLines() - .forEach( - line -> { - checkNodeAvailability(line, nodes); - ConnectorValidationUtils.check(line); - }); + exceptions.addAll( + rawGridElements.getLines().stream() + .map( + line -> { + try { + checkNodeAvailability(line, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return ConnectorValidationUtils.check(line); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); /* Checking two winding transformers */ - rawGridElements - .getTransformer2Ws() - .forEach( - transformer -> { - checkNodeAvailability(transformer, nodes); - ConnectorValidationUtils.check(transformer); - }); + exceptions.addAll( + rawGridElements.getTransformer2Ws().stream() + .map( + transformer -> { + try { + checkNodeAvailability(transformer, nodes); + } catch (InvalidGridException e) { + return new Failure<>(e); + } + return ConnectorValidationUtils.check(transformer); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); /* Checking three winding transformers */ - rawGridElements - .getTransformer3Ws() - .forEach( - transformer -> { - checkNodeAvailability(transformer, nodes); - ConnectorValidationUtils.check(transformer); - }); + exceptions.addAll( + rawGridElements.getTransformer3Ws().stream() + .map( + transformer -> { + try { + checkNodeAvailability(transformer, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return ConnectorValidationUtils.check(transformer); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); /* Checking switches * Because of the fact, that a transformer with switch gear in "upstream" direction has it's corresponding node in @@ -123,22 +165,45 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { .getLast()) .toList()); - rawGridElements - .getSwitches() - .forEach( - switcher -> { - checkNodeAvailability(switcher, validSwitchNodes); - ConnectorValidationUtils.check(switcher); - }); + exceptions.addAll( + rawGridElements.getSwitches().stream() + .map( + switcher -> { + try { + checkNodeAvailability(switcher, validSwitchNodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return ConnectorValidationUtils.check(switcher); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); /* Checking measurement units */ - rawGridElements - .getMeasurementUnits() - .forEach( - measurement -> { - checkNodeAvailability(measurement, nodes); - MeasurementUnitValidationUtils.check(measurement); - }); + exceptions.addAll( + rawGridElements.getMeasurementUnits().stream() + .map( + measurement -> { + try { + checkNodeAvailability(measurement, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return MeasurementUnitValidationUtils.check(measurement); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new FailedValidationException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -148,85 +213,154 @@ protected static void checkRawGridElements(RawGridElements rawGridElements) { * @param systemParticipants The system participants * @param nodes Set of already known nodes */ - protected static void checkSystemParticipants( + protected static Try checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { checkNonNull(systemParticipants, "system participants"); + 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)); + exceptions.add( + 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); - }); + exceptions.addAll( + systemParticipants.getBmPlants().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getChpPlants().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); /* 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); - }); - - systemParticipants - .getLoads() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - systemParticipants - .getPvPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - systemParticipants - .getStorages() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); - - systemParticipants - .getWecPlants() - .forEach( - entity -> { - checkNodeAvailability(entity, nodes); - SystemParticipantValidationUtils.check(entity); - }); + exceptions.addAll( + systemParticipants.getFixedFeedIns().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getHeatPumps().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getLoads().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getPvPlants().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getStorages().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + systemParticipants.getWecPlants().stream() + .map( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (ValidationException e) { + return new Failure<>(e); + } + return SystemParticipantValidationUtils.check(entity); + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new FailedValidationException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -236,47 +370,83 @@ protected static void checkSystemParticipants( * @param nodes Already known and checked nodes * @param lines Already known and checked lines */ - protected static void checkGraphicElements( + protected static Try checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { checkNonNull(graphicElements, "graphic elements"); + 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( + 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); - }); - - 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( + (Collection) + graphicElements.getNodeGraphics().stream() + .map( + graphic -> { + try { + GraphicValidationUtils.check(graphic); + } catch (ValidationException e) { + return new Failure<>(e); + } + if (!nodes.contains(graphic.getNode())) { + return new Failure<>( + 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)); + } else { + return Success.empty(); + } + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + exceptions.addAll( + (Collection) + graphicElements.getLineGraphics().stream() + .map( + graphic -> { + try { + GraphicValidationUtils.check(graphic); + } catch (ValidationException e) { + return new Failure<>(e); + } + if (!lines.contains(graphic.getLine())) { + return new Failure<>( + 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)); + } else { + return Success.empty(); + } + }) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new FailedValidationException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** 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..851c7b2a0 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -6,7 +6,11 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.UnsafeEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.MeasurementUnitInput; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; public class MeasurementUnitValidationUtils extends ValidationUtils { @@ -22,13 +26,22 @@ private MeasurementUnitValidationUtils() { * * @param measurementUnit Measurement unit to validate */ - protected static void check(MeasurementUnitInput measurementUnit) { - checkNonNull(measurementUnit, "a measurement unit"); + protected static Try check(MeasurementUnitInput measurementUnit) { + try { + checkNonNull(measurementUnit, "a measurement unit"); + } catch (ValidationException e) { + return new Failure<>(e); + } + if (!measurementUnit.getP() && !measurementUnit.getQ() && !measurementUnit.getVAng() - && !measurementUnit.getVMag()) - throw new UnsafeEntityException( - "Measurement Unit does not measure any values", measurementUnit); + && !measurementUnit.getVMag()) { + return new Failure<>( + new UnsafeEntityException( + "Measurement Unit does not measure any values", measurementUnit)); + } else { + return Success.empty(); + } } } 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..5da63d841 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,11 @@ import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.NotImplementedException; +import edu.ie3.datamodel.exceptions.ValidationException; 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.options.Try; import javax.measure.Quantity; import javax.measure.quantity.Dimensionless; import tech.units.indriya.ComparableQuantity; @@ -36,7 +38,7 @@ private SystemParticipantValidationUtils() { * @param systemParticipant systemParticipant to validate * @throws edu.ie3.datamodel.exceptions.NotImplementedException if an unknown class is handed in */ - protected static void check(SystemParticipantInput systemParticipant) { + protected static Try check(SystemParticipantInput systemParticipant) { checkNonNull(systemParticipant, "a system participant"); if (systemParticipant.getqCharacteristics() == null) throw new InvalidEntityException( 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..b478ab577 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -26,9 +26,12 @@ 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() { From 438e3b411c70af5acd2ca2b3c1d029af113fabd2 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Wed, 8 Mar 2023 12:34:11 +0100 Subject: [PATCH 02/39] Improving ``ValidationUtils``. --- .../validation/ConnectorValidationUtils.java | 17 +- .../validation/GraphicValidationUtils.java | 58 ++- .../GridContainerValidationUtils.java | 84 ++- .../MeasurementUnitValidationUtils.java | 9 +- .../utils/validation/NodeValidationUtils.java | 50 +- .../SystemParticipantValidationUtils.java | 484 ++++++++++++++---- .../ThermalUnitValidationUtils.java | 218 ++++++-- .../utils/validation/ValidationUtils.java | 163 ++++-- 8 files changed, 842 insertions(+), 241 deletions(-) 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 b9d7f4065..9264b262d 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -46,12 +46,12 @@ 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 try object either containing a {@link ValidationException} or an empty Success */ protected static Try check(ConnectorInput connector) { try { checkNonNull(connector, "a connector"); - } catch (Exception e) { + } catch (InvalidEntityException e) { return new Failure<>( new InvalidEntityException( "Validation not possible because received object {" + connector + "} was null", e)); @@ -102,6 +102,7 @@ protected static Try check(ConnectorInput connector) * - its coordinates of start and end point equal coordinates of nodes * * @param line Line to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ private static Try checkLine(LineInput line) { List exceptions = @@ -139,11 +140,12 @@ private static Try checkLine(LineInput line) { * - vRated is greater 0 (Rated voltage) * * @param lineType Line type to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ protected static Try checkLineType(LineTypeInput lineType) { try { checkNonNull(lineType, "a line type"); - } catch (Exception e) { + } catch (InvalidEntityException e) { return new Failure<>( new InvalidEntityException( "Validation not possible because received object {" + lineType + "} was null", e)); @@ -189,6 +191,7 @@ protected static Try checkLineType(LineTypeInput l * - its rated voltages match the voltages at the nodes * * @param transformer2W Transformer2W to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ private static Try checkTransformer2W( Transformer2WInput transformer2W) { @@ -229,12 +232,13 @@ private static Try checkTransformer2W( * - minimum tap position is smaller than maximum tap position * * @param transformer2WType Transformer2W type to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ protected static Try checkTransformer2WType( Transformer2WTypeInput transformer2WType) { try { checkNonNull(transformer2WType, "a two winding transformer type"); - } catch (Exception e) { + } catch (InvalidEntityException e) { return new Failure<>( new InvalidEntityException( "Validation not possible because received object {" @@ -298,6 +302,7 @@ protected static Try checkTransformer2WType( * - its rated voltages match the voltages at the nodes * * @param transformer3W Transformer3W to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ private static Try checkTransformer3W( Transformer3WInput transformer3W) { @@ -358,12 +363,13 @@ private static Try checkTransformer3W( * - minimum tap position is smaller than maximum tap position
* * @param transformer3WType Transformer type to validate + * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ protected static Try checkTransformer3WType( Transformer3WTypeInput transformer3WType) { try { checkNonNull(transformer3WType, "a three winding transformer type"); - } catch (Exception e) { + } catch (InvalidEntityException e) { return new Failure<>( new InvalidEntityException( "Validation not possible because received object {" @@ -428,6 +434,7 @@ protected static Try checkTransformer3WType( * - 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 Try checkSwitch(SwitchInput switchInput) { if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) { 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 24e414dbd..4ab789ce7 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -6,11 +6,15 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; -import edu.ie3.datamodel.exceptions.ValidationException; 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.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; +import java.util.List; +import java.util.stream.Stream; public class GraphicValidationUtils extends ValidationUtils { @@ -28,19 +32,51 @@ 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 try object either containing an {@link InvalidEntityException} or an empty Success */ - protected static Try 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 Try check(GraphicInput graphicInput) { + try { + checkNonNull(graphicInput, "a graphic input"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + graphicInput + "} was null", + e)); + } + + Try layer; + + if (graphicInput.getGraphicLayer() == null) { + layer = + new Failure<>( + new InvalidEntityException( + "Graphic Layer of graphic element is not defined", graphicInput)); + } else { + layer = Success.empty(); + } + + Try graphic; // 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())) { + graphic = Try.apply(() -> checkLineGraphicInput((LineGraphicInput) graphicInput)); + } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { + graphic = Try.apply(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput)); + } else { + graphic = Success.empty(); + } + + List exceptions = + Stream.of(layer, graphic).filter(Try::isFailure).map(Try::getException).toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** 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 c942f4837..107af46db 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -44,29 +44,55 @@ private GridContainerValidationUtils() { * Checks a complete grid data container * * @param gridContainer Grid model to check + * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static void check(GridContainer gridContainer) { - checkNonNull(gridContainer, "grid container"); + protected static Try check(GridContainer gridContainer) { + try { + checkNonNull(gridContainer, "grid container"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + gridContainer + "} was null", + e)); + } + + 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( + new InvalidGridException( + duplicateUuidsString(gridContainer.getClass().getSimpleName(), exceptionString))); } - Try rawGridElements = + Try rawGridElements = checkRawGridElements(gridContainer.getRawGrid()); - Try systemParticipants = + Try systemParticipants = checkSystemParticipants( gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes()); - Try graphicElements = + Try graphicElements = checkGraphicElements( gridContainer.getGraphics(), gridContainer.getRawGrid().getNodes(), gridContainer.getRawGrid().getLines()); + + exceptions.addAll( + Stream.of(rawGridElements, systemParticipants, graphicElements) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new FailedValidationException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -74,15 +100,15 @@ 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 try object either containing an {@link ValidationException} or an empty Success */ - protected static Try checkRawGridElements( + protected static Try checkRawGridElements( RawGridElements rawGridElements) { try { checkNonNull(rawGridElements, "raw grid elements"); - } catch (ValidationException e) { + } catch (InvalidEntityException e) { return new Failure<>( - new FailedValidationException( + new InvalidEntityException( "Validation not possible because received object {" + rawGridElements + "} was null", e)); } @@ -212,10 +238,20 @@ protected static Try checkRawGridElements( * * @param systemParticipants The system participants * @param nodes Set of already known nodes + * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static Try checkSystemParticipants( + protected static Try checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { - checkNonNull(systemParticipants, "system participants"); + try { + checkNonNull(systemParticipants, "system participants"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipants + + "} was null", + e)); + } List exceptions = new ArrayList<>(); @@ -369,10 +405,18 @@ protected static Try checkSystemParticipants( * @param graphicElements Elements to check * @param nodes Already known and checked nodes * @param lines Already known and checked lines + * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static Try checkGraphicElements( + protected static Try checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { - checkNonNull(graphicElements, "graphic elements"); + try { + checkNonNull(graphicElements, "graphic elements"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + graphicElements + "} was null", + e)); + } List exceptions = new ArrayList<>(); @@ -392,7 +436,7 @@ protected static Try checkGraphicElements( graphic -> { try { GraphicValidationUtils.check(graphic); - } catch (ValidationException e) { + } catch (InvalidEntityException e) { return new Failure<>(e); } if (!nodes.contains(graphic.getNode())) { @@ -404,9 +448,8 @@ protected static Try checkGraphicElements( + graphic.getNode().getUuid() + "', that is not among the provided ones.", graphic)); - } else { - return Success.empty(); } + return Success.empty(); }) .filter(Try::isFailure) .map(Try::getException) @@ -419,7 +462,7 @@ protected static Try checkGraphicElements( graphic -> { try { GraphicValidationUtils.check(graphic); - } catch (ValidationException e) { + } catch (InvalidEntityException e) { return new Failure<>(e); } if (!lines.contains(graphic.getLine())) { @@ -431,9 +474,8 @@ protected static Try checkGraphicElements( + graphic.getLine().getUuid() + "', that is not among the provided ones.", graphic)); - } else { - return Success.empty(); } + return Success.empty(); }) .filter(Try::isFailure) .map(Try::getException) 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 851c7b2a0..bd48b1fc9 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -5,6 +5,7 @@ */ 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; @@ -25,12 +26,16 @@ 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 Try check(MeasurementUnitInput measurementUnit) { try { checkNonNull(measurementUnit, "a measurement unit"); - } catch (ValidationException e) { - return new Failure<>(e); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + measurementUnit + "} was null", + e)); } if (!measurementUnit.getP() 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..b6488a540 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,13 @@ */ 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.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -30,33 +31,52 @@ private NodeValidationUtils() { * - geoPosition is not null * * @param node Node to validate + * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static void check(NodeInput node) { - checkNonNull(node, "a node"); + protected static Try check(NodeInput node) { + try { + checkNonNull(node, "a node"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + node + "} was null", e)); + } + try { checkVoltageLevel(node.getVoltLvl()); } catch (VoltageLevelException e) { - throw new InvalidEntityException("Node has invalid voltage level", node); + return new Failure<>(new InvalidEntityException("Node has invalid voltage level", node)); + } catch (InvalidEntityException invalidEntityException) { + return 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); + .isLessThanOrEqualTo(Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { + return new Failure<>( + new InvalidEntityException("Target voltage (p.u.) is not a positive value", node)); + } else if (node.getvTarget() + .isGreaterThan(Quantities.getQuantity(2, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { + return new Failure<>( + 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); + return new Failure<>(new InvalidEntityException("Subnet can't be zero or negative", node)); + if (node.getGeoPosition() == null) { + return new Failure<>(new InvalidEntityException("GeoPosition of node is null", node)); + } + + return Success.empty(); } /** * 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 { + private static void checkVoltageLevel(VoltageLevel voltageLevel) + throws InvalidEntityException, VoltageLevelException { checkNonNull(voltageLevel, "a voltage level"); if (voltageLevel.getNominalVoltage() == null) throw new VoltageLevelException( 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 5da63d841..5f5dd9762 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -13,7 +13,13 @@ 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.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import javax.measure.Quantity; import javax.measure.quantity.Dimensionless; import tech.units.indriya.ComparableQuantity; @@ -36,35 +42,76 @@ 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 try object either containing an {@link ValidationException} or an empty Success */ protected static Try 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); + try { + checkNonNull(systemParticipant, "a system participant"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipant + + "} was null", + e)); + } + + Try qCharacteristic; + + if (systemParticipant.getqCharacteristics() == null) { + qCharacteristic = + new Failure<>( + new InvalidEntityException( + "Reactive power characteristics of system participant is not defined", + systemParticipant)); + } else { + qCharacteristic = Success.empty(); + } + + Try participant; // 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())) { + participant = Try.apply(() -> checkBm((BmInput) systemParticipant)); + } else if (ChpInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(() -> checkChp((ChpInput) systemParticipant)); + } else if (EvInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(() -> checkEv((EvInput) systemParticipant)); + } else if (FixedFeedInInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = checkFixedFeedIn((FixedFeedInInput) systemParticipant); + } else if (HpInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(() -> checkHp((HpInput) systemParticipant)); + } else if (LoadInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = checkLoad((LoadInput) systemParticipant); + } else if (PvInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = checkPv((PvInput) systemParticipant); + } else if (StorageInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(() -> checkStorage((StorageInput) systemParticipant)); + } else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(() -> checkWec((WecInput) systemParticipant)); + } else if (EvcsInput.class.isAssignableFrom(systemParticipant.getClass())) { + participant = Try.apply(SystemParticipantValidationUtils::checkEvcs); + } else { + participant = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(systemParticipant))); + } + + List exceptions = + Stream.of(qCharacteristic, participant) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -79,37 +126,80 @@ 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 try object either containing an {@link InvalidEntityException} or an empty Success */ - protected static void checkType(SystemParticipantTypeInput systemParticipantTypeInput) { - checkNonNull(systemParticipantTypeInput, "a system participant type"); + protected static Try checkType( + SystemParticipantTypeInput systemParticipantTypeInput) { + try { + checkNonNull(systemParticipantTypeInput, "a system participant type"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipantTypeInput + + "} was null", + e)); + } + + List exceptions = new ArrayList<>(); + 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); + || (systemParticipantTypeInput.getsRated() == null)) { + exceptions.add( + new InvalidEntityException( + "At least one of capex, opex, or sRated is null", systemParticipantTypeInput)); + } + + Try negative = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] { + systemParticipantTypeInput.getCapex(), + systemParticipantTypeInput.getOpex(), + systemParticipantTypeInput.getsRated() + }, + systemParticipantTypeInput)); + + Try ratedPF = + Try.apply( + () -> + checkRatedPowerFactor( + systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated())); + Try type; + + if (BmTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkBmType((BmTypeInput) systemParticipantTypeInput); + } else if (ChpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkChpType((ChpTypeInput) systemParticipantTypeInput); + } else if (EvTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkEvType((EvTypeInput) systemParticipantTypeInput); + } else if (HpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkHpType((HpTypeInput) systemParticipantTypeInput); + } else if (StorageTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkStorageType((StorageTypeInput) systemParticipantTypeInput); + } else if (WecTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { + type = checkWecType((WecTypeInput) systemParticipantTypeInput); + } else { + type = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", + checkNotImplementedException(systemParticipantTypeInput))); + } + + exceptions.addAll( + Stream.of(negative, ratedPF, type).filter(Try::isFailure).map(Try::getException).toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -129,10 +219,31 @@ private static void checkBm(BmInput bmInput) { * - its efficiency of assets inverter is between 0% and 100% * * @param bmTypeInput BmTypeInput to validate + * @return a try object 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 Try checkBmType(BmTypeInput bmTypeInput) { + Try negative = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput)); + Try betweenZero = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter")); + + List exceptions = + Stream.of(negative, betweenZero).filter(Try::isFailure).map(Try::getException).toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -154,13 +265,43 @@ private static void checkChp(ChpInput chpInput) { * - its needed self-consumption is not negative * * @param chpTypeInput ChpTypeInput to validate + * @return a try object 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 Try checkChpType(ChpTypeInput chpTypeInput) { + Try negative = + Try.apply( + () -> + detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput)); + Try zeroOrNegative = + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput)); + Try betweenZero = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency")); + Try betweenZero2 = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency")); + + List exceptions = + Stream.of(negative, zeroOrNegative, betweenZero, betweenZero2) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -180,10 +321,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.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, + evTypeInput)); } /** @@ -192,10 +337,29 @@ private static void checkEvType(EvTypeInput evTypeInput) { * - its rated power factor is between 0 and 1 * * @param fixedFeedInInput FixedFeedInInput to validate + * @return a try object 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 Try checkFixedFeedIn( + FixedFeedInInput fixedFeedInInput) { + Try negative = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput)); + Try ratedPF = + Try.apply(() -> checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated())); + + List exceptions = + Stream.of(negative, ratedPF).filter(Try::isFailure).map(Try::getException).toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -214,9 +378,13 @@ 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.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput)); } /** @@ -227,13 +395,36 @@ private static void checkHpType(HpTypeInput hpTypeInput) { * - its rated power factor is between 0 and 1 * * @param loadInput LoadInput to validate + * @return a try object 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 Try checkLoad(LoadInput loadInput) { + List exceptions = new ArrayList<>(); + + if (loadInput.getLoadProfile() == null) { + exceptions.add( + new InvalidEntityException("No standard load profile defined for load", loadInput)); + } + + Try negative = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, + loadInput)); + Try ratedPF = + Try.apply(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated())); + + exceptions.addAll( + Stream.of(negative, ratedPF).filter(Try::isFailure).map(Try::getException).toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -246,14 +437,37 @@ private static void checkLoad(LoadInput loadInput) { * - its rated power factor is between 0 and 1 * * @param pvInput PvInput to validate + * @return a try object 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 Try checkPv(PvInput pvInput) { + Try negative = + Try.apply(() -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)); + Try albedo = Try.apply(() -> checkAlbedo(pvInput)); + Try azimuth = Try.apply(() -> checkAzimuth(pvInput)); + Try betweenZero = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + pvInput, pvInput.getEtaConv(), "Efficiency of the converter")); + Try elevationAngle = + Try.apply(() -> checkElevationAngle(pvInput)); + Try ratedPF = + Try.apply(() -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated())); + + List exceptions = + Stream.of(negative, albedo, azimuth, betweenZero, elevationAngle, ratedPF) + .filter(Try::isFailure) + .map(Try::getException) + .toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -324,25 +538,63 @@ private static void checkStorage(StorageInput storageInput) { * - its permissible hours of full use is not negative * * @param storageTypeInput StorageTypeInput to validate + * @return a try object 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 Try checkStorageType( + StorageTypeInput storageTypeInput) { + List exceptions = new ArrayList<>(); + + if (storageTypeInput.getLifeCycle() < 0) { + exceptions.add( + new InvalidEntityException( + "Permissible amount of life cycles of the storage type must be zero or positive", + storageTypeInput)); + } + + Try betweenZero = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + storageTypeInput, + storageTypeInput.getEta(), + "Efficiency of the electrical converter")); + Try betweenZero2 = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + storageTypeInput, + storageTypeInput.getDod(), + "Maximum permissible depth of discharge")); + Try betweenZero3 = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] { + storageTypeInput.getpMax(), + storageTypeInput.getActivePowerGradient(), + storageTypeInput.getLifeTime() + }, + storageTypeInput)); + Try betweenZero4 = + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput)); + + exceptions.addAll( + Stream.of(betweenZero, betweenZero2, betweenZero3, betweenZero4) + .filter(Try::isFailure) + .map(Try::getException) + .toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -363,12 +615,32 @@ private static void checkWec(WecInput wecInput) { * - its height of the rotor hub is not negative * * @param wecTypeInput WecTypeInput to validate + * @return a try object 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 Try checkWecType(WecTypeInput wecTypeInput) { + Try betweenZero = + Try.apply( + () -> + isBetweenZeroAndHundredPercent( + wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter")); + Try betweenZero2 = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {wecTypeInput.getRotorArea(), wecTypeInput.getHubHeight()}, + wecTypeInput)); + + List exceptions = + Stream.of(betweenZero, betweenZero2).filter(Try::isFailure).map(Try::getException).toList(); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** Validates a EvcsInput */ 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..91ca53c09 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -6,7 +6,15 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.thermal.*; +import edu.ie3.datamodel.utils.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import javax.measure.Quantity; public class ThermalUnitValidationUtils extends ValidationUtils { @@ -23,17 +31,33 @@ 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 try object either containing an {@link ValidationException} or an empty Success */ - protected static void check(ThermalUnitInput thermalUnitInput) { - checkNonNull(thermalUnitInput, "a thermal unit"); + protected static Try check(ThermalUnitInput thermalUnitInput) { + try { + checkNonNull(thermalUnitInput, "a thermal unit"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + thermalUnitInput + "} was null", + e)); + } + + Try thermal; // 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())) { + thermal = checkThermalSink((ThermalSinkInput) thermalUnitInput); + } else if (ThermalStorageInput.class.isAssignableFrom(thermalUnitInput.getClass())) { + thermal = checkThermalStorage((ThermalStorageInput) thermalUnitInput); + } else { + thermal = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(thermalUnitInput))); + } + + return thermal; } /** @@ -43,15 +67,32 @@ 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 try object either containing an {@link ValidationException} or an empty Success */ - private static void checkThermalSink(ThermalSinkInput thermalSinkInput) { - checkNonNull(thermalSinkInput, "a thermal sink"); + private static Try checkThermalSink( + ThermalSinkInput thermalSinkInput) { + try { + checkNonNull(thermalSinkInput, "a thermal sink"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + thermalSinkInput + "} was null", + e)); + } + + Try thermal; // Further checks for subclasses - if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) - checkThermalHouse((ThermalHouseInput) thermalSinkInput); - else throw checkNotImplementedException(thermalSinkInput); + if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) { + thermal = checkThermalHouse((ThermalHouseInput) thermalSinkInput); + } else { + thermal = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(thermalSinkInput))); + } + + return thermal; } /** @@ -61,15 +102,34 @@ 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 try object either containing an {@link ValidationException} or an empty Success */ - private static void checkThermalStorage(ThermalStorageInput thermalStorageInput) { - checkNonNull(thermalStorageInput, "a thermal storage"); + private static Try checkThermalStorage( + ThermalStorageInput thermalStorageInput) { + try { + checkNonNull(thermalStorageInput, "a thermal storage"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalStorageInput + + "} was null", + e)); + } + + Try thermal; // Further checks for subclasses - if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) - checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput); - else throw checkNotImplementedException(thermalStorageInput); + if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) { + thermal = checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput); + } else { + thermal = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(thermalStorageInput))); + } + + return thermal; } /** @@ -81,22 +141,58 @@ private static void checkThermalStorage(ThermalStorageInput thermalStorageInput) * - its target temperature lies between the upper und lower limit temperatures * * @param thermalHouseInput ThermalHouseInput to validate + * @return a try object either containing an {@link ValidationException} 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 Try checkThermalHouse( + ThermalHouseInput thermalHouseInput) { + try { + checkNonNull(thermalHouseInput, "a thermal house"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalHouseInput + + "} was null", + e)); + } + + List exceptions = new ArrayList<>(); + + Try negative = + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput)); + + Try zeroOrNegative = + Try.apply( + () -> + 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 InvalidEntityException( + "Target temperature must be higher than lower temperature limit and lower than upper temperature limit", + thermalHouseInput)); + } + + exceptions.addAll( + Stream.of(negative, zeroOrNegative).filter(Try::isFailure).map(Try::getException).toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -109,27 +205,59 @@ private static void checkThermalHouse(ThermalHouseInput thermalHouseInput) { * - its specific heat capacity is positive * * @param cylindricalStorageInput CylindricalStorageInput to validate + * @return a try object either containing an {@link ValidationException} or an empty Success */ - private static void checkCylindricalStorage(CylindricalStorageInput cylindricalStorageInput) { - checkNonNull(cylindricalStorageInput, "a cylindrical storage"); + private static Try checkCylindricalStorage( + CylindricalStorageInput cylindricalStorageInput) { + try { + checkNonNull(cylindricalStorageInput, "a cylindrical storage"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + cylindricalStorageInput + + "} was null", + e)); + } + + 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( + 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( + new InvalidEntityException( + "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", + cylindricalStorageInput)); + + Try zeroOrNegative = + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + cylindricalStorageInput.getStorageVolumeLvl(), + cylindricalStorageInput.getStorageVolumeLvlMin(), + cylindricalStorageInput.getC() + }, + cylindricalStorageInput)); + + exceptions.addAll( + Stream.of(zeroOrNegative).filter(Try::isFailure).map(Try::getException).toList()); + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } } 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 b478ab577..56d4e3961 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -20,6 +20,10 @@ 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.ExceptionUtils; +import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; +import edu.ie3.datamodel.utils.options.Try; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @@ -57,18 +61,40 @@ 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 + * @return a try object either containing a {@link ValidationException} or an empty Success */ - 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 Try check(Object obj) { + try { + checkNonNull(obj, "an object"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + obj + "} was null", e)); + } + + Try check; + + if (AssetInput.class.isAssignableFrom(obj.getClass())) { + check = checkAsset((AssetInput) obj); + } else if (GridContainer.class.isAssignableFrom(obj.getClass())) { + check = GridContainerValidationUtils.check((GridContainer) obj); + } else if (GraphicInput.class.isAssignableFrom(obj.getClass())) { + check = GraphicValidationUtils.check((GraphicInput) obj); + } else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) { + check = checkAssetType((AssetTypeInput) obj); + } else { + check = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(obj))); + } + + if (check.isFailure()) { + return new Failure<>( + new FailedValidationException("Validation failed due to: ", check.getException())); + } else { + return Success.empty(); + } } /** @@ -81,13 +107,26 @@ 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 try object 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); + private static Try checkAsset(AssetInput assetInput) { + try { + checkNonNull(assetInput, "an asset"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + assetInput + "} was null", e)); + } + + List exceptions = new ArrayList<>(); + + if (assetInput.getId() == null) { + exceptions.add(new InvalidEntityException("No ID assigned", assetInput)); + } + if (assetInput.getOperationTime() == null) { + exceptions.add( + 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 @@ -101,24 +140,45 @@ private static void checkAsset(AssetInput assetInput) { .ifPresent( startDate -> { if (endDate.isBefore(startDate)) - throw new InvalidEntityException( - "Operation start time of the asset has to be before end time", - assetInput); + exceptions.add( + new InvalidEntityException( + "Operation start time of the asset has to be before end time", + assetInput)); })); } + Try check; + // Further checks for subclasses if (NodeInput.class.isAssignableFrom(assetInput.getClass())) - NodeValidationUtils.check((NodeInput) assetInput); + check = NodeValidationUtils.check((NodeInput) assetInput); else if (ConnectorInput.class.isAssignableFrom(assetInput.getClass())) - ConnectorValidationUtils.check((ConnectorInput) assetInput); + check = ConnectorValidationUtils.check((ConnectorInput) assetInput); else if (MeasurementUnitInput.class.isAssignableFrom(assetInput.getClass())) - MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput); + check = MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput); else if (SystemParticipantInput.class.isAssignableFrom(assetInput.getClass())) - SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput); + check = SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput); else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) - ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput); - else throw checkNotImplementedException(assetInput); + check = ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput); + else { + check = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(assetInput))); + } + + if (check.isFailure()) { + exceptions.add(check.getException()); + } + + if (exceptions.size() > 0) { + return new Failure<>( + new FailedValidationException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); + } } /** @@ -128,26 +188,57 @@ 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 try object either containing a {@link InvalidEntityException} or an empty Success */ - private static void checkAssetType(AssetTypeInput assetTypeInput) { - checkNonNull(assetTypeInput, "an asset type"); + private static Try checkAssetType(AssetTypeInput assetTypeInput) { + try { + checkNonNull(assetTypeInput, "an asset type"); + } catch (InvalidEntityException e) { + return new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + assetTypeInput + "} was null", + e)); + } + + List exceptions = new ArrayList<>(); + if (assetTypeInput.getUuid() == null) - throw new InvalidEntityException("No UUID assigned", assetTypeInput); + exceptions.add(new InvalidEntityException("No UUID assigned", assetTypeInput)); if (assetTypeInput.getId() == null) - throw new InvalidEntityException("No ID assigned", assetTypeInput); + exceptions.add(new InvalidEntityException("No ID assigned", assetTypeInput)); + + Try check; // Further checks for subclasses if (LineTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput); + check = ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput); else if (Transformer2WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput); + check = + ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput); else if (Transformer3WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput); + check = + ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput); else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput); + check = + SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput); else { - throw checkNotImplementedException(assetTypeInput); + check = + new Failure<>( + new InvalidEntityException( + "Validation failed due to: ", checkNotImplementedException(assetTypeInput))); + } + + if (check.isFailure()) { + exceptions.add(check.getException()); + } + + if (exceptions.size() > 0) { + return new Failure<>( + new InvalidEntityException( + "Validation failed due to the following exception(s): ", + new Throwable(ExceptionUtils.getMessages(exceptions)))); + } else { + return Success.empty(); } } From db202f52e0bdd4ea96c2b4819c3689c76d357c44 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 9 Mar 2023 12:42:22 +0100 Subject: [PATCH 03/39] Updating CHANGELOG. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8720ede8e..23838d696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - 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 From c145bbdf12f847e3bdc545cbe67006a5390c4b8f Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Fri, 10 Mar 2023 09:31:29 +0100 Subject: [PATCH 04/39] Improving `ValidationUtils`. --- .../exceptions/FailedValidationException.java | 15 +- .../ie3/datamodel/utils/ExceptionUtils.java | 22 +- .../validation/ConnectorValidationUtils.java | 400 +++++------- .../validation/GraphicValidationUtils.java | 46 +- .../GridContainerValidationUtils.java | 594 ++++++++---------- .../utils/validation/NodeValidationUtils.java | 40 +- .../SystemParticipantValidationUtils.java | 391 +++++------- .../ThermalUnitValidationUtils.java | 193 +++--- .../utils/validation/ValidationUtils.java | 155 ++--- .../ConnectorValidationUtilsTest.groovy | 86 +-- 10 files changed, 832 insertions(+), 1110 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java index c1e530c7d..d519d8cfc 100644 --- a/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java +++ b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java @@ -5,12 +5,19 @@ */ package edu.ie3.datamodel.exceptions; +import edu.ie3.datamodel.utils.ExceptionUtils; +import java.util.List; + public class FailedValidationException extends ValidationException { - public FailedValidationException(String s) { - super(s); + public FailedValidationException(String message, Throwable throwable) { + super(message, throwable); + } + + public FailedValidationException(String message) { + super(message); } - public FailedValidationException(String s, Throwable throwable) { - super(s, throwable); + public FailedValidationException(List exceptions) { + super("Validation failed due to: " + ExceptionUtils.getMessages(exceptions)); } } diff --git a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java index 76acc2b09..133d30a8e 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java @@ -10,28 +10,16 @@ public class 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 */ public static String getMessages(List exceptions) { - Exception firstInList = exceptions.remove(0); - return exceptions.stream() - .map(Throwable::getMessage) - .reduce(firstInList.getMessage(), (a, b) -> a + ", " + b); - } - - /** - * Creates a new {@link Exception} for multiple given exceptions. The new exception contains all - * messages of the given exceptions. - * - * @param exceptions list of exceptions - * @return new exceptions - */ - public static Exception getExceptions(List exceptions) { ArrayList list = new ArrayList<>(exceptions); - String messages = getMessages(list); - return new Exception(messages); + Exception firstInList = list.remove(0); + return list.stream() + .map(Throwable::getMessage) + .reduce(firstInList.getMessage(), (a, b) -> a + ",\n" + b); } } 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 9264b262d..3760a9166 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -6,13 +6,11 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; -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.utils.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; @@ -20,7 +18,6 @@ import edu.ie3.util.quantities.QuantityUtil; import java.util.ArrayList; import java.util.List; -import java.util.stream.Stream; import javax.measure.Quantity; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -46,48 +43,40 @@ private ConnectorValidationUtils() { * the checking task, based on the class of the given object. * * @param connector Connector to validate - * @return a try object either containing a {@link ValidationException} or an empty Success + * @return a list of try objects either containing a {@link InvalidEntityException} or an empty + * Success */ - protected static Try check(ConnectorInput connector) { + protected static List> check(ConnectorInput connector) { try { checkNonNull(connector, "a connector"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + connector + "} was null", e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + connector + "} was null", + e))); } - Try diffNodes = - Try.apply(() -> connectsDifferentNodes(connector)); - Try con; + List> exceptions = new ArrayList<>(); + exceptions.add(Try.apply(() -> connectsDifferentNodes(connector))); // Further checks for subclasses if (LineInput.class.isAssignableFrom(connector.getClass())) { - con = checkLine((LineInput) connector); + exceptions.addAll(checkLine((LineInput) connector)); } else if (Transformer2WInput.class.isAssignableFrom(connector.getClass())) { - con = checkTransformer2W((Transformer2WInput) connector); + exceptions.addAll(checkTransformer2W((Transformer2WInput) connector)); } else if (Transformer3WInput.class.isAssignableFrom(connector.getClass())) { - con = checkTransformer3W((Transformer3WInput) connector); + exceptions.addAll(checkTransformer3W((Transformer3WInput) connector)); } else if (SwitchInput.class.isAssignableFrom(connector.getClass())) { - con = checkSwitch((SwitchInput) connector); + exceptions.add(checkSwitch((SwitchInput) connector)); } else { - con = + exceptions.add( new Failure<>( new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(connector))); + "Validation failed due to: ", checkNotImplementedException(connector)))); } - List exceptions = - Stream.of(diffNodes, con).filter(Try::isFailure).map(Try::getException).toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -102,31 +91,22 @@ protected static Try check(ConnectorInput connector) * - its coordinates of start and end point equal coordinates of nodes * * @param line Line to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkLine(LineInput line) { - List exceptions = - Stream.of( - Try.apply(() -> checkLineType(line.getType())), - Try.apply(() -> connectsNodesInDifferentSubnets(line, false)), - Try.apply(() -> connectsNodesWithDifferentVoltageLevels(line, false)), - Try.apply( - () -> - detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line)), - Try.apply(() -> coordinatesOfLineEqualCoordinatesOfNodes(line)), - Try.apply(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + private static List> checkLine(LineInput line) { + List> exceptions = + new ArrayList<>(checkLineType(line.getType())); + + exceptions.add(Try.apply(() -> connectsNodesInDifferentSubnets(line, false))); + exceptions.add(Try.apply(() -> connectsNodesWithDifferentVoltageLevels(line, false))); + exceptions.add( + Try.apply( + () -> detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line))); + exceptions.add(Try.apply(() -> coordinatesOfLineEqualCoordinatesOfNodes(line))); + exceptions.add(Try.apply(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))); + + return exceptions; } /** @@ -140,45 +120,32 @@ private static Try checkLine(LineInput line) { * - vRated is greater 0 (Rated voltage) * * @param lineType Line type to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try checkLineType(LineTypeInput lineType) { + protected static List> checkLineType(LineTypeInput lineType) { try { checkNonNull(lineType, "a line type"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + lineType + "} was null", e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + lineType + "} was null", + e))); } - List exceptions = - Stream.of( - Try.apply( - () -> - detectNegativeQuantities( - new Quantity[] {lineType.getB(), lineType.getG()}, lineType)), - Try.apply( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] { - lineType.getvRated(), - lineType.getiMax(), - lineType.getX(), - lineType.getR() - }, - lineType))) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return List.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {lineType.getB(), lineType.getG()}, lineType)), + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + lineType.getvRated(), lineType.getiMax(), lineType.getX(), lineType.getR() + }, + lineType))); } /** @@ -191,29 +158,21 @@ protected static Try checkLineType(LineTypeInput l * - its rated voltages match the voltages at the nodes * * @param transformer2W Transformer2W to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkTransformer2W( + private static List> checkTransformer2W( Transformer2WInput transformer2W) { - List exceptions = - Stream.of( - Try.apply(() -> checkTransformer2WType(transformer2W.getType())), - Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer2W)), - Try.apply(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true)), - Try.apply(() -> connectsNodesInDifferentSubnets(transformer2W, true)), - Try.apply(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + List> exceptions = + new ArrayList<>(checkTransformer2WType(transformer2W.getType())); + + exceptions.add(Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer2W))); + exceptions.add(Try.apply(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true))); + exceptions.add(Try.apply(() -> connectsNodesInDifferentSubnets(transformer2W, true))); + exceptions.add( + Try.apply(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); + + return exceptions; } /** @@ -232,64 +191,50 @@ private static Try checkTransformer2W( * - minimum tap position is smaller than maximum tap position * * @param transformer2WType Transformer2W type to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try checkTransformer2WType( + protected static List> checkTransformer2WType( Transformer2WTypeInput transformer2WType) { try { checkNonNull(transformer2WType, "a two winding transformer type"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + transformer2WType - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + transformer2WType + + "} was null", + e))); } - List exceptions = - Stream.of( - Try.apply( - () -> - detectNegativeQuantities( - new Quantity[] { - transformer2WType.getgM(), - transformer2WType.getdPhi(), - transformer2WType.getrSc() - }, - transformer2WType)), - Try.apply( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] { - transformer2WType.getsRated(), - transformer2WType.getvRatedA(), - transformer2WType.getvRatedB(), - transformer2WType.getxSc() - }, - transformer2WType)), - Try.apply( - () -> - detectPositiveQuantities( - new Quantity[] {transformer2WType.getbM()}, transformer2WType)), - Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), - Try.apply( - () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), - Try.apply( - () -> - checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return List.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] { + transformer2WType.getgM(), + transformer2WType.getdPhi(), + transformer2WType.getrSc() + }, + transformer2WType)), + Try.apply( + () -> + detectZeroOrNegativeQuantities( + new Quantity[] { + transformer2WType.getsRated(), + transformer2WType.getvRatedA(), + transformer2WType.getvRatedB(), + transformer2WType.getxSc() + }, + transformer2WType)), + Try.apply( + () -> + detectPositiveQuantities( + new Quantity[] {transformer2WType.getbM()}, transformer2WType)), + Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), + Try.apply(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), + Try.apply(() -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))); } /** @@ -302,50 +247,39 @@ protected static Try checkTransformer2WType( * - its rated voltages match the voltages at the nodes * * @param transformer3W Transformer3W to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkTransformer3W( + private static List> checkTransformer3W( Transformer3WInput transformer3W) { - List exceptions = - new ArrayList<>( - Stream.of( - Try.apply(() -> checkTransformer3WType(transformer3W.getType())), - Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer3W))) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + List> exceptions = + new ArrayList<>(checkTransformer3WType(transformer3W.getType())); + + exceptions.add(Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer3W))); // 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()) { exceptions.add( - new InvalidEntityException( - "Transformer connects nodes of the same voltage level", transformer3W)); + new Failure<>( + 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()) { exceptions.add( - new InvalidEntityException( - "Transformer connects nodes in the same subnet", transformer3W)); + new Failure<>( + new InvalidEntityException( + "Transformer connects nodes in the same subnet", transformer3W))); } - Try ratedVoltage = - Try.apply(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W)); - if (ratedVoltage.isFailure()) { - exceptions.add(ratedVoltage.getException()); - } + exceptions.add( + Try.apply(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W))); - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -363,70 +297,54 @@ private static Try checkTransformer3W( * - minimum tap position is smaller than maximum tap position
* * @param transformer3WType Transformer type to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try checkTransformer3WType( + protected static List> checkTransformer3WType( Transformer3WTypeInput transformer3WType) { try { checkNonNull(transformer3WType, "a three winding transformer type"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + transformer3WType - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + transformer3WType + + "} was null", + e))); } - List exceptions = - Stream.of( - Try.apply( - () -> - detectNegativeQuantities( - new Quantity[] { - transformer3WType.getgM(), transformer3WType.getdPhi() - }, - transformer3WType)), - Try.apply( - () -> - 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)), - Try.apply( - () -> - detectPositiveQuantities( - new Quantity[] {transformer3WType.getbM()}, transformer3WType)), - Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), - Try.apply( - () -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), - Try.apply( - () -> - checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return List.of( + Try.apply( + () -> + detectNegativeQuantities( + new Quantity[] {transformer3WType.getgM(), transformer3WType.getdPhi()}, + transformer3WType)), + Try.apply( + () -> + 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)), + Try.apply( + () -> + detectPositiveQuantities( + new Quantity[] {transformer3WType.getbM()}, transformer3WType)), + Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), + Try.apply(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), + Try.apply(() -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))); } /** 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 4ab789ce7..dc6fdbdb0 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -9,12 +9,10 @@ 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.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; +import java.util.ArrayList; import java.util.List; -import java.util.stream.Stream; public class GraphicValidationUtils extends ValidationUtils { @@ -32,51 +30,37 @@ private GraphicValidationUtils() { * fulfill the checking task, based on the class of the given object. * * @param graphicInput GraphicInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try check(GraphicInput graphicInput) { + protected static List> check(GraphicInput graphicInput) { try { checkNonNull(graphicInput, "a graphic input"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + graphicInput + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + graphicInput + "} was null", + e))); } - Try layer; + List> exceptions = new ArrayList<>(); if (graphicInput.getGraphicLayer() == null) { - layer = + exceptions.add( new Failure<>( new InvalidEntityException( - "Graphic Layer of graphic element is not defined", graphicInput)); - } else { - layer = Success.empty(); + "Graphic Layer of graphic element is not defined", graphicInput))); } - Try graphic; - // Further checks for subclasses if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - graphic = Try.apply(() -> checkLineGraphicInput((LineGraphicInput) graphicInput)); + exceptions.add(Try.apply(() -> checkLineGraphicInput((LineGraphicInput) graphicInput))); } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - graphic = Try.apply(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput)); - } else { - graphic = Success.empty(); + exceptions.add(Try.apply(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput))); } - List exceptions = - Stream.of(layer, graphic).filter(Try::isFailure).map(Try::getException).toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** 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 107af46db..d67d3c110 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -5,7 +5,6 @@ */ package edu.ie3.datamodel.utils.validation; -import edu.ie3.datamodel.exceptions.FailedValidationException; import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.exceptions.ValidationException; @@ -18,9 +17,7 @@ import edu.ie3.datamodel.models.input.container.*; import edu.ie3.datamodel.models.input.system.SystemParticipantInput; import edu.ie3.datamodel.utils.ContainerUtils; -import edu.ie3.datamodel.utils.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; import java.util.*; import java.util.stream.Stream; @@ -44,55 +41,47 @@ private GridContainerValidationUtils() { * Checks a complete grid data container * * @param gridContainer Grid model to check - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try check(GridContainer gridContainer) { + protected static List> check( + GridContainer gridContainer) { try { checkNonNull(gridContainer, "grid container"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + gridContainer + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + gridContainer + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(gridContainer.allEntitiesAsList())); if (exceptionString.isPresent()) { exceptions.add( - new InvalidGridException( - duplicateUuidsString(gridContainer.getClass().getSimpleName(), exceptionString))); + new Failure<>( + new InvalidGridException( + duplicateUuidsString( + gridContainer.getClass().getSimpleName(), exceptionString)))); } - Try rawGridElements = - checkRawGridElements(gridContainer.getRawGrid()); - - Try systemParticipants = + exceptions.addAll(checkRawGridElements(gridContainer.getRawGrid())); + exceptions.addAll( checkSystemParticipants( - gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes()); - Try graphicElements = + gridContainer.getSystemParticipants(), gridContainer.getRawGrid().getNodes())); + exceptions.addAll( checkGraphicElements( gridContainer.getGraphics(), gridContainer.getRawGrid().getNodes(), - gridContainer.getRawGrid().getLines()); - - exceptions.addAll( - Stream.of(rawGridElements, systemParticipants, graphicElements) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + gridContainer.getRawGrid().getLines())); - if (exceptions.size() > 0) { - return new Failure<>( - new FailedValidationException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -100,28 +89,34 @@ protected static Try check(GridContainer gridContaine * 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 - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try checkRawGridElements( + protected static List> checkRawGridElements( RawGridElements rawGridElements) { try { checkNonNull(rawGridElements, "raw grid elements"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + rawGridElements + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + rawGridElements + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(rawGridElements.allEntitiesAsList())); if (exceptionString.isPresent()) { exceptions.add( - new InvalidGridException( - duplicateUuidsString(rawGridElements.getClass().getSimpleName(), exceptionString))); + new Failure<>( + new InvalidGridException( + duplicateUuidsString( + rawGridElements.getClass().getSimpleName(), exceptionString)))); } /* Checking nodes */ @@ -129,52 +124,43 @@ protected static Try checkRawGridElements( nodes.forEach(NodeValidationUtils::check); /* Checking lines */ - exceptions.addAll( - rawGridElements.getLines().stream() - .map( - line -> { - try { - checkNodeAvailability(line, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return ConnectorValidationUtils.check(line); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + rawGridElements + .getLines() + .forEach( + line -> { + try { + checkNodeAvailability(line, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(ConnectorValidationUtils.check(line)); + }); /* Checking two winding transformers */ - exceptions.addAll( - rawGridElements.getTransformer2Ws().stream() - .map( - transformer -> { - try { - checkNodeAvailability(transformer, nodes); - } catch (InvalidGridException e) { - return new Failure<>(e); - } - return ConnectorValidationUtils.check(transformer); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + rawGridElements + .getTransformer2Ws() + .forEach( + transformer -> { + try { + checkNodeAvailability(transformer, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(ConnectorValidationUtils.check(transformer)); + }); /* Checking three winding transformers */ - exceptions.addAll( - rawGridElements.getTransformer3Ws().stream() - .map( - transformer -> { - try { - checkNodeAvailability(transformer, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return ConnectorValidationUtils.check(transformer); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + rawGridElements + .getTransformer3Ws() + .forEach( + transformer -> { + try { + checkNodeAvailability(transformer, nodes); + } catch (ValidationException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(ConnectorValidationUtils.check(transformer)); + }); /* Checking switches * Because of the fact, that a transformer with switch gear in "upstream" direction has it's corresponding node in @@ -191,45 +177,32 @@ protected static Try checkRawGridElements( .getLast()) .toList()); - exceptions.addAll( - rawGridElements.getSwitches().stream() - .map( - switcher -> { - try { - checkNodeAvailability(switcher, validSwitchNodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return ConnectorValidationUtils.check(switcher); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + rawGridElements + .getSwitches() + .forEach( + switcher -> { + try { + checkNodeAvailability(switcher, validSwitchNodes); + } catch (ValidationException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(ConnectorValidationUtils.check(switcher)); + }); /* Checking measurement units */ - exceptions.addAll( - rawGridElements.getMeasurementUnits().stream() - .map( - measurement -> { - try { - checkNodeAvailability(measurement, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return MeasurementUnitValidationUtils.check(measurement); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new FailedValidationException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + rawGridElements + .getMeasurementUnits() + .forEach( + measurement -> { + try { + checkNodeAvailability(measurement, nodes); + } catch (ValidationException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.add(MeasurementUnitValidationUtils.check(measurement)); + }); + + return exceptions; } /** @@ -238,22 +211,24 @@ protected static Try checkRawGridElements( * * @param systemParticipants The system participants * @param nodes Set of already known nodes - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try checkSystemParticipants( + protected static List> checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { try { checkNonNull(systemParticipants, "system participants"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipants - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipants + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = @@ -261,142 +236,112 @@ protected static Try checkSystemParticipants( new HashSet<>(systemParticipants.allEntitiesAsList())); if (exceptionString.isPresent()) { exceptions.add( - new InvalidGridException( - duplicateUuidsString( - systemParticipants.getClass().getSimpleName(), exceptionString))); + new Failure<>( + new InvalidGridException( + duplicateUuidsString( + systemParticipants.getClass().getSimpleName(), exceptionString)))); } - exceptions.addAll( - systemParticipants.getBmPlants().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getChpPlants().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); + systemParticipants + .getBmPlants() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getChpPlants() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); /* TODO: Electric vehicle charging systems are currently only dummy implementation. if this has changed, the whole * method can be aggregated */ - exceptions.addAll( - systemParticipants.getFixedFeedIns().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getHeatPumps().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getLoads().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getPvPlants().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getStorages().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - systemParticipants.getWecPlants().stream() - .map( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (ValidationException e) { - return new Failure<>(e); - } - return SystemParticipantValidationUtils.check(entity); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new FailedValidationException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + systemParticipants + .getFixedFeedIns() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getHeatPumps() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getLoads() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getPvPlants() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getStorages() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + systemParticipants + .getWecPlants() + .forEach( + entity -> { + try { + checkNodeAvailability(entity, nodes); + } catch (InvalidGridException e) { + exceptions.add(new Failure<>(e)); + } + exceptions.addAll(SystemParticipantValidationUtils.check(entity)); + }); + + return exceptions; } /** @@ -405,90 +350,81 @@ protected static Try checkSystemParticipants( * @param graphicElements Elements to check * @param nodes Already known and checked nodes * @param lines Already known and checked lines - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try checkGraphicElements( + protected static List> checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { try { checkNonNull(graphicElements, "graphic elements"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + graphicElements + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + graphicElements + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = checkForDuplicateUuids(new HashSet<>(graphicElements.allEntitiesAsList())); if (exceptionString.isPresent()) { exceptions.add( - new InvalidGridException( - duplicateUuidsString(graphicElements.getClass().getSimpleName(), exceptionString))); + new Failure<>( + new InvalidGridException( + duplicateUuidsString( + graphicElements.getClass().getSimpleName(), exceptionString)))); } - exceptions.addAll( - (Collection) - graphicElements.getNodeGraphics().stream() - .map( - graphic -> { - try { - GraphicValidationUtils.check(graphic); - } catch (InvalidEntityException e) { - return new Failure<>(e); - } - if (!nodes.contains(graphic.getNode())) { - return new Failure<>( - 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)); - } - return Success.empty(); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - exceptions.addAll( - (Collection) - graphicElements.getLineGraphics().stream() - .map( - graphic -> { - try { - GraphicValidationUtils.check(graphic); - } catch (InvalidEntityException e) { - return new Failure<>(e); - } - if (!lines.contains(graphic.getLine())) { - return new Failure<>( - 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)); - } - return Success.empty(); - }) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new FailedValidationException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + graphicElements + .getNodeGraphics() + .forEach( + graphic -> { + try { + GraphicValidationUtils.check(graphic); + } catch (InvalidEntityException e) { + exceptions.add(new Failure<>(e)); + } + if (!nodes.contains(graphic.getNode())) { + exceptions.add( + new Failure<>( + 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))); + } + }); + + graphicElements + .getLineGraphics() + .forEach( + graphic -> { + try { + GraphicValidationUtils.check(graphic); + } catch (InvalidEntityException e) { + exceptions.add(new Failure<>(e)); + } + if (!lines.contains(graphic.getLine())) { + exceptions.add( + new Failure<>( + 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))); + } + }); + + return exceptions; } /** 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 b6488a540..9d011bfba 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -10,8 +10,9 @@ import edu.ie3.datamodel.models.input.NodeInput; import edu.ie3.datamodel.models.voltagelevels.VoltageLevel; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; +import java.util.ArrayList; +import java.util.List; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; @@ -31,41 +32,50 @@ private NodeValidationUtils() { * - geoPosition is not null * * @param node Node to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try check(NodeInput node) { + protected static List> check(NodeInput node) { try { checkNonNull(node, "a node"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + node + "} was null", e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + node + "} was null", e))); } + List> exceptions = new ArrayList<>(); + try { checkVoltageLevel(node.getVoltLvl()); } catch (VoltageLevelException e) { - return new Failure<>(new InvalidEntityException("Node has invalid voltage level", node)); + exceptions.add( + new Failure<>(new InvalidEntityException("Node has invalid voltage level", node))); } catch (InvalidEntityException invalidEntityException) { - return new Failure<>(invalidEntityException); + exceptions.add(new Failure<>(invalidEntityException)); } if (node.getvTarget() .isLessThanOrEqualTo(Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { - return new Failure<>( - new InvalidEntityException("Target voltage (p.u.) is not a positive value", node)); + exceptions.add( + new Failure<>( + new InvalidEntityException("Target voltage (p.u.) is not a positive value", node))); } else if (node.getvTarget() .isGreaterThan(Quantities.getQuantity(2, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { - return new Failure<>( - new UnsafeEntityException("Target voltage (p.u.) might be too high", node)); + exceptions.add( + new Failure<>( + new UnsafeEntityException("Target voltage (p.u.) might be too high", node))); } if (node.getSubnet() <= 0) - return new Failure<>(new InvalidEntityException("Subnet can't be zero or negative", node)); + exceptions.add( + new Failure<>(new InvalidEntityException("Subnet can't be zero or negative", node))); if (node.getGeoPosition() == null) { - return new Failure<>(new InvalidEntityException("GeoPosition of node is null", node)); + exceptions.add( + new Failure<>(new InvalidEntityException("GeoPosition of node is null", node))); } - return Success.empty(); + return exceptions; } /** 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 5f5dd9762..29aabcb05 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -9,17 +9,13 @@ import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.NotImplementedException; -import edu.ie3.datamodel.exceptions.ValidationException; 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.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; import java.util.ArrayList; import java.util.List; -import java.util.stream.Stream; import javax.measure.Quantity; import javax.measure.quantity.Dimensionless; import tech.units.indriya.ComparableQuantity; @@ -42,76 +38,62 @@ private SystemParticipantValidationUtils() { * fulfill the checking task, based on the class of the given object. * * @param systemParticipant systemParticipant to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try check(SystemParticipantInput systemParticipant) { + protected static List> check( + SystemParticipantInput systemParticipant) { try { checkNonNull(systemParticipant, "a system participant"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipant - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipant + + "} was null", + e))); } - Try qCharacteristic; + List> exceptions = new ArrayList<>(); if (systemParticipant.getqCharacteristics() == null) { - qCharacteristic = + exceptions.add( new Failure<>( new InvalidEntityException( "Reactive power characteristics of system participant is not defined", - systemParticipant)); - } else { - qCharacteristic = Success.empty(); + systemParticipant))); } - Try participant; - // Further checks for subclasses if (BmInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkBm((BmInput) systemParticipant)); + exceptions.addAll(checkBm((BmInput) systemParticipant)); } else if (ChpInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkChp((ChpInput) systemParticipant)); + exceptions.addAll(checkChp((ChpInput) systemParticipant)); } else if (EvInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkEv((EvInput) systemParticipant)); + exceptions.addAll(checkEv((EvInput) systemParticipant)); } else if (FixedFeedInInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = checkFixedFeedIn((FixedFeedInInput) systemParticipant); + exceptions.addAll(checkFixedFeedIn((FixedFeedInInput) systemParticipant)); } else if (HpInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkHp((HpInput) systemParticipant)); + exceptions.addAll(checkHp((HpInput) systemParticipant)); } else if (LoadInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = checkLoad((LoadInput) systemParticipant); + exceptions.addAll(checkLoad((LoadInput) systemParticipant)); } else if (PvInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = checkPv((PvInput) systemParticipant); + exceptions.addAll(checkPv((PvInput) systemParticipant)); } else if (StorageInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkStorage((StorageInput) systemParticipant)); + exceptions.addAll(checkStorage((StorageInput) systemParticipant)); } else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(() -> checkWec((WecInput) systemParticipant)); + exceptions.addAll(checkWec((WecInput) systemParticipant)); } else if (EvcsInput.class.isAssignableFrom(systemParticipant.getClass())) { - participant = Try.apply(SystemParticipantValidationUtils::checkEvcs); + exceptions.add(Try.apply(SystemParticipantValidationUtils::checkEvcs)); } else { - participant = + exceptions.add( new Failure<>( new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(systemParticipant))); + "Validation failed due to: ", checkNotImplementedException(systemParticipant)))); } - List exceptions = - Stream.of(qCharacteristic, participant) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -126,32 +108,35 @@ protected static Try check(SystemParticipantInput sys * fulfill the checking task, based on the class of the given object. * * @param systemParticipantTypeInput systemParticipant Type to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - protected static Try checkType( + protected static List> checkType( SystemParticipantTypeInput systemParticipantTypeInput) { try { checkNonNull(systemParticipantTypeInput, "a system participant type"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipantTypeInput - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + systemParticipantTypeInput + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if ((systemParticipantTypeInput.getCapex() == null) || (systemParticipantTypeInput.getOpex() == null) || (systemParticipantTypeInput.getsRated() == null)) { exceptions.add( - new InvalidEntityException( - "At least one of capex, opex, or sRated is null", systemParticipantTypeInput)); + new Failure<>( + new InvalidEntityException( + "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); } - Try negative = + exceptions.add( Try.apply( () -> detectNegativeQuantities( @@ -160,46 +145,35 @@ protected static Try checkType( systemParticipantTypeInput.getOpex(), systemParticipantTypeInput.getsRated() }, - systemParticipantTypeInput)); + systemParticipantTypeInput))); - Try ratedPF = + exceptions.add( Try.apply( () -> checkRatedPowerFactor( - systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated())); - Try type; + systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated()))); if (BmTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkBmType((BmTypeInput) systemParticipantTypeInput); + exceptions.addAll(checkBmType((BmTypeInput) systemParticipantTypeInput)); } else if (ChpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkChpType((ChpTypeInput) systemParticipantTypeInput); + exceptions.addAll(checkChpType((ChpTypeInput) systemParticipantTypeInput)); } else if (EvTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkEvType((EvTypeInput) systemParticipantTypeInput); + exceptions.add(checkEvType((EvTypeInput) systemParticipantTypeInput)); } else if (HpTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkHpType((HpTypeInput) systemParticipantTypeInput); + exceptions.add(checkHpType((HpTypeInput) systemParticipantTypeInput)); } else if (StorageTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkStorageType((StorageTypeInput) systemParticipantTypeInput); + exceptions.addAll(checkStorageType((StorageTypeInput) systemParticipantTypeInput)); } else if (WecTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { - type = checkWecType((WecTypeInput) systemParticipantTypeInput); + exceptions.addAll(checkWecType((WecTypeInput) systemParticipantTypeInput)); } else { - type = + exceptions.add( new Failure<>( new InvalidEntityException( "Validation failed due to: ", - checkNotImplementedException(systemParticipantTypeInput))); + checkNotImplementedException(systemParticipantTypeInput)))); } - exceptions.addAll( - Stream.of(negative, ratedPF, type).filter(Try::isFailure).map(Try::getException).toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -208,9 +182,11 @@ protected static Try checkType( * 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()); } /** @@ -219,31 +195,19 @@ private static void checkBm(BmInput bmInput) { * - its efficiency of assets inverter is between 0% and 100% * * @param bmTypeInput BmTypeInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkBmType(BmTypeInput bmTypeInput) { - Try negative = + private static List> checkBmType(BmTypeInput bmTypeInput) { + return List.of( Try.apply( () -> detectNegativeQuantities( - new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput)); - Try betweenZero = + new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput)), Try.apply( () -> isBetweenZeroAndHundredPercent( - bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter")); - - List exceptions = - Stream.of(negative, betweenZero).filter(Try::isFailure).map(Try::getException).toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter"))); } /** @@ -252,9 +216,11 @@ private static Try checkBmType(BmTypeInput bmTypeI * 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()); } /** @@ -265,43 +231,26 @@ private static void checkChp(ChpInput chpInput) { * - its needed self-consumption is not negative * * @param chpTypeInput ChpTypeInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkChpType(ChpTypeInput chpTypeInput) { - Try negative = + private static List> checkChpType(ChpTypeInput chpTypeInput) { + return List.of( Try.apply( () -> - detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput)); - Try zeroOrNegative = + detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput)), Try.apply( () -> detectZeroOrNegativeQuantities( - new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput)); - Try betweenZero = + new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput)), Try.apply( () -> isBetweenZeroAndHundredPercent( - chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency")); - Try betweenZero2 = + chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency")), Try.apply( () -> isBetweenZeroAndHundredPercent( - chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency")); - - List exceptions = - Stream.of(negative, zeroOrNegative, betweenZero, betweenZero2) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency"))); } /** @@ -310,9 +259,11 @@ private static Try checkChpType(ChpTypeInput chpTy * 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()); } /** @@ -337,29 +288,18 @@ private static Try checkEvType(EvTypeInput evTypeI * - its rated power factor is between 0 and 1 * * @param fixedFeedInInput FixedFeedInInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkFixedFeedIn( + private static List> checkFixedFeedIn( FixedFeedInInput fixedFeedInInput) { - Try negative = + return List.of( Try.apply( () -> detectNegativeQuantities( - new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput)); - Try ratedPF = - Try.apply(() -> checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated())); - - List exceptions = - Stream.of(negative, ratedPF).filter(Try::isFailure).map(Try::getException).toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput)), + Try.apply( + () -> checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated()))); } /** @@ -368,9 +308,11 @@ private static Try checkFixedFeedIn( * 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()); } /** @@ -395,36 +337,27 @@ private static Try checkHpType(HpTypeInput hpTypeI * - its rated power factor is between 0 and 1 * * @param loadInput LoadInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkLoad(LoadInput loadInput) { - List exceptions = new ArrayList<>(); + private static List> checkLoad(LoadInput loadInput) { + List> exceptions = new ArrayList<>(); if (loadInput.getLoadProfile() == null) { exceptions.add( - new InvalidEntityException("No standard load profile defined for load", loadInput)); + new Failure<>( + new InvalidEntityException("No standard load profile defined for load", loadInput))); } - Try negative = + exceptions.add( Try.apply( () -> detectNegativeQuantities( new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, - loadInput)); - Try ratedPF = - Try.apply(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated())); - - exceptions.addAll( - Stream.of(negative, ratedPF).filter(Try::isFailure).map(Try::getException).toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + loadInput))); + exceptions.add(Try.apply(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); + + return exceptions; } /** @@ -437,37 +370,20 @@ private static Try checkLoad(LoadInput loadInput) * - its rated power factor is between 0 and 1 * * @param pvInput PvInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkPv(PvInput pvInput) { - Try negative = - Try.apply(() -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)); - Try albedo = Try.apply(() -> checkAlbedo(pvInput)); - Try azimuth = Try.apply(() -> checkAzimuth(pvInput)); - Try betweenZero = + private static List> checkPv(PvInput pvInput) { + return List.of( + Try.apply(() -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)), + Try.apply(() -> checkAlbedo(pvInput)), + Try.apply(() -> checkAzimuth(pvInput)), Try.apply( () -> isBetweenZeroAndHundredPercent( - pvInput, pvInput.getEtaConv(), "Efficiency of the converter")); - Try elevationAngle = - Try.apply(() -> checkElevationAngle(pvInput)); - Try ratedPF = - Try.apply(() -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated())); - - List exceptions = - Stream.of(negative, albedo, azimuth, betweenZero, elevationAngle, ratedPF) - .filter(Try::isFailure) - .map(Try::getException) - .toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + pvInput, pvInput.getEtaConv(), "Efficiency of the converter")), + Try.apply(() -> checkElevationAngle(pvInput)), + Try.apply(() -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated()))); } /** @@ -522,9 +438,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()); } /** @@ -538,34 +456,36 @@ private static void checkStorage(StorageInput storageInput) { * - its permissible hours of full use is not negative * * @param storageTypeInput StorageTypeInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkStorageType( + private static List> checkStorageType( StorageTypeInput storageTypeInput) { - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (storageTypeInput.getLifeCycle() < 0) { exceptions.add( - new InvalidEntityException( - "Permissible amount of life cycles of the storage type must be zero or positive", - storageTypeInput)); + new Failure<>( + new InvalidEntityException( + "Permissible amount of life cycles of the storage type must be zero or positive", + storageTypeInput))); } - Try betweenZero = + exceptions.add( Try.apply( () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getEta(), - "Efficiency of the electrical converter")); - Try betweenZero2 = + "Efficiency of the electrical converter"))); + exceptions.add( Try.apply( () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getDod(), - "Maximum permissible depth of discharge")); - Try betweenZero3 = + "Maximum permissible depth of discharge"))); + exceptions.add( Try.apply( () -> detectNegativeQuantities( @@ -574,27 +494,14 @@ private static Try checkStorageType( storageTypeInput.getActivePowerGradient(), storageTypeInput.getLifeTime() }, - storageTypeInput)); - Try betweenZero4 = + storageTypeInput))); + exceptions.add( Try.apply( () -> detectZeroOrNegativeQuantities( - new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput)); - - exceptions.addAll( - Stream.of(betweenZero, betweenZero2, betweenZero3, betweenZero4) - .filter(Try::isFailure) - .map(Try::getException) - .toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput))); + + return exceptions; } /** @@ -603,9 +510,11 @@ private static Try checkStorageType( * 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()); } /** @@ -615,32 +524,20 @@ private static void checkWec(WecInput wecInput) { * - its height of the rotor hub is not negative * * @param wecTypeInput WecTypeInput to validate - * @return a try object either containing an {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkWecType(WecTypeInput wecTypeInput) { - Try betweenZero = + private static List> checkWecType(WecTypeInput wecTypeInput) { + return List.of( Try.apply( () -> isBetweenZeroAndHundredPercent( - wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter")); - Try betweenZero2 = + wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter")), Try.apply( () -> detectNegativeQuantities( new Quantity[] {wecTypeInput.getRotorArea(), wecTypeInput.getHubHeight()}, - wecTypeInput)); - - List exceptions = - Stream.of(betweenZero, betweenZero2).filter(Try::isFailure).map(Try::getException).toList(); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + wecTypeInput))); } /** Validates a EvcsInput */ 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 91ca53c09..e82699ffc 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -5,16 +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.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; import java.util.ArrayList; import java.util.List; -import java.util.stream.Stream; import javax.measure.Quantity; public class ThermalUnitValidationUtils extends ValidationUtils { @@ -31,33 +29,38 @@ private ThermalUnitValidationUtils() { * the checking task, based on the class of the given object. * * @param thermalUnitInput ThermalUnitInput to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - protected static Try check(ThermalUnitInput thermalUnitInput) { + protected static List> check( + ThermalUnitInput thermalUnitInput) { try { checkNonNull(thermalUnitInput, "a thermal unit"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + thermalUnitInput + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalUnitInput + + "} was null", + e))); } - Try thermal; + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalSinkInput.class.isAssignableFrom(thermalUnitInput.getClass())) { - thermal = checkThermalSink((ThermalSinkInput) thermalUnitInput); + exceptions.addAll(checkThermalSink((ThermalSinkInput) thermalUnitInput)); } else if (ThermalStorageInput.class.isAssignableFrom(thermalUnitInput.getClass())) { - thermal = checkThermalStorage((ThermalStorageInput) thermalUnitInput); + exceptions.addAll(checkThermalStorage((ThermalStorageInput) thermalUnitInput)); } else { - thermal = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(thermalUnitInput))); + new FailedValidationException( + "Validation failed due to: ", checkNotImplementedException(thermalUnitInput)))); } - return thermal; + return exceptions; } /** @@ -67,32 +70,36 @@ protected static Try check(ThermalUnitInput therma * the checking task, based on the class of the given object. * * @param thermalSinkInput ThermalSinkInput to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - private static Try checkThermalSink( + private static List> checkThermalSink( ThermalSinkInput thermalSinkInput) { try { checkNonNull(thermalSinkInput, "a thermal sink"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + thermalSinkInput + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalSinkInput + + "} was null", + e))); } - Try thermal; + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) { - thermal = checkThermalHouse((ThermalHouseInput) thermalSinkInput); + exceptions.addAll(checkThermalHouse((ThermalHouseInput) thermalSinkInput)); } else { - thermal = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(thermalSinkInput))); + new FailedValidationException( + "Validation failed due to: ", checkNotImplementedException(thermalSinkInput)))); } - return thermal; + return exceptions; } /** @@ -102,34 +109,37 @@ private static Try checkThermalSink( * the checking task, based on the class of the given object. * * @param thermalStorageInput ThermalStorageInput to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link ValidationException} or an empty + * Success */ - private static Try checkThermalStorage( + private static List> checkThermalStorage( ThermalStorageInput thermalStorageInput) { try { checkNonNull(thermalStorageInput, "a thermal storage"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalStorageInput - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalStorageInput + + "} was null", + e))); } - Try thermal; + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) { - thermal = checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput); + exceptions.addAll(checkCylindricalStorage((CylindricalStorageInput) thermalStorageInput)); } else { - thermal = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(thermalStorageInput))); + new FailedValidationException( + "Validation failed due to: ", + checkNotImplementedException(thermalStorageInput)))); } - return thermal; + return exceptions; } /** @@ -141,34 +151,34 @@ private static Try checkThermalStorage( * - its target temperature lies between the upper und lower limit temperatures * * @param thermalHouseInput ThermalHouseInput to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkThermalHouse( + private static List> checkThermalHouse( ThermalHouseInput thermalHouseInput) { try { checkNonNull(thermalHouseInput, "a thermal house"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalHouseInput - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + thermalHouseInput + + "} was null", + e))); } - List exceptions = new ArrayList<>(); - - Try negative = + List> exceptions = new ArrayList<>(); + exceptions.add( Try.apply( () -> detectNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput)); - - Try zeroOrNegative = + new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput))); + exceptions.add( Try.apply( () -> detectZeroOrNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput)); + new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput))); if (thermalHouseInput .getLowerTemperatureLimit() @@ -177,22 +187,13 @@ private static Try checkThermalHouse( .getUpperTemperatureLimit() .isLessThan(thermalHouseInput.getTargetTemperature())) { exceptions.add( - new InvalidEntityException( - "Target temperature must be higher than lower temperature limit and lower than upper temperature limit", - thermalHouseInput)); + new Failure<>( + new InvalidEntityException( + "Target temperature must be higher than lower temperature limit and lower than upper temperature limit", + thermalHouseInput))); } - exceptions.addAll( - Stream.of(negative, zeroOrNegative).filter(Try::isFailure).map(Try::getException).toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -205,39 +206,43 @@ private static Try checkThermalHouse( * - its specific heat capacity is positive * * @param cylindricalStorageInput CylindricalStorageInput to validate - * @return a try object either containing an {@link ValidationException} or an empty Success + * @return a list of try objects either containing an {@link InvalidEntityException} or an empty + * Success */ - private static Try checkCylindricalStorage( + private static List> checkCylindricalStorage( CylindricalStorageInput cylindricalStorageInput) { try { checkNonNull(cylindricalStorageInput, "a cylindrical storage"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + cylindricalStorageInput - + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + cylindricalStorageInput + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Check if inlet temperature is higher/equal to outlet temperature if (cylindricalStorageInput.getInletTemp().isLessThan(cylindricalStorageInput.getReturnTemp())) exceptions.add( - new InvalidEntityException( - "Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", - cylindricalStorageInput)); + new Failure<>( + 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())) exceptions.add( - new InvalidEntityException( - "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", - cylindricalStorageInput)); + new Failure<>( + new InvalidEntityException( + "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", + cylindricalStorageInput))); - Try zeroOrNegative = + exceptions.add( Try.apply( () -> detectZeroOrNegativeQuantities( @@ -246,18 +251,8 @@ private static Try checkCylindricalStorage( cylindricalStorageInput.getStorageVolumeLvlMin(), cylindricalStorageInput.getC() }, - cylindricalStorageInput)); + cylindricalStorageInput))); - exceptions.addAll( - Stream.of(zeroOrNegative).filter(Try::isFailure).map(Try::getException).toList()); - - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + 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 56d4e3961..347025340 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -20,9 +20,7 @@ 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.ExceptionUtils; import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -61,40 +59,37 @@ protected static NotImplementedException checkNotImplementedException(Object obj * fulfill the checking task, based on the class of the given object. * * @param obj Object to check - * @return a try object either containing a {@link ValidationException} or an empty Success + * @return a list of try objects either containing a {@link ValidationException} or an empty + * Success */ - public static Try check(Object obj) { + public static List> check(Object obj) { try { checkNonNull(obj, "an object"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + obj + "} was null", e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + obj + "} was null", e))); } - Try check; + List> exceptions = new ArrayList<>(); if (AssetInput.class.isAssignableFrom(obj.getClass())) { - check = checkAsset((AssetInput) obj); + exceptions.addAll(checkAsset((AssetInput) obj)); } else if (GridContainer.class.isAssignableFrom(obj.getClass())) { - check = GridContainerValidationUtils.check((GridContainer) obj); + exceptions.addAll(GridContainerValidationUtils.check((GridContainer) obj)); } else if (GraphicInput.class.isAssignableFrom(obj.getClass())) { - check = GraphicValidationUtils.check((GraphicInput) obj); + exceptions.addAll(GraphicValidationUtils.check((GraphicInput) obj)); } else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) { - check = checkAssetType((AssetTypeInput) obj); + exceptions.addAll(checkAssetType((AssetTypeInput) obj)); } else { - check = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(obj))); + new FailedValidationException( + "Validation failed due to: ", checkNotImplementedException(obj)))); } - if (check.isFailure()) { - return new Failure<>( - new FailedValidationException("Validation failed due to: ", check.getException())); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -107,25 +102,30 @@ public static Try check(Object obj) { * the checking task, based on the class of the given object. * * @param assetInput AssetInput to check - * @return a try object either containing a {@link ValidationException} or an empty Success + * @return a list of try objects either containing a {@link ValidationException} or an empty + * Success */ - private static Try checkAsset(AssetInput assetInput) { + private static List> checkAsset(AssetInput assetInput) { try { checkNonNull(assetInput, "an asset"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + assetInput + "} was null", e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + assetInput + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetInput.getId() == null) { - exceptions.add(new InvalidEntityException("No ID assigned", assetInput)); + exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput))); } if (assetInput.getOperationTime() == null) { exceptions.add( - new InvalidEntityException("Operation time of the asset is not defined", assetInput)); + new Failure<>( + 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()) { @@ -141,44 +141,33 @@ private static Try checkAsset(AssetInput assetInput) startDate -> { if (endDate.isBefore(startDate)) exceptions.add( - new InvalidEntityException( - "Operation start time of the asset has to be before end time", - assetInput)); + new Failure<>( + new InvalidEntityException( + "Operation start time of the asset has to be before end time", + assetInput))); })); } - Try check; - // Further checks for subclasses if (NodeInput.class.isAssignableFrom(assetInput.getClass())) - check = NodeValidationUtils.check((NodeInput) assetInput); + exceptions.addAll(NodeValidationUtils.check((NodeInput) assetInput)); else if (ConnectorInput.class.isAssignableFrom(assetInput.getClass())) - check = ConnectorValidationUtils.check((ConnectorInput) assetInput); + exceptions.addAll(ConnectorValidationUtils.check((ConnectorInput) assetInput)); else if (MeasurementUnitInput.class.isAssignableFrom(assetInput.getClass())) - check = MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput); + exceptions.add(MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput)); else if (SystemParticipantInput.class.isAssignableFrom(assetInput.getClass())) - check = SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput); + exceptions.addAll( + SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput)); else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) - check = ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput); + exceptions.addAll(ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput)); else { - check = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(assetInput))); + new FailedValidationException( + "Validation failed due to: ", checkNotImplementedException(assetInput)))); } - if (check.isFailure()) { - exceptions.add(check.getException()); - } - - if (exceptions.size() > 0) { - return new Failure<>( - new FailedValidationException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** @@ -188,58 +177,50 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) * the checking task, based on the class of the given object. * * @param assetTypeInput AssetTypeInput to check - * @return a try object either containing a {@link InvalidEntityException} or an empty Success + * @return a list of try objects either containing a {@link ValidationException} or an empty + * Success */ - private static Try checkAssetType(AssetTypeInput assetTypeInput) { + private static List> checkAssetType( + AssetTypeInput assetTypeInput) { try { checkNonNull(assetTypeInput, "an asset type"); } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + assetTypeInput + "} was null", - e)); + return List.of( + new Failure<>( + new InvalidEntityException( + "Validation not possible because received object {" + + assetTypeInput + + "} was null", + e))); } - List exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetTypeInput.getUuid() == null) - exceptions.add(new InvalidEntityException("No UUID assigned", assetTypeInput)); + exceptions.add(new Failure<>(new InvalidEntityException("No UUID assigned", assetTypeInput))); if (assetTypeInput.getId() == null) - exceptions.add(new InvalidEntityException("No ID assigned", assetTypeInput)); - - Try check; + exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetTypeInput))); // Further checks for subclasses if (LineTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - check = ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput); + exceptions.addAll(ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput)); else if (Transformer2WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - check = - ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput); + exceptions.addAll( + ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput)); else if (Transformer3WTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - check = - ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput); + exceptions.addAll( + ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput)); else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) - check = - SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput); + exceptions.addAll( + SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput)); else { - check = + exceptions.add( new Failure<>( - new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(assetTypeInput))); - } - - if (check.isFailure()) { - exceptions.add(check.getException()); + new FailedValidationException( + "Validation failed due to: ", checkNotImplementedException(assetTypeInput)))); } - if (exceptions.size() > 0) { - return new Failure<>( - new InvalidEntityException( - "Validation failed due to the following exception(s): ", - new Throwable(ExceptionUtils.getMessages(exceptions)))); - } else { - return Success.empty(); - } + return exceptions; } /** 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..12d493504 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -5,6 +5,8 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.utils.options.Try + import static edu.ie3.datamodel.models.StandardUnits.* import static edu.ie3.util.quantities.PowerSystemUnits.* @@ -69,22 +71,21 @@ 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 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 +114,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 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"() { @@ -158,18 +160,19 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2WType recognizes all potential errors for a transformer2W type"() { when: - ConnectorValidationUtils.check(invalidTransformer2WType) + List> exceptions = ConnectorValidationUtils.check(invalidTransformer2WType).stream().filter {it -> it.failure}.toList() then: - Exception ex = thrown() + exceptions.size() == excpectedSize + Exception ex = exceptions.get(0).exception ex.class == expectedException.class ex.message == expectedException.message where: - invalidTransformer2WType || expectedException - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapSide, tapNeutr, tapMin, tapMax) || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer2WType) - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, tapNeutr, 100, tapMax) || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer2WType) - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, 100, tapMin, tapMax) || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer2WType) + invalidTransformer2WType || excpectedSize || expectedException + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapSide, tapNeutr, tapMin, tapMax) || 1 || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer2WType) + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, tapNeutr, 100, tapMax) || 2 || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer2WType) + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, 100, tapMin, tapMax) || 1 || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer2WType) } def "Smoke Test: Correct transformer3W throws no exception"() { @@ -185,19 +188,20 @@ 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() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception ex.class == expectedException.class 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"() { @@ -225,18 +229,19 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3WType recognizes all potential errors for a transformer3W type"() { when: - ConnectorValidationUtils.check(invalidTransformer3WType) + List> exceptions = ConnectorValidationUtils.check(invalidTransformer3WType).stream().filter {it -> it.failure}.toList() then: - Exception ex = thrown() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception ex.class == expectedException.class ex.message == expectedException.message where: - invalidTransformer3WType || expectedException - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapNeutr, tapMin, tapMax) || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer3WType) - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, tapNeutr, 100, tapMax) || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer3WType) - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, 100, tapMin, tapMax) || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer3WType) + invalidTransformer3WType || expectedSize || expectedException + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapNeutr, tapMin, tapMax) || 1 || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer3WType) + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, tapNeutr, 100, tapMax) || 2 || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer3WType) + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, 100, tapMin, tapMax) || 1 || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer3WType) } def "Smoke Test: Correct switch throws no exception"() { @@ -252,15 +257,16 @@ 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() + exceptions.size() == expectedSize + Exception ex = exceptions.get(0).exception ex.class == expectedException.class 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) } } From 94f5da1f129ab6d177b99b27500b650f956b08ba Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Mon, 13 Mar 2023 11:05:10 +0100 Subject: [PATCH 05/39] Adapting tests. --- .../SystemParticipantValidationUtils.java | 4 +- .../ThermalUnitValidationUtils.java | 7 +- .../utils/validation/ValidationUtils.java | 26 ++-- .../ConnectorValidationUtilsTest.groovy | 33 +++-- .../GraphicValidationUtilsTest.groovy | 28 +++-- .../MeasurementUnitValidationUtilsTest.groovy | 8 +- .../validation/NodeValidationUtilsTest.groovy | 24 ++-- ...ystemParticipantValidationUtilsTest.groovy | 119 +++++++++--------- .../ThermalUnitValidationUtilsTest.groovy | 32 ++--- .../validation/ValidationUtilsTest.groovy | 38 +++--- 10 files changed, 170 insertions(+), 149 deletions(-) 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 29aabcb05..b938ba03c 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -169,8 +169,8 @@ protected static List> checkType( exceptions.add( new Failure<>( new InvalidEntityException( - "Validation failed due to: ", - checkNotImplementedException(systemParticipantTypeInput)))); + checkNotImplementedException(systemParticipantTypeInput).getMessage(), + systemParticipantTypeInput))); } return exceptions; 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 e82699ffc..877f52f85 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -57,7 +57,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - "Validation failed due to: ", checkNotImplementedException(thermalUnitInput)))); + checkNotImplementedException(thermalUnitInput).getMessage()))); } return exceptions; @@ -96,7 +96,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - "Validation failed due to: ", checkNotImplementedException(thermalSinkInput)))); + checkNotImplementedException(thermalSinkInput).getMessage()))); } return exceptions; @@ -135,8 +135,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - "Validation failed due to: ", - checkNotImplementedException(thermalStorageInput)))); + checkNotImplementedException(thermalStorageInput).getMessage()))); } 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 347025340..374fd35e1 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -21,6 +21,7 @@ import edu.ie3.datamodel.models.input.system.type.*; import edu.ie3.datamodel.models.input.thermal.ThermalUnitInput; import edu.ie3.datamodel.utils.options.Failure; +import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -62,14 +63,11 @@ protected static NotImplementedException checkNotImplementedException(Object obj * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - public static List> check(Object obj) { + public static Try check(Object obj) { try { checkNonNull(obj, "an object"); } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + obj + "} was null", e))); + return new Failure<>(e); } List> exceptions = new ArrayList<>(); @@ -85,11 +83,17 @@ protected static NotImplementedException checkNotImplementedException(Object obj } else { exceptions.add( new Failure<>( - new FailedValidationException( - "Validation failed due to: ", checkNotImplementedException(obj)))); + new FailedValidationException(checkNotImplementedException(obj).getMessage()))); } - return exceptions; + List list = + exceptions.stream().filter(Try::isFailure).map(Try::getException).toList(); + + if (list.size() > 0) { + return new Failure<>(new FailedValidationException(list)); + } else { + return Success.empty(); + } } /** @@ -122,7 +126,7 @@ protected static NotImplementedException checkNotImplementedException(Object obj exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput))); } if (assetInput.getOperationTime() == null) { - exceptions.add( + return List.of( new Failure<>( new InvalidEntityException( "Operation time of the asset is not defined", assetInput))); @@ -164,7 +168,7 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) exceptions.add( new Failure<>( new FailedValidationException( - "Validation failed due to: ", checkNotImplementedException(assetInput)))); + checkNotImplementedException(assetInput).getMessage()))); } return exceptions; @@ -217,7 +221,7 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla exceptions.add( new Failure<>( new FailedValidationException( - "Validation failed due to: ", checkNotImplementedException(assetTypeInput)))); + checkNotImplementedException(assetTypeInput).getMessage()))); } return exceptions; 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 12d493504..ee577446e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.utils.options.Try import static edu.ie3.datamodel.models.StandardUnits.* @@ -160,19 +161,17 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2WType recognizes all potential errors for a transformer2W type"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer2WType).stream().filter {it -> it.failure}.toList() + Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) then: - exceptions.size() == excpectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: - invalidTransformer2WType || excpectedSize || expectedException - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapSide, tapNeutr, tapMin, tapMax) || 1 || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer2WType) - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, tapNeutr, 100, tapMax) || 2 || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer2WType) - new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, 100, tapMin, tapMax) || 1 || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer2WType) + invalidTransformer2WType || expectedException + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapSide, tapNeutr, tapMin, tapMax) || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer2WType) + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, tapNeutr, 100, tapMax) || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer2WType) + new Transformer2WTypeInput(uuid, id, rSc, xSc, sRated, vRatedA, vRatedB, gM, bM, dV, dPhi, tapSide, 100, tapMin, tapMax) || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer2WType) } def "Smoke Test: Correct transformer3W throws no exception"() { @@ -229,19 +228,17 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3WType recognizes all potential errors for a transformer3W type"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer3WType).stream().filter {it -> it.failure}.toList() + Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) then: - exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: - invalidTransformer3WType || expectedSize || expectedException - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapNeutr, tapMin, tapMax) || 1 || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer3WType) - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, tapNeutr, 100, tapMax) || 2 || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer3WType) - new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, 100, tapMin, tapMax) || 1 || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer3WType) + invalidTransformer3WType || expectedException + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, Quantities.getQuantity(-1d, DV_TAP), dPhi, tapNeutr, tapMin, tapMax) || new InvalidEntityException("Voltage magnitude increase per tap position must be between 0% and 100%", invalidTransformer3WType) + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, tapNeutr, 100, tapMax) || new InvalidEntityException("Minimum tap position must be lower than maximum tap position", invalidTransformer3WType) + new Transformer3WTypeInput(uuid, id, sRatedA, sRatedB, sRatedC, vRatedA, vRatedB, vRatedC, rScA, rScB, rScC, xScA, xScB, xScC, gM, bM, dV, dPhi, 100, tapMin, tapMax) || new InvalidEntityException("Neutral tap position must be between minimum and maximum tap position", invalidTransformer3WType) } def "Smoke Test: Correct switch throws no exception"() { 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..68560a720 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.options.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 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 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 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/MeasurementUnitValidationUtilsTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy index 8daa30362..1535687f2 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy @@ -5,7 +5,10 @@ */ 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.utils.options.Try import edu.ie3.test.common.GridTestData import spock.lang.Specification @@ -24,10 +27,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 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..bb05d9b1a 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -5,6 +5,9 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.exceptions.ValidationException +import edu.ie3.datamodel.utils.options.Try + import static edu.ie3.util.quantities.PowerSystemUnits.KILOVOLT import static edu.ie3.util.quantities.PowerSystemUnits.PU @@ -32,31 +35,32 @@ class NodeValidationUtilsTest extends Specification { 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 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("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..bfea59a64 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -7,9 +7,11 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.exceptions.NotImplementedException +import edu.ie3.datamodel.exceptions.ValidationException 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.options.Try import edu.ie3.test.common.SystemParticipantTestData import edu.ie3.util.quantities.interfaces.Currency import edu.ie3.util.quantities.interfaces.DimensionlessRate @@ -47,16 +49,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 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 @@ -96,12 +99,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkType() recognizes all potential errors for a system participant type"() { when: - SystemParticipantValidationUtils.check(invalidType) + Try exceptions = SystemParticipantValidationUtils.check(invalidType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidType || expectedException @@ -138,17 +140,16 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkBmType() recognizes all potential errors for a biomass power plant type"() { when: - SystemParticipantValidationUtils.check(invalidBmType) + Try exceptions = ValidationUtils.check(invalidBmType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(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 @@ -179,12 +180,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkChpType() recognizes all potential errors for a CHP type"() { when: - SystemParticipantValidationUtils.check(invalidChpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidChpType || expectedException @@ -222,12 +222,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkEvType() recognizes all potential errors for an EV type"() { when: - SystemParticipantValidationUtils.check(invalidEvType) + Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidEvType || expectedException @@ -249,17 +248,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 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 @@ -290,12 +290,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkHpType() recognizes all potential errors for an HP type"() { when: - SystemParticipantValidationUtils.check(invalidHpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidHpType || expectedException @@ -317,18 +316,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 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 +346,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 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 @@ -391,12 +392,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkStorageType() recognizes all potential errors for a storage type"() { when: - SystemParticipantValidationUtils.check(invalidStorageType) + Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidStorageType || expectedException @@ -435,12 +435,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkWecType() recognizes all potential errors for a wec type"() { when: - SystemParticipantValidationUtils.check(invalidWecType) + Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + Exception ex = exceptions.exception + ex.message.contains(expectedException.message) where: invalidWecType || expectedException @@ -455,10 +454,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.cause e.message == "Cannot validate object of class 'InvalidSystemParticipantInput', as no routine is implemented." } @@ -467,11 +466,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipantInput = new InvalidSystemParticipantTypeInput() when: - SystemParticipantValidationUtils.check(invalidParticipantInput) + Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) then: - def e = thrown(NotImplementedException) - e.message == "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." + def e = exceptions.exception + 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 ca25fa8fe..c7b3f4263 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.options.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 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,18 +98,19 @@ 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 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..ec8ba2174 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -5,6 +5,9 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.exceptions.ValidationException +import edu.ie3.datamodel.utils.options.Try + 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 @@ -106,12 +109,12 @@ class ValidationUtilsTest extends Specification { def "If an object can't be identified, a ValidationException is thrown as expected"() { when: - ValidationUtils.check(invalidObject) + Try actual = ValidationUtils.check(invalidObject) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + actual.failure + Throwable ex = actual.exception + ex.message.contains(expectedException.message) where: invalidObject || expectedException @@ -120,12 +123,12 @@ class ValidationUtilsTest extends Specification { def "The validation check method recognizes all potential errors for an asset"() { when: - ValidationUtils.check(invalidAsset) + Try actual = ValidationUtils.check(invalidAsset) then: - Exception ex = thrown() - ex.class == expectedException.class - ex.message == expectedException.message + actual.failure + Exception ex = actual.exception + ex.message.contains(expectedException.message) where: invalidAsset || expectedException @@ -216,11 +219,12 @@ class ValidationUtilsTest extends Specification { def invalidAsset = new InvalidAssetInput() 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 + e.message.contains("Cannot validate object of class 'InvalidAssetInput', as no routine is implemented.") } def "Checking an unsupported asset type leads to an exception"() { @@ -228,11 +232,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 + 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 +245,11 @@ 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: - def e = thrown(InvalidEntityException) + exceptions.size() == 2 + def e = exceptions.get(0).exception e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") } } From 3cd33c98be4b356cbdb186694247cffdbbb097dd Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Tue, 11 Apr 2023 12:17:51 +0200 Subject: [PATCH 06/39] Adding some new features. --- .../validation/ConnectorValidationUtils.java | 53 +++++++++++++++++++ .../GridContainerValidationUtils.java | 50 +++++++++++++++++ .../utils/validation/ValidationUtils.java | 29 ++++++++++ 3 files changed, 132 insertions(+) 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 3760a9166..9ad045d22 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -6,11 +6,13 @@ package edu.ie3.datamodel.utils.validation; import edu.ie3.datamodel.exceptions.InvalidEntityException; +import edu.ie3.datamodel.exceptions.InvalidGridException; 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.RawGridElements; import edu.ie3.datamodel.utils.options.Failure; import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; @@ -18,7 +20,12 @@ 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; @@ -366,6 +373,52 @@ private static Try checkSwitch(SwitchInput switchI * grid, whilst the "real" upper node is within the upper grid */ } + /** + * Check if all given elements are connected. + * + * @param elements grid elements + * @param subnetNo subnet number + * @return a try object either containing an {@link InvalidGridException} or an empty Success + */ + private static Try checkConnectivity( + RawGridElements elements, int subnetNo) { + Graph graph = new SimpleGraph<>(DefaultEdge.class); + + elements.getNodes().forEach(node -> graph.addVertex(node.getUuid())); + elements + .getLines() + .forEach(line -> graph.addEdge(line.getNodeA().getUuid(), line.getNodeB().getUuid())); + elements + .getTransformer2Ws() + .forEach( + trafo2w -> graph.addEdge(trafo2w.getNodeA().getUuid(), trafo2w.getNodeB().getUuid())); + elements + .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()); + }); + elements + .getSwitches() + .forEach( + switches -> + graph.addEdge(switches.getNodeA().getUuid(), switches.getNodeB().getUuid())); + + ConnectivityInspector inspector = new ConnectivityInspector<>(graph); + + if (!inspector.isConnected()) { + return new Failure<>( + new InvalidGridException( + "The grid with subnetNo " + + subnetNo + + " is not connected! Please ensure that all elements are connected correctly!")); + } else { + return Success.empty(); + } + } + /** * Check that a connector connects different nodes * 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 d67d3c110..480b5e166 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,7 @@ 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; @@ -202,6 +203,28 @@ private GridContainerValidationUtils() { 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.checkTypeIds(rawGridElements.getNodes())); + exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getLines())); + exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getTransformer2Ws())); + exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getTransformer3Ws())); + exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getSwitches())); + exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getMeasurementUnits())); + return exceptions; } @@ -341,6 +364,33 @@ private GridContainerValidationUtils() { exceptions.addAll(SystemParticipantValidationUtils.check(entity)); }); + exceptions.addAll(checkSystemParticipantsTypeIds(systemParticipants)); + + return exceptions; + } + + /** + * 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.checkTypeIds(systemParticipants.getBmPlants())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getChpPlants())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEvCS())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEvs())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getFixedFeedIns())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getHeatPumps())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getLoads())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getPvPlants())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getStorages())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getWecPlants())); + exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEmSystems())); + 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 374fd35e1..f641c5e03 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -227,6 +227,35 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla 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> checkTypeIds( + Set inputs) { + List ids = new ArrayList<>(); + List> exceptions = new ArrayList<>(); + + inputs.forEach( + input -> { + String id = input.getId(); + if (!ids.contains(id)) { + ids.add(id); + exceptions.add(Success.empty()); + } 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. * From f8667c3d62942d9fbf030a5c2b5531337daf177e Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Wed, 12 Apr 2023 12:03:20 +0200 Subject: [PATCH 07/39] Adding tests. --- .../validation/ConnectorValidationUtils.java | 25 ++++++------ .../GridContainerValidationUtils.java | 38 ++++++++++--------- .../utils/validation/ValidationUtils.java | 2 +- .../utils/validation/ValidAssetInput.groovy | 27 +++++++++++++ .../validation/ValidationUtilsTest.groovy | 33 ++++++++++++++++ 5 files changed, 96 insertions(+), 29 deletions(-) create mode 100644 src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy 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 9ad045d22..6ddf26500 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -12,7 +12,7 @@ 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.RawGridElements; +import edu.ie3.datamodel.models.input.container.SubGridContainer; import edu.ie3.datamodel.utils.options.Failure; import edu.ie3.datamodel.utils.options.Success; import edu.ie3.datamodel.utils.options.Try; @@ -376,23 +376,25 @@ private static Try checkSwitch(SwitchInput switchI /** * Check if all given elements are connected. * - * @param elements grid elements - * @param subnetNo subnet number + * @param subGridContainer the subgrid to check the connectivity for * @return a try object either containing an {@link InvalidGridException} or an empty Success */ - private static Try checkConnectivity( - RawGridElements elements, int subnetNo) { + protected static Try checkConnectivity( + SubGridContainer subGridContainer) { Graph graph = new SimpleGraph<>(DefaultEdge.class); - elements.getNodes().forEach(node -> graph.addVertex(node.getUuid())); - elements + subGridContainer.getRawGrid().getNodes().forEach(node -> graph.addVertex(node.getUuid())); + subGridContainer + .getRawGrid() .getLines() .forEach(line -> graph.addEdge(line.getNodeA().getUuid(), line.getNodeB().getUuid())); - elements + subGridContainer + .getRawGrid() .getTransformer2Ws() .forEach( trafo2w -> graph.addEdge(trafo2w.getNodeA().getUuid(), trafo2w.getNodeB().getUuid())); - elements + subGridContainer + .getRawGrid() .getTransformer3Ws() .forEach( trafor3w -> { @@ -400,7 +402,8 @@ private static Try checkConnectivity( graph.addEdge(trafor3w.getNodeInternal().getUuid(), trafor3w.getNodeB().getUuid()); graph.addEdge(trafor3w.getNodeInternal().getUuid(), trafor3w.getNodeC().getUuid()); }); - elements + subGridContainer + .getRawGrid() .getSwitches() .forEach( switches -> @@ -412,7 +415,7 @@ private static Try checkConnectivity( return new Failure<>( new InvalidGridException( "The grid with subnetNo " - + subnetNo + + subGridContainer.getSubnet() + " is not connected! Please ensure that all elements are connected correctly!")); } else { return Success.empty(); 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 480b5e166..096a3d541 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -82,6 +82,10 @@ private GridContainerValidationUtils() { gridContainer.getRawGrid().getNodes(), gridContainer.getRawGrid().getLines())); + if (gridContainer instanceof SubGridContainer subGridContainer) { + exceptions.add(ConnectorValidationUtils.checkConnectivity(subGridContainer)); + } + return exceptions; } @@ -218,12 +222,12 @@ private GridContainerValidationUtils() { protected static List> checkRawGridTypeIds( RawGridElements rawGridElements) { List> exceptions = new ArrayList<>(); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getNodes())); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getLines())); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getTransformer2Ws())); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getTransformer3Ws())); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getSwitches())); - exceptions.addAll(ValidationUtils.checkTypeIds(rawGridElements.getMeasurementUnits())); + 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; } @@ -379,17 +383,17 @@ protected static List> checkRawGridTypeIds( protected static List> checkSystemParticipantsTypeIds( SystemParticipants systemParticipants) { List> exceptions = new ArrayList<>(); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getBmPlants())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getChpPlants())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEvCS())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEvs())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getFixedFeedIns())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getHeatPumps())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getLoads())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getPvPlants())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getStorages())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getWecPlants())); - exceptions.addAll(ValidationUtils.checkTypeIds(systemParticipants.getEmSystems())); + 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; } 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 f641c5e03..540f4bd0b 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -234,7 +234,7 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty * Success */ - protected static List> checkTypeIds( + protected static List> checkIds( Set inputs) { List ids = new ArrayList<>(); List> exceptions = new ArrayList<>(); diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy new file mode 100644 index 000000000..70dff1c30 --- /dev/null +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy @@ -0,0 +1,27 @@ +/* + * © 2023. TU Dortmund University, + * Institute of Energy Systems, Energy Efficiency and Energy Economics, + * Research group Distribution grid planning and operation + */ +package edu.ie3.datamodel.utils.validation + +import edu.ie3.datamodel.models.input.AssetInput + +import java.time.ZonedDateTime + +class ValidAssetInput extends AssetInput { + + ValidAssetInput(String id) { + super(UUID.randomUUID(), id) + } + + @Override + boolean inOperationOn(ZonedDateTime date) { + throw new UnsupportedOperationException("This is a dummy class") + } + + @Override + UniqueEntityBuilder copy() { + throw new UnsupportedOperationException("This is a dummy class") + } +} 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 ec8ba2174..022bb3e31 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -5,7 +5,9 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.exceptions.UnsafeEntityException import edu.ie3.datamodel.exceptions.ValidationException +import edu.ie3.datamodel.models.input.AssetInput import edu.ie3.datamodel.utils.options.Try import static edu.ie3.datamodel.models.StandardUnits.CONDUCTANCE_PER_LENGTH @@ -252,4 +254,35 @@ class ValidationUtilsTest extends Specification { def e = exceptions.get(0).exception e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") } + + def "Checking if asset input ids are unique"() { + given: + Set validAssetIds = [ + new ValidAssetInput("first"), + new ValidAssetInput("second"), + new ValidAssetInput("third") + ] + + when: + List> exceptions = ValidationUtils.checkIds(validAssetIds) + + then: + exceptions.forEach {ex -> ex.success } + } + + def "Duplicate asset input ids leads to an exception"() { + given: + Set invalidAssetIds = [ + new InvalidAssetInput(), + new InvalidAssetInput() + ] + + when: + List> exceptions = ValidationUtils.checkIds(invalidAssetIds) + + then: + exceptions.get(0).success + exceptions.get(1).failure + exceptions.get(1).exception.message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") + } } From 54ecf77029ad51f39ac39f82076ef91454b9ed55 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Tue, 18 Apr 2023 11:11:54 +0200 Subject: [PATCH 08/39] fmt --- .../ie3/datamodel/io/source/csv/CsvTimeSeriesMappingSource.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesMappingSource.java b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesMappingSource.java index deb4d7ab0..67a2c8d41 100644 --- a/src/main/java/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesMappingSource.java +++ b/src/main/java/edu/ie3/datamodel/io/source/csv/CsvTimeSeriesMappingSource.java @@ -11,7 +11,6 @@ import edu.ie3.datamodel.io.source.TimeSeriesMappingSource; import edu.ie3.datamodel.utils.options.Try; import java.util.Map; -import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; From 9a5c7a6728182115fd9b0e442e3fd19744a3fd2d Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Tue, 18 Apr 2023 12:40:23 +0200 Subject: [PATCH 09/39] Improving ``GridContainerValidationUtils`` --- .../GridContainerValidationUtils.java | 121 +++++------------- 1 file changed, 30 insertions(+), 91 deletions(-) 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 096a3d541..3dc70e321 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -269,108 +269,47 @@ protected static List> checkRawGridTypeIds( systemParticipants.getClass().getSimpleName(), exceptionString)))); } - systemParticipants - .getBmPlants() - .forEach( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); - - systemParticipants - .getChpPlants() - .forEach( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(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 -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); - - systemParticipants - .getHeatPumps() - .forEach( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); - - systemParticipants - .getLoads() - .forEach( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); + 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)); - systemParticipants - .getPvPlants() - .forEach( - entity -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); + return exceptions; + } - systemParticipants - .getStorages() - .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 -> { - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } - exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); + List> exceptions = new ArrayList<>(); - systemParticipants - .getWecPlants() - .forEach( - entity -> { try { checkNodeAvailability(entity, nodes); } catch (InvalidGridException e) { exceptions.add(new Failure<>(e)); } exceptions.addAll(SystemParticipantValidationUtils.check(entity)); - }); - exceptions.addAll(checkSystemParticipantsTypeIds(systemParticipants)); - - return exceptions; + return exceptions; + }) + .flatMap(List::stream) + .toList(); } /** From ca16f5175c3c2eb8a20d8047f784f0c922f37118 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Tue, 9 May 2023 12:02:09 +0200 Subject: [PATCH 10/39] fmt --- .../datamodel/io/source/csv/CsvJointGridContainerSource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4660eba41..153639a94 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 @@ -9,9 +9,9 @@ import edu.ie3.datamodel.exceptions.GraphicSourceException; import edu.ie3.datamodel.exceptions.RawGridException; import edu.ie3.datamodel.exceptions.SourceException; +import edu.ie3.datamodel.exceptions.SystemParticipantsException; import edu.ie3.datamodel.io.naming.DefaultDirectoryHierarchy; import edu.ie3.datamodel.io.naming.EntityPersistenceNamingStrategy; -import edu.ie3.datamodel.exceptions.SystemParticipantsException; import edu.ie3.datamodel.io.naming.FileNamingStrategy; import edu.ie3.datamodel.io.source.*; import edu.ie3.datamodel.models.input.container.GraphicElements; From b7e8eb69434f89c7092421f2da74fcb8cee5a3f7 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Tue, 16 May 2023 16:07:19 +0200 Subject: [PATCH 11/39] Adapting to changes. --- .../datamodel/io/source/sql/SqlIdCoordinateSource.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/io/source/sql/SqlIdCoordinateSource.java b/src/main/java/edu/ie3/datamodel/io/source/sql/SqlIdCoordinateSource.java index 1d567e87f..06618d13a 100644 --- a/src/main/java/edu/ie3/datamodel/io/source/sql/SqlIdCoordinateSource.java +++ b/src/main/java/edu/ie3/datamodel/io/source/sql/SqlIdCoordinateSource.java @@ -5,11 +5,14 @@ */ package edu.ie3.datamodel.io.source.sql; +import edu.ie3.datamodel.exceptions.FactoryException; import edu.ie3.datamodel.io.connectors.SqlConnector; +import edu.ie3.datamodel.io.factory.FactoryData; import edu.ie3.datamodel.io.factory.SimpleFactoryData; import edu.ie3.datamodel.io.factory.timeseries.SqlCoordinateFactory; import edu.ie3.datamodel.io.source.IdCoordinateSource; import edu.ie3.datamodel.models.value.CoordinateValue; +import edu.ie3.datamodel.utils.options.Try; import edu.ie3.util.geo.CoordinateDistance; import edu.ie3.util.geo.GeoUtils; import java.sql.Array; @@ -74,8 +77,9 @@ public SqlIdCoordinateSource( protected Optional createEntity(Map fieldToValues) { fieldToValues.remove("distance"); - SimpleFactoryData simpleFactoryData = new SimpleFactoryData(fieldToValues, Pair.class); - Optional> pair = factory.get(simpleFactoryData); + SimpleFactoryData simpleFactoryData = + new SimpleFactoryData(new FactoryData.MapWithRowIndex("-1", fieldToValues), Pair.class); + Try, FactoryException> pair = factory.get(simpleFactoryData); if (pair.isEmpty()) { return Optional.empty(); From 3dc162b275d6826a21873c37310884f81e3761ac Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 29 Jun 2023 14:53:48 +0200 Subject: [PATCH 12/39] Adapting to changes. --- .../io/source/csv/CsvIdCoordinateSource.java | 2 +- .../java/edu/ie3/datamodel/utils/Try.java | 6 +- .../validation/ConnectorValidationUtils.java | 91 ++++++++------- .../validation/GraphicValidationUtils.java | 12 +- .../GridContainerValidationUtils.java | 35 +++--- .../MeasurementUnitValidationUtils.java | 7 +- .../utils/validation/NodeValidationUtils.java | 8 +- .../SystemParticipantValidationUtils.java | 104 +++++++++--------- .../ThermalUnitValidationUtils.java | 34 +++--- .../utils/validation/ValidationUtils.java | 28 ++--- .../edu/ie3/datamodel/utils/TryTest.groovy | 2 +- .../ConnectorValidationUtilsTest.groovy | 29 +++-- .../GraphicValidationUtilsTest.groovy | 14 +-- .../MeasurementUnitValidationUtilsTest.groovy | 7 +- .../validation/NodeValidationUtilsTest.groovy | 7 +- ...ystemParticipantValidationUtilsTest.groovy | 59 +++++----- .../ThermalUnitValidationUtilsTest.groovy | 11 +- .../validation/ValidationUtilsTest.groovy | 30 ++--- 18 files changed, 228 insertions(+), 258 deletions(-) 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 14a4dd326..e3aa743ef 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 @@ -8,7 +8,7 @@ import edu.ie3.datamodel.io.factory.SimpleFactoryData; import edu.ie3.datamodel.io.factory.timeseries.IdCoordinateFactory; import edu.ie3.datamodel.io.source.IdCoordinateSource; -import edu.ie3.datamodel.utils.options.Try; +import edu.ie3.datamodel.utils.Try; import edu.ie3.util.geo.CoordinateDistance; import edu.ie3.util.geo.GeoUtils; import java.io.BufferedReader; diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index ef9a2da7f..ff750d790 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -59,9 +59,9 @@ public static Try of(TrySupplier supplier) { * @param supplier that either returns no data or throws an exception * @return a try object */ - public static Try testForException(TrySupplier supplier) { + public static Try ofVoid(Runnable supplier) { try { - supplier.get(); + supplier.run(); return Success.empty(); } catch (Exception e) { return new Failure<>(e); @@ -244,7 +244,7 @@ public static Try> scanCollection(Collection> c, Class type * @param tries collection of {@link Try} objects * @return a list of {@link Exception}'s */ - public static List getExceptions(Collection> tries) { + public static List getExceptions(Collection> tries) { return tries.stream().filter(Try::isFailure).map(t -> ((Failure) t).get()).toList(); } 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 6ddf26500..265b78261 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -13,9 +13,8 @@ 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.options.Failure; -import edu.ie3.datamodel.utils.options.Success; -import edu.ie3.datamodel.utils.options.Try; +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; @@ -53,7 +52,7 @@ private ConnectorValidationUtils() { * @return a list of try objects either containing a {@link InvalidEntityException} or an empty * Success */ - protected static List> check(ConnectorInput connector) { + protected static List> check(ConnectorInput connector) { try { checkNonNull(connector, "a connector"); } catch (InvalidEntityException e) { @@ -64,8 +63,8 @@ protected static List> check(ConnectorInput co e))); } - List> exceptions = new ArrayList<>(); - exceptions.add(Try.apply(() -> connectsDifferentNodes(connector))); + List> exceptions = new ArrayList<>(); + exceptions.add(Try.ofVoid(() -> connectsDifferentNodes(connector))); // Further checks for subclasses if (LineInput.class.isAssignableFrom(connector.getClass())) { @@ -101,17 +100,16 @@ protected static List> check(ConnectorInput co * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkLine(LineInput line) { - List> exceptions = - new ArrayList<>(checkLineType(line.getType())); + private static List> checkLine(LineInput line) { + List> exceptions = new ArrayList<>(checkLineType(line.getType())); - exceptions.add(Try.apply(() -> connectsNodesInDifferentSubnets(line, false))); - exceptions.add(Try.apply(() -> connectsNodesWithDifferentVoltageLevels(line, false))); + exceptions.add(Try.ofVoid(() -> connectsNodesInDifferentSubnets(line, false))); + exceptions.add(Try.ofVoid(() -> connectsNodesWithDifferentVoltageLevels(line, false))); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line))); - exceptions.add(Try.apply(() -> coordinatesOfLineEqualCoordinatesOfNodes(line))); - exceptions.add(Try.apply(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))); + exceptions.add(Try.ofVoid(() -> coordinatesOfLineEqualCoordinatesOfNodes(line))); + exceptions.add(Try.ofVoid(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))); return exceptions; } @@ -130,7 +128,7 @@ private static List> checkLine(LineInput line) * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkLineType(LineTypeInput lineType) { + protected static List> checkLineType(LineTypeInput lineType) { try { checkNonNull(lineType, "a line type"); } catch (InvalidEntityException e) { @@ -142,11 +140,11 @@ protected static List> checkLineType(LineTypeI } return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {lineType.getB(), lineType.getG()}, lineType)), - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] { @@ -168,16 +166,14 @@ protected static List> checkLineType(LineTypeI * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkTransformer2W( - Transformer2WInput transformer2W) { - List> exceptions = - new ArrayList<>(checkTransformer2WType(transformer2W.getType())); + private static List> checkTransformer2W(Transformer2WInput transformer2W) { + List> exceptions = new ArrayList<>(checkTransformer2WType(transformer2W.getType())); - exceptions.add(Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer2W))); - exceptions.add(Try.apply(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true))); - exceptions.add(Try.apply(() -> connectsNodesInDifferentSubnets(transformer2W, true))); + exceptions.add(Try.ofVoid(() -> checkIfTapPositionIsWithinBounds(transformer2W))); + exceptions.add(Try.ofVoid(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true))); + exceptions.add(Try.ofVoid(() -> connectsNodesInDifferentSubnets(transformer2W, true))); exceptions.add( - Try.apply(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); + Try.ofVoid(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); return exceptions; } @@ -201,7 +197,7 @@ private static List> checkTransformer2W( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkTransformer2WType( + protected static List> checkTransformer2WType( Transformer2WTypeInput transformer2WType) { try { checkNonNull(transformer2WType, "a two winding transformer type"); @@ -216,7 +212,7 @@ protected static List> checkTransformer2WType( } return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] { @@ -225,7 +221,7 @@ protected static List> checkTransformer2WType( transformer2WType.getrSc() }, transformer2WType)), - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] { @@ -235,13 +231,14 @@ protected static List> checkTransformer2WType( transformer2WType.getxSc() }, transformer2WType)), - Try.apply( + Try.ofVoid( () -> detectPositiveQuantities( new Quantity[] {transformer2WType.getbM()}, transformer2WType)), - Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), - Try.apply(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), - Try.apply(() -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))); + Try.ofVoid(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), + Try.ofVoid(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), + Try.ofVoid( + () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))); } /** @@ -257,12 +254,10 @@ protected static List> checkTransformer2WType( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkTransformer3W( - Transformer3WInput transformer3W) { - List> exceptions = - new ArrayList<>(checkTransformer3WType(transformer3W.getType())); + private static List> checkTransformer3W(Transformer3WInput transformer3W) { + List> exceptions = new ArrayList<>(checkTransformer3WType(transformer3W.getType())); - exceptions.add(Try.apply(() -> checkIfTapPositionIsWithinBounds(transformer3W))); + exceptions.add(Try.ofVoid(() -> checkIfTapPositionIsWithinBounds(transformer3W))); // Check if transformer connects different voltage levels if (transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeB().getVoltLvl() @@ -284,7 +279,7 @@ private static List> checkTransformer3W( } exceptions.add( - Try.apply(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W))); + Try.ofVoid(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W))); return exceptions; } @@ -307,7 +302,7 @@ private static List> checkTransformer3W( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkTransformer3WType( + protected static List> checkTransformer3WType( Transformer3WTypeInput transformer3WType) { try { checkNonNull(transformer3WType, "a three winding transformer type"); @@ -322,12 +317,12 @@ protected static List> checkTransformer3WType( } return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {transformer3WType.getgM(), transformer3WType.getdPhi()}, transformer3WType)), - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] { @@ -345,13 +340,14 @@ protected static List> checkTransformer3WType( transformer3WType.getxScC() }, transformer3WType)), - Try.apply( + Try.ofVoid( () -> detectPositiveQuantities( new Quantity[] {transformer3WType.getbM()}, transformer3WType)), - Try.apply(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), - Try.apply(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), - Try.apply(() -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))); + Try.ofVoid(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), + Try.ofVoid(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), + Try.ofVoid( + () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))); } /** @@ -361,7 +357,7 @@ protected static List> checkTransformer3WType( * @param switchInput Switch to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkSwitch(SwitchInput switchInput) { + private static Try checkSwitch(SwitchInput switchInput) { if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) { return new Failure<>( new InvalidEntityException("Switch connects two different voltage levels", switchInput)); @@ -379,8 +375,7 @@ private static Try checkSwitch(SwitchInput switchI * @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) { + protected static Try checkConnectivity(SubGridContainer subGridContainer) { Graph graph = new SimpleGraph<>(DefaultEdge.class); subGridContainer.getRawGrid().getNodes().forEach(node -> graph.addVertex(node.getUuid())); 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 dc6fdbdb0..3eb2e6055 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -9,8 +9,8 @@ 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.options.Failure; -import edu.ie3.datamodel.utils.options.Try; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.Failure; import java.util.ArrayList; import java.util.List; @@ -33,7 +33,7 @@ private GraphicValidationUtils() { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> check(GraphicInput graphicInput) { + protected static List> check(GraphicInput graphicInput) { try { checkNonNull(graphicInput, "a graphic input"); } catch (InvalidEntityException e) { @@ -44,7 +44,7 @@ protected static List> check(GraphicInput grap e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (graphicInput.getGraphicLayer() == null) { exceptions.add( @@ -55,9 +55,9 @@ protected static List> check(GraphicInput grap // Further checks for subclasses if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - exceptions.add(Try.apply(() -> checkLineGraphicInput((LineGraphicInput) graphicInput))); + exceptions.add(Try.ofVoid(() -> checkLineGraphicInput((LineGraphicInput) graphicInput))); } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - exceptions.add(Try.apply(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput))); + exceptions.add(Try.ofVoid(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput))); } return exceptions; 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 3dc70e321..fd7764ff1 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -18,8 +18,8 @@ import edu.ie3.datamodel.models.input.container.*; import edu.ie3.datamodel.models.input.system.SystemParticipantInput; import edu.ie3.datamodel.utils.ContainerUtils; -import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Try; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.Failure; import java.util.*; import java.util.stream.Stream; @@ -45,8 +45,7 @@ private GridContainerValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check( - GridContainer gridContainer) { + protected static List> check(GridContainer gridContainer) { try { checkNonNull(gridContainer, "grid container"); } catch (InvalidEntityException e) { @@ -59,7 +58,7 @@ private GridContainerValidationUtils() { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = @@ -97,8 +96,7 @@ private GridContainerValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkRawGridElements( - RawGridElements rawGridElements) { + protected static List> checkRawGridElements(RawGridElements rawGridElements) { try { checkNonNull(rawGridElements, "raw grid elements"); } catch (InvalidEntityException e) { @@ -111,7 +109,7 @@ private GridContainerValidationUtils() { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = @@ -219,9 +217,8 @@ private GridContainerValidationUtils() { * @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<>(); + 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())); @@ -241,7 +238,7 @@ protected static List> checkRawGridTypeIds( * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkSystemParticipants( + protected static List> checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { try { checkNonNull(systemParticipants, "system participants"); @@ -255,7 +252,7 @@ protected static List> checkRawGridTypeIds( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = @@ -292,12 +289,12 @@ protected static List> checkRawGridTypeIds( * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkSystemParticipants( + protected static List> checkSystemParticipants( Set participants, Set nodes) { return participants.stream() .map( entity -> { - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); try { checkNodeAvailability(entity, nodes); @@ -319,9 +316,9 @@ protected static List> checkRawGridTypeIds( * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty * Success */ - protected static List> checkSystemParticipantsTypeIds( + protected static List> checkSystemParticipantsTypeIds( SystemParticipants systemParticipants) { - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getBmPlants())); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getChpPlants())); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getEvCS())); @@ -346,7 +343,7 @@ protected static List> checkSystemParticipantsT * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkGraphicElements( + protected static List> checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { try { checkNonNull(graphicElements, "graphic elements"); @@ -360,7 +357,7 @@ protected static List> checkGraphicElements( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = 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 bd48b1fc9..92f4f9f5f 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -9,9 +9,8 @@ import edu.ie3.datamodel.exceptions.UnsafeEntityException; import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.MeasurementUnitInput; -import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Success; -import edu.ie3.datamodel.utils.options.Try; +import edu.ie3.datamodel.utils.Try; +import edu.ie3.datamodel.utils.Try.*; public class MeasurementUnitValidationUtils extends ValidationUtils { @@ -28,7 +27,7 @@ private MeasurementUnitValidationUtils() { * @param measurementUnit Measurement unit to validate * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static Try check(MeasurementUnitInput measurementUnit) { + protected static Try check(MeasurementUnitInput measurementUnit) { try { checkNonNull(measurementUnit, "a measurement unit"); } catch (InvalidEntityException e) { 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 9d011bfba..d1f676c9e 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -9,8 +9,8 @@ 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.options.Failure; -import edu.ie3.datamodel.utils.options.Try; +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; @@ -35,7 +35,7 @@ private NodeValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check(NodeInput node) { + protected static List> check(NodeInput node) { try { checkNonNull(node, "a node"); } catch (InvalidEntityException e) { @@ -45,7 +45,7 @@ protected static List> check(NodeInput node) { "Validation not possible because received object {" + node + "} was null", e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); try { checkVoltageLevel(node.getVoltLvl()); 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 b938ba03c..98941f016 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -12,8 +12,8 @@ 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.options.Failure; -import edu.ie3.datamodel.utils.options.Try; +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; @@ -41,8 +41,7 @@ private SystemParticipantValidationUtils() { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> check( - SystemParticipantInput systemParticipant) { + protected static List> check(SystemParticipantInput systemParticipant) { try { checkNonNull(systemParticipant, "a system participant"); } catch (InvalidEntityException e) { @@ -55,7 +54,7 @@ protected static List> check( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (systemParticipant.getqCharacteristics() == null) { exceptions.add( @@ -85,7 +84,7 @@ protected static List> check( } else if (WecInput.class.isAssignableFrom(systemParticipant.getClass())) { exceptions.addAll(checkWec((WecInput) systemParticipant)); } else if (EvcsInput.class.isAssignableFrom(systemParticipant.getClass())) { - exceptions.add(Try.apply(SystemParticipantValidationUtils::checkEvcs)); + exceptions.add(Try.ofVoid(SystemParticipantValidationUtils::checkEvcs)); } else { exceptions.add( new Failure<>( @@ -111,7 +110,7 @@ protected static List> check( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkType( + protected static List> checkType( SystemParticipantTypeInput systemParticipantTypeInput) { try { checkNonNull(systemParticipantTypeInput, "a system participant type"); @@ -125,7 +124,7 @@ protected static List> checkType( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if ((systemParticipantTypeInput.getCapex() == null) || (systemParticipantTypeInput.getOpex() == null) @@ -137,7 +136,7 @@ protected static List> checkType( } exceptions.add( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] { @@ -148,7 +147,7 @@ protected static List> checkType( systemParticipantTypeInput))); exceptions.add( - Try.apply( + Try.ofVoid( () -> checkRatedPowerFactor( systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated()))); @@ -185,7 +184,7 @@ protected static List> checkType( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkBm(BmInput bmInput) { + private static List> checkBm(BmInput bmInput) { return checkType(bmInput.getType()); } @@ -198,13 +197,13 @@ private static List> checkBm(BmInput bmInput) * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkBmType(BmTypeInput bmTypeInput) { + private static List> checkBmType(BmTypeInput bmTypeInput) { return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput)), - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( bmTypeInput, bmTypeInput.getEtaConv(), "Efficiency of inverter"))); @@ -219,7 +218,7 @@ private static List> checkBmType(BmTypeInput b * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkChp(ChpInput chpInput) { + private static List> checkChp(ChpInput chpInput) { return checkType(chpInput.getType()); } @@ -234,20 +233,20 @@ private static List> checkChp(ChpInput chpInpu * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkChpType(ChpTypeInput chpTypeInput) { + private static List> checkChpType(ChpTypeInput chpTypeInput) { return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput)), - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput)), - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency")), - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( chpTypeInput, chpTypeInput.getEtaThermal(), "Thermal efficiency"))); @@ -262,7 +261,7 @@ private static List> checkChpType(ChpTypeInput * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkEv(EvInput evInput) { + private static List> checkEv(EvInput evInput) { return checkType(evInput.getType()); } @@ -274,8 +273,8 @@ private static List> checkEv(EvInput evInput) * @param evTypeInput EvTypeInput to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkEvType(EvTypeInput evTypeInput) { - return Try.apply( + private static Try checkEvType(EvTypeInput evTypeInput) { + return Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, @@ -291,14 +290,13 @@ private static Try checkEvType(EvTypeInput evTypeI * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkFixedFeedIn( - FixedFeedInInput fixedFeedInInput) { + private static List> checkFixedFeedIn(FixedFeedInInput fixedFeedInInput) { return List.of( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput)), - Try.apply( + Try.ofVoid( () -> checkRatedPowerFactor(fixedFeedInInput, fixedFeedInInput.getCosPhiRated()))); } @@ -311,7 +309,7 @@ private static List> checkFixedFeedIn( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkHp(HpInput hpInput) { + private static List> checkHp(HpInput hpInput) { return checkType(hpInput.getType()); } @@ -322,8 +320,8 @@ private static List> checkHp(HpInput hpInput) * @param hpTypeInput HpTypeInput to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkHpType(HpTypeInput hpTypeInput) { - return Try.apply( + private static Try checkHpType(HpTypeInput hpTypeInput) { + return Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput)); @@ -340,8 +338,8 @@ private static Try checkHpType(HpTypeInput hpTypeI * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkLoad(LoadInput loadInput) { - List> exceptions = new ArrayList<>(); + private static List> checkLoad(LoadInput loadInput) { + List> exceptions = new ArrayList<>(); if (loadInput.getLoadProfile() == null) { exceptions.add( @@ -350,12 +348,12 @@ private static List> checkLoad(LoadInput loadI } exceptions.add( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, loadInput))); - exceptions.add(Try.apply(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); + exceptions.add(Try.ofVoid(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); return exceptions; } @@ -373,17 +371,18 @@ private static List> checkLoad(LoadInput loadI * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkPv(PvInput pvInput) { + private static List> checkPv(PvInput pvInput) { return List.of( - Try.apply(() -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)), - Try.apply(() -> checkAlbedo(pvInput)), - Try.apply(() -> checkAzimuth(pvInput)), - Try.apply( + Try.ofVoid( + () -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)), + Try.ofVoid(() -> checkAlbedo(pvInput)), + Try.ofVoid(() -> checkAzimuth(pvInput)), + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( pvInput, pvInput.getEtaConv(), "Efficiency of the converter")), - Try.apply(() -> checkElevationAngle(pvInput)), - Try.apply(() -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated()))); + Try.ofVoid(() -> checkElevationAngle(pvInput)), + Try.ofVoid(() -> checkRatedPowerFactor(pvInput, pvInput.getCosPhiRated()))); } /** @@ -441,7 +440,7 @@ private static void checkElevationAngle(PvInput pvInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkStorage(StorageInput storageInput) { + private static List> checkStorage(StorageInput storageInput) { return checkType(storageInput.getType()); } @@ -459,9 +458,8 @@ private static List> checkStorage(StorageInput * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkStorageType( - StorageTypeInput storageTypeInput) { - List> exceptions = new ArrayList<>(); + private static List> checkStorageType(StorageTypeInput storageTypeInput) { + List> exceptions = new ArrayList<>(); if (storageTypeInput.getLifeCycle() < 0) { exceptions.add( @@ -472,21 +470,21 @@ private static List> checkStorageType( } exceptions.add( - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getEta(), "Efficiency of the electrical converter"))); exceptions.add( - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getDod(), "Maximum permissible depth of discharge"))); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] { @@ -496,7 +494,7 @@ private static List> checkStorageType( }, storageTypeInput))); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput))); @@ -513,7 +511,7 @@ private static List> checkStorageType( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkWec(WecInput wecInput) { + private static List> checkWec(WecInput wecInput) { return checkType(wecInput.getType()); } @@ -527,13 +525,13 @@ private static List> checkWec(WecInput wecInpu * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkWecType(WecTypeInput wecTypeInput) { + private static List> checkWecType(WecTypeInput wecTypeInput) { return List.of( - Try.apply( + Try.ofVoid( () -> isBetweenZeroAndHundredPercent( wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter")), - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {wecTypeInput.getRotorArea(), wecTypeInput.getHubHeight()}, 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 877f52f85..0c3370e52 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -9,8 +9,8 @@ import edu.ie3.datamodel.exceptions.InvalidEntityException; import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.thermal.*; -import edu.ie3.datamodel.utils.options.Failure; -import edu.ie3.datamodel.utils.options.Try; +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; @@ -32,8 +32,7 @@ private ThermalUnitValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check( - ThermalUnitInput thermalUnitInput) { + protected static List> check(ThermalUnitInput thermalUnitInput) { try { checkNonNull(thermalUnitInput, "a thermal unit"); } catch (InvalidEntityException e) { @@ -46,7 +45,7 @@ private ThermalUnitValidationUtils() { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalSinkInput.class.isAssignableFrom(thermalUnitInput.getClass())) { @@ -73,8 +72,7 @@ private ThermalUnitValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - private static List> checkThermalSink( - ThermalSinkInput thermalSinkInput) { + private static List> checkThermalSink(ThermalSinkInput thermalSinkInput) { try { checkNonNull(thermalSinkInput, "a thermal sink"); } catch (InvalidEntityException e) { @@ -87,7 +85,7 @@ private ThermalUnitValidationUtils() { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) { @@ -112,8 +110,7 @@ private ThermalUnitValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - private static List> checkThermalStorage( - ThermalStorageInput thermalStorageInput) { + private static List> checkThermalStorage(ThermalStorageInput thermalStorageInput) { try { checkNonNull(thermalStorageInput, "a thermal storage"); } catch (InvalidEntityException e) { @@ -126,7 +123,7 @@ private ThermalUnitValidationUtils() { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) { @@ -153,8 +150,7 @@ private ThermalUnitValidationUtils() { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkThermalHouse( - ThermalHouseInput thermalHouseInput) { + private static List> checkThermalHouse(ThermalHouseInput thermalHouseInput) { try { checkNonNull(thermalHouseInput, "a thermal house"); } catch (InvalidEntityException e) { @@ -167,14 +163,14 @@ private static List> checkThermalHouse( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectNegativeQuantities( new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput))); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput))); @@ -208,7 +204,7 @@ private static List> checkThermalHouse( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkCylindricalStorage( + private static List> checkCylindricalStorage( CylindricalStorageInput cylindricalStorageInput) { try { checkNonNull(cylindricalStorageInput, "a cylindrical storage"); @@ -222,7 +218,7 @@ private static List> checkCylindricalStorage( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Check if inlet temperature is higher/equal to outlet temperature if (cylindricalStorageInput.getInletTemp().isLessThan(cylindricalStorageInput.getReturnTemp())) @@ -242,7 +238,7 @@ private static List> checkCylindricalStorage( cylindricalStorageInput))); exceptions.add( - Try.apply( + Try.ofVoid( () -> detectZeroOrNegativeQuantities( new Quantity[] { 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 540f4bd0b..5b2b6a6ed 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -20,9 +20,8 @@ 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.options.Failure; -import edu.ie3.datamodel.utils.options.Success; -import edu.ie3.datamodel.utils.options.Try; +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; @@ -63,14 +62,14 @@ protected static NotImplementedException checkNotImplementedException(Object obj * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - public static Try check(Object obj) { + public static Try check(Object obj) { try { checkNonNull(obj, "an object"); } catch (InvalidEntityException e) { return new Failure<>(e); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (AssetInput.class.isAssignableFrom(obj.getClass())) { exceptions.addAll(checkAsset((AssetInput) obj)); @@ -86,10 +85,9 @@ public static Try check(Object obj) { new FailedValidationException(checkNotImplementedException(obj).getMessage()))); } - List list = - exceptions.stream().filter(Try::isFailure).map(Try::getException).toList(); + List list = (List) Try.getExceptions(exceptions); - if (list.size() > 0) { + if (!list.isEmpty()) { return new Failure<>(new FailedValidationException(list)); } else { return Success.empty(); @@ -109,7 +107,7 @@ public static Try check(Object obj) { * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - private static List> checkAsset(AssetInput assetInput) { + private static List> checkAsset(AssetInput assetInput) { try { checkNonNull(assetInput, "an asset"); } catch (InvalidEntityException e) { @@ -120,7 +118,7 @@ public static Try check(Object obj) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetInput.getId() == null) { exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput))); @@ -184,8 +182,7 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - private static List> checkAssetType( - AssetTypeInput assetTypeInput) { + private static List> checkAssetType(AssetTypeInput assetTypeInput) { try { checkNonNull(assetTypeInput, "an asset type"); } catch (InvalidEntityException e) { @@ -198,7 +195,7 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetTypeInput.getUuid() == null) exceptions.add(new Failure<>(new InvalidEntityException("No UUID assigned", assetTypeInput))); @@ -234,10 +231,9 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty * Success */ - protected static List> checkIds( - Set inputs) { + protected static List> checkIds(Set inputs) { List ids = new ArrayList<>(); - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); inputs.forEach( input -> { diff --git a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index 3e5b00da2..993f5379e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy @@ -35,7 +35,7 @@ class TryTest extends Specification { def "A void method can be applied to a try object"() { when: - Try actual = Try.testForException(() -> 1) + Try actual = Try.ofVoid(() -> void) then: actual.success 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 ee577446e..0a67537b7 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -6,7 +6,7 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.ValidationException -import edu.ie3.datamodel.utils.options.Try +import edu.ie3.datamodel.utils.Try import static edu.ie3.datamodel.models.StandardUnits.* import static edu.ie3.util.quantities.PowerSystemUnits.* @@ -72,12 +72,11 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkLine() recognizes all potential errors for a line"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter {it -> it.failure}.toList() - + List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message @@ -115,11 +114,11 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2W recognizes all potential errors for a transformer2W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message @@ -161,10 +160,10 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2WType recognizes all potential errors for a transformer2W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) + Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -187,12 +186,11 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3W recognizes all potential errors for a transformer3W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: @@ -228,10 +226,10 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3WType recognizes all potential errors for a transformer3W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) + Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -254,12 +252,11 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkSwitch recognizes all potential errors for a switch"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: 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 68560a720..c68efe063 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy @@ -6,7 +6,7 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException -import edu.ie3.datamodel.utils.options.Try +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import spock.lang.Specification @@ -30,11 +30,11 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.check() recognizes all potential errors for a graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message @@ -45,11 +45,11 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkLineGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message @@ -60,11 +60,11 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkNodeGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message 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 1535687f2..90cd0fc1f 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy @@ -5,10 +5,9 @@ */ 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.utils.options.Try +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import spock.lang.Specification @@ -27,11 +26,11 @@ class MeasurementUnitValidationUtilsTest extends Specification { def "MeasurementUnitValidationUtils.check() recognizes all potential errors for a measurement unit"() { when: - Try exception = MeasurementUnitValidationUtils.check(invalidMeasurementUnit) + Try exception = MeasurementUnitValidationUtils.check(invalidMeasurementUnit) then: exception.failure - Exception ex = exception.exception + Exception ex = exception.exception() 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 bb05d9b1a..d3ef346a8 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -5,8 +5,7 @@ */ package edu.ie3.datamodel.utils.validation -import edu.ie3.datamodel.exceptions.ValidationException -import edu.ie3.datamodel.utils.options.Try +import edu.ie3.datamodel.utils.Try import static edu.ie3.util.quantities.PowerSystemUnits.KILOVOLT import static edu.ie3.util.quantities.PowerSystemUnits.PU @@ -35,11 +34,11 @@ class NodeValidationUtilsTest extends Specification { def "The check method recognizes all potential errors for a node"() { when: - List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure}.toList() + List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message 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 bfea59a64..9c70e39e4 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -7,11 +7,10 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.exceptions.NotImplementedException -import edu.ie3.datamodel.exceptions.ValidationException 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.options.Try +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 @@ -49,12 +48,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.check() recognizes all potential errors for a system participant"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: @@ -99,10 +97,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkType() recognizes all potential errors for a system participant type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidType) + Try exceptions = SystemParticipantValidationUtils.check(invalidType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -140,10 +138,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkBmType() recognizes all potential errors for a biomass power plant type"() { when: - Try exceptions = ValidationUtils.check(invalidBmType) + Try exceptions = ValidationUtils.check(invalidBmType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -180,10 +178,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkChpType() recognizes all potential errors for a CHP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -222,10 +220,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkEvType() recognizes all potential errors for an EV type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) + Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -248,12 +246,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkFixedFeedIn() recognizes all potential errors for an a Fixed Feed-In"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: @@ -290,10 +287,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkHpType() recognizes all potential errors for an HP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -316,12 +313,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkLoad() recognizes all potential errors for a load"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: @@ -346,12 +342,11 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkPV() recognizes all potential errors for a PV"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception - ex.class == expectedException.class + Exception ex = exceptions.get(0).exception() ex.message == expectedException.message where: @@ -392,10 +387,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkStorageType() recognizes all potential errors for a storage type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) + Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -435,10 +430,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkWecType() recognizes all potential errors for a wec type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) + Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) then: - Exception ex = exceptions.exception + Exception ex = exceptions.exception() ex.message.contains(expectedException.message) where: @@ -454,10 +449,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipant = new InvalidSystemParticipantInput(node) when: - List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter {it -> it.failure}.toList() then: - def e = exceptions.get(0).exception.cause + def e = exceptions.get(0).exception().cause e.message == "Cannot validate object of class 'InvalidSystemParticipantInput', as no routine is implemented." } @@ -466,10 +461,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipantInput = new InvalidSystemParticipantTypeInput() when: - Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) + Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) then: - def e = exceptions.exception + def e = exceptions.exception() e.message.contains("Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented.") } 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 ee5b52c10..a7632631c 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy @@ -6,13 +6,12 @@ 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.options.Try +import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.SystemParticipantTestData import edu.ie3.test.common.ThermalUnitInputTestData import edu.ie3.util.TimeUtil @@ -66,11 +65,11 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkThermalHouse() recognizes all potential errors for a thermal house"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter {it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message @@ -98,11 +97,11 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkCylindricalStorage() recognizes all potential errors for a thermal cylindrical storage"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter {it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception + Exception ex = exceptions.get(0).exception() ex.class == expectedException.class ex.message == expectedException.message 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 022bb3e31..3aa34493a 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -6,9 +6,8 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.UnsafeEntityException -import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.input.AssetInput -import edu.ie3.datamodel.utils.options.Try +import edu.ie3.datamodel.utils.Try import static edu.ie3.datamodel.models.StandardUnits.CONDUCTANCE_PER_LENGTH import static edu.ie3.datamodel.models.StandardUnits.ELECTRIC_CURRENT_MAGNITUDE @@ -111,11 +110,11 @@ class ValidationUtilsTest extends Specification { def "If an object can't be identified, a ValidationException is thrown as expected"() { when: - Try actual = ValidationUtils.check(invalidObject) + Try actual = ValidationUtils.check(invalidObject) then: actual.failure - Throwable ex = actual.exception + Throwable ex = actual.exception() ex.message.contains(expectedException.message) where: @@ -125,11 +124,11 @@ class ValidationUtilsTest extends Specification { def "The validation check method recognizes all potential errors for an asset"() { when: - Try actual = ValidationUtils.check(invalidAsset) + Try actual = ValidationUtils.check(invalidAsset) then: actual.failure - Exception ex = actual.exception + Exception ex = actual.exception() ex.message.contains(expectedException.message) where: @@ -221,11 +220,11 @@ class ValidationUtilsTest extends Specification { def invalidAsset = new InvalidAssetInput() when: - List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 1 - def e = exceptions.get(0).exception + def e = exceptions.get(0).exception() e.message.contains("Cannot validate object of class 'InvalidAssetInput', as no routine is implemented.") } @@ -234,11 +233,11 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput() when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 1 - def e = exceptions.get(0).exception + def e = exceptions.get(0).exception() e.message.contains("Cannot validate object of class 'InvalidAssetTypeInput', as no routine is implemented.") } @@ -247,11 +246,11 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput(UUID.randomUUID(), null) when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 2 - def e = exceptions.get(0).exception + def e = exceptions.get(0).exception() e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") } @@ -264,7 +263,7 @@ class ValidationUtilsTest extends Specification { ] when: - List> exceptions = ValidationUtils.checkIds(validAssetIds) + List> exceptions = ValidationUtils.checkIds(validAssetIds) then: exceptions.forEach {ex -> ex.success } @@ -278,11 +277,12 @@ class ValidationUtilsTest extends Specification { ] when: - List> exceptions = ValidationUtils.checkIds(invalidAssetIds) + List> exceptions = ValidationUtils.checkIds(invalidAssetIds) then: exceptions.get(0).success exceptions.get(1).failure - exceptions.get(1).exception.message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") + exceptions.get(1).exception().class == UnsafeEntityException.class + exceptions.get(1).exception().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") } } From 863b5feb2f04d2928fb972f81c36b6b5457952a6 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Wed, 26 Jul 2023 13:58:38 +0200 Subject: [PATCH 13/39] Adapting ``ValidationUtils`` to the recent changes in ``Try``. --- .../java/edu/ie3/datamodel/utils/Try.java | 26 ++- .../validation/ConnectorValidationUtils.java | 206 ++++++++--------- .../validation/GraphicValidationUtils.java | 14 +- .../GridContainerValidationUtils.java | 31 +-- .../MeasurementUnitValidationUtils.java | 3 +- .../utils/validation/NodeValidationUtils.java | 4 +- .../SystemParticipantValidationUtils.java | 207 +++++++++--------- .../ThermalUnitValidationUtils.java | 46 ++-- .../utils/validation/ValidationUtils.java | 24 +- .../ConnectorValidationUtilsTest.groovy | 12 +- .../GraphicValidationUtilsTest.groovy | 6 +- .../MeasurementUnitValidationUtilsTest.groovy | 2 +- .../validation/NodeValidationUtilsTest.groovy | 3 +- ...ystemParticipantValidationUtilsTest.groovy | 27 +-- .../ThermalUnitValidationUtilsTest.groovy | 5 +- .../validation/ValidationUtilsTest.groovy | 16 +- 16 files changed, 345 insertions(+), 287 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index 40c4f69ce..acb77fbaa 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -75,7 +75,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(); @@ -270,6 +270,20 @@ public static Try, FailureException> scanStre } } + /** + * 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 + */ + @SafeVarargs + public static List> ofVoid( + Class clazz, VoidSupplier... supplier) { + return Arrays.stream(supplier).map(sup -> Try.ofVoid(sup, clazz)).toList(); + } + /** * Method to retrieve the exceptions from all {@link Failure} objects. * @@ -379,4 +393,14 @@ 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; + } } 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 265b78261..7348ac592 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -7,6 +7,7 @@ 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; @@ -52,7 +53,7 @@ private ConnectorValidationUtils() { * @return a list of try objects either containing a {@link InvalidEntityException} or an empty * Success */ - protected static List> check(ConnectorInput connector) { + protected static List> check(ConnectorInput connector) { try { checkNonNull(connector, "a connector"); } catch (InvalidEntityException e) { @@ -63,8 +64,9 @@ protected static List> check(ConnectorInput connector) { e))); } - List> exceptions = new ArrayList<>(); - exceptions.add(Try.ofVoid(() -> connectsDifferentNodes(connector))); + List> exceptions = new ArrayList<>(); + exceptions.add( + Try.ofVoid(() -> connectsDifferentNodes(connector), InvalidEntityException.class)); // Further checks for subclasses if (LineInput.class.isAssignableFrom(connector.getClass())) { @@ -100,16 +102,20 @@ protected static List> check(ConnectorInput connector) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkLine(LineInput line) { - List> exceptions = new ArrayList<>(checkLineType(line.getType())); + private static List> checkLine(LineInput line) { + List> exceptions = + new ArrayList<>(checkLineType(line.getType())); - exceptions.add(Try.ofVoid(() -> connectsNodesInDifferentSubnets(line, false))); - exceptions.add(Try.ofVoid(() -> connectsNodesWithDifferentVoltageLevels(line, false))); - exceptions.add( + exceptions.addAll( Try.ofVoid( + InvalidEntityException.class, + () -> connectsNodesInDifferentSubnets(line, false), + () -> connectsNodesWithDifferentVoltageLevels(line, false), () -> detectZeroOrNegativeQuantities(new Quantity[] {line.getLength()}, line))); - exceptions.add(Try.ofVoid(() -> coordinatesOfLineEqualCoordinatesOfNodes(line))); - exceptions.add(Try.ofVoid(() -> lineLengthMatchesDistancesBetweenPointsOfLineString(line))); + + /* these two won't throw exceptions and will only log */ + coordinatesOfLineEqualCoordinatesOfNodes(line); + lineLengthMatchesDistancesBetweenPointsOfLineString(line); return exceptions; } @@ -128,7 +134,7 @@ private static List> checkLine(LineInput line) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkLineType(LineTypeInput lineType) { + protected static List> checkLineType(LineTypeInput lineType) { try { checkNonNull(lineType, "a line type"); } catch (InvalidEntityException e) { @@ -139,18 +145,17 @@ protected static List> checkLineType(LineTypeInput lineType) { e))); } - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] {lineType.getB(), lineType.getG()}, lineType)), - Try.ofVoid( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] { - lineType.getvRated(), lineType.getiMax(), lineType.getX(), lineType.getR() - }, - lineType))); + 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)); } /** @@ -166,14 +171,18 @@ protected static List> checkLineType(LineTypeInput lineType) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkTransformer2W(Transformer2WInput transformer2W) { - List> exceptions = new ArrayList<>(checkTransformer2WType(transformer2W.getType())); + private static List> checkTransformer2W( + Transformer2WInput transformer2W) { + List> exceptions = + new ArrayList<>(checkTransformer2WType(transformer2W.getType())); - exceptions.add(Try.ofVoid(() -> checkIfTapPositionIsWithinBounds(transformer2W))); - exceptions.add(Try.ofVoid(() -> connectsNodesWithDifferentVoltageLevels(transformer2W, true))); - exceptions.add(Try.ofVoid(() -> connectsNodesInDifferentSubnets(transformer2W, true))); - exceptions.add( - Try.ofVoid(() -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); + exceptions.addAll( + Try.ofVoid( + InvalidEntityException.class, + () -> checkIfTapPositionIsWithinBounds(transformer2W), + () -> connectsNodesWithDifferentVoltageLevels(transformer2W, true), + () -> connectsNodesInDifferentSubnets(transformer2W, true), + () -> ratedVoltageOfTransformer2WMatchesVoltagesOfNodes(transformer2W))); return exceptions; } @@ -197,7 +206,7 @@ private static List> checkTransformer2W(Transformer2WInput transformer * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkTransformer2WType( + protected static List> checkTransformer2WType( Transformer2WTypeInput transformer2WType) { try { checkNonNull(transformer2WType, "a two winding transformer type"); @@ -211,34 +220,29 @@ protected static List> checkTransformer2WType( e))); } - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] { - transformer2WType.getgM(), - transformer2WType.getdPhi(), - transformer2WType.getrSc() - }, - transformer2WType)), - Try.ofVoid( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] { - transformer2WType.getsRated(), - transformer2WType.getvRatedA(), - transformer2WType.getvRatedB(), - transformer2WType.getxSc() - }, - transformer2WType)), - Try.ofVoid( - () -> - detectPositiveQuantities( - new Quantity[] {transformer2WType.getbM()}, transformer2WType)), - Try.ofVoid(() -> checkVoltageMagnitudeChangePerTapPosition(transformer2WType)), - Try.ofVoid(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer2WType)), - Try.ofVoid( - () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer2WType))); + 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)); } /** @@ -254,10 +258,14 @@ protected static List> checkTransformer2WType( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkTransformer3W(Transformer3WInput transformer3W) { - List> exceptions = new ArrayList<>(checkTransformer3WType(transformer3W.getType())); + private static List> checkTransformer3W( + Transformer3WInput transformer3W) { + List> exceptions = + new ArrayList<>(checkTransformer3WType(transformer3W.getType())); - exceptions.add(Try.ofVoid(() -> checkIfTapPositionIsWithinBounds(transformer3W))); + exceptions.add( + Try.ofVoid( + () -> checkIfTapPositionIsWithinBounds(transformer3W), InvalidEntityException.class)); // Check if transformer connects different voltage levels if (transformer3W.getNodeA().getVoltLvl() == transformer3W.getNodeB().getVoltLvl() @@ -279,7 +287,9 @@ private static List> checkTransformer3W(Transformer3WInput transformer } exceptions.add( - Try.ofVoid(() -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W))); + Try.ofVoid( + () -> ratedVoltageOfTransformer3WMatchesVoltagesOfNodes(transformer3W), + InvalidEntityException.class)); return exceptions; } @@ -302,7 +312,7 @@ private static List> checkTransformer3W(Transformer3WInput transformer * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkTransformer3WType( + protected static List> checkTransformer3WType( Transformer3WTypeInput transformer3WType) { try { checkNonNull(transformer3WType, "a three winding transformer type"); @@ -316,38 +326,35 @@ protected static List> checkTransformer3WType( e))); } - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] {transformer3WType.getgM(), transformer3WType.getdPhi()}, - transformer3WType)), - Try.ofVoid( - () -> - 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)), - Try.ofVoid( - () -> - detectPositiveQuantities( - new Quantity[] {transformer3WType.getbM()}, transformer3WType)), - Try.ofVoid(() -> checkVoltageMagnitudeChangePerTapPosition(transformer3WType)), - Try.ofVoid(() -> checkMinimumTapPositionIsLowerThanMaximumTapPosition(transformer3WType)), - Try.ofVoid( - () -> checkNeutralTapPositionLiesBetweenMinAndMaxTapPosition(transformer3WType))); + 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)); } /** @@ -357,9 +364,9 @@ protected static List> checkTransformer3WType( * @param switchInput Switch to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkSwitch(SwitchInput switchInput) { + private static Try checkSwitch(SwitchInput switchInput) { if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) { - return new Failure<>( + return Failure.ofVoid( new InvalidEntityException("Switch connects two different voltage levels", switchInput)); } else { return Success.empty(); @@ -375,7 +382,8 @@ private static Try checkSwitch(SwitchInput switchInput) { * @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) { + protected static Try checkConnectivity( + SubGridContainer subGridContainer) { Graph graph = new SimpleGraph<>(DefaultEdge.class); subGridContainer.getRawGrid().getNodes().forEach(node -> graph.addVertex(node.getUuid())); 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 3eb2e6055..d13cb8115 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -33,7 +33,7 @@ private GraphicValidationUtils() { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> check(GraphicInput graphicInput) { + protected static List> check(GraphicInput graphicInput) { try { checkNonNull(graphicInput, "a graphic input"); } catch (InvalidEntityException e) { @@ -44,7 +44,7 @@ protected static List> check(GraphicInput graphicInput) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (graphicInput.getGraphicLayer() == null) { exceptions.add( @@ -55,9 +55,15 @@ protected static List> check(GraphicInput graphicInput) { // Further checks for subclasses if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - exceptions.add(Try.ofVoid(() -> checkLineGraphicInput((LineGraphicInput) graphicInput))); + exceptions.add( + Try.ofVoid( + () -> checkLineGraphicInput((LineGraphicInput) graphicInput), + InvalidEntityException.class)); } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - exceptions.add(Try.ofVoid(() -> checkNodeGraphicInput((NodeGraphicInput) graphicInput))); + exceptions.add( + Try.ofVoid( + () -> checkNodeGraphicInput((NodeGraphicInput) graphicInput), + InvalidEntityException.class)); } return exceptions; 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 fd7764ff1..c2e4191fb 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -45,7 +45,8 @@ private GridContainerValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check(GridContainer gridContainer) { + protected static List> check( + GridContainer gridContainer) { try { checkNonNull(gridContainer, "grid container"); } catch (InvalidEntityException e) { @@ -58,7 +59,7 @@ protected static List> check(GridContainer gridContainer) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = @@ -96,7 +97,8 @@ protected static List> check(GridContainer gridContainer) { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkRawGridElements(RawGridElements rawGridElements) { + protected static List> checkRawGridElements( + RawGridElements rawGridElements) { try { checkNonNull(rawGridElements, "raw grid elements"); } catch (InvalidEntityException e) { @@ -109,7 +111,7 @@ protected static List> checkRawGridElements(RawGridElements rawGridEle e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); /* sanity check to ensure distinct UUIDs */ Optional exceptionString = @@ -217,8 +219,9 @@ protected static List> checkRawGridElements(RawGridElements rawGridEle * @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<>(); + 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())); @@ -238,7 +241,7 @@ protected static List> checkRawGridTypeIds(RawGridElements rawGridElem * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkSystemParticipants( + protected static List> checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { try { checkNonNull(systemParticipants, "system participants"); @@ -252,7 +255,7 @@ protected static List> checkSystemParticipants( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = @@ -289,12 +292,12 @@ protected static List> checkSystemParticipants( * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkSystemParticipants( + protected static List> checkSystemParticipants( Set participants, Set nodes) { return participants.stream() .map( entity -> { - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); try { checkNodeAvailability(entity, nodes); @@ -316,9 +319,9 @@ protected static List> checkSystemParticipants( * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty * Success */ - protected static List> checkSystemParticipantsTypeIds( + protected static List> checkSystemParticipantsTypeIds( SystemParticipants systemParticipants) { - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getBmPlants())); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getChpPlants())); exceptions.addAll(ValidationUtils.checkIds(systemParticipants.getEvCS())); @@ -343,7 +346,7 @@ protected static List> checkSystemParticipantsTypeIds( * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkGraphicElements( + protected static List> checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { try { checkNonNull(graphicElements, "graphic elements"); @@ -357,7 +360,7 @@ protected static List> checkGraphicElements( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = 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 92f4f9f5f..92f73db35 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -27,7 +27,8 @@ private MeasurementUnitValidationUtils() { * @param measurementUnit Measurement unit to validate * @return a try object either containing an {@link ValidationException} or an empty Success */ - protected static Try check(MeasurementUnitInput measurementUnit) { + protected static Try check( + MeasurementUnitInput measurementUnit) { try { checkNonNull(measurementUnit, "a measurement unit"); } catch (InvalidEntityException e) { 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 d1f676c9e..2c8698412 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -35,7 +35,7 @@ private NodeValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check(NodeInput node) { + protected static List> check(NodeInput node) { try { checkNonNull(node, "a node"); } catch (InvalidEntityException e) { @@ -45,7 +45,7 @@ protected static List> check(NodeInput node) { "Validation not possible because received object {" + node + "} was null", e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); try { checkVoltageLevel(node.getVoltLvl()); 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 98941f016..6325ea0fb 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -9,6 +9,7 @@ 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.*; @@ -41,7 +42,8 @@ private SystemParticipantValidationUtils() { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> check(SystemParticipantInput systemParticipant) { + protected static List> check( + SystemParticipantInput systemParticipant) { try { checkNonNull(systemParticipant, "a system participant"); } catch (InvalidEntityException e) { @@ -54,7 +56,7 @@ protected static List> check(SystemParticipantInput systemParticipant) e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (systemParticipant.getqCharacteristics() == null) { exceptions.add( @@ -84,7 +86,9 @@ protected static List> check(SystemParticipantInput 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)); + exceptions.add( + Try.ofVoid(SystemParticipantValidationUtils::checkEvcs, NotImplementedException.class) + .transformF(e -> new InvalidEntityException(e.getMessage(), e.getCause()))); } else { exceptions.add( new Failure<>( @@ -110,7 +114,7 @@ protected static List> check(SystemParticipantInput systemParticipant) * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - protected static List> checkType( + protected static List> checkType( SystemParticipantTypeInput systemParticipantTypeInput) { try { checkNonNull(systemParticipantTypeInput, "a system participant type"); @@ -124,7 +128,7 @@ protected static List> checkType( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if ((systemParticipantTypeInput.getCapex() == null) || (systemParticipantTypeInput.getOpex() == null) @@ -135,22 +139,30 @@ protected static List> checkType( "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); } - exceptions.add( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] { - systemParticipantTypeInput.getCapex(), - systemParticipantTypeInput.getOpex(), - systemParticipantTypeInput.getsRated() - }, - 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()))); + systemParticipantTypeInput, systemParticipantTypeInput.getCosPhiRated()), + InvalidEntityException.class)); if (BmTypeInput.class.isAssignableFrom(systemParticipantTypeInput.getClass())) { exceptions.addAll(checkBmType((BmTypeInput) systemParticipantTypeInput)); @@ -184,7 +196,7 @@ protected static List> checkType( * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkBm(BmInput bmInput) { + private static List> checkBm(BmInput bmInput) { return checkType(bmInput.getType()); } @@ -197,16 +209,15 @@ private static List> checkBm(BmInput bmInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkBmType(BmTypeInput bmTypeInput) { - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] {bmTypeInput.getActivePowerGradient()}, bmTypeInput)), - Try.ofVoid( - () -> - 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")); } /** @@ -218,7 +229,7 @@ private static List> checkBmType(BmTypeInput bmTypeInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkChp(ChpInput chpInput) { + private static List> checkChp(ChpInput chpInput) { return checkType(chpInput.getType()); } @@ -233,23 +244,19 @@ private static List> checkChp(ChpInput chpInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkChpType(ChpTypeInput chpTypeInput) { - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities(new Quantity[] {chpTypeInput.getpOwn()}, chpTypeInput)), - Try.ofVoid( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] {chpTypeInput.getpThermal()}, chpTypeInput)), - Try.ofVoid( - () -> - isBetweenZeroAndHundredPercent( - chpTypeInput, chpTypeInput.getEtaEl(), "Electrical efficiency")), - Try.ofVoid( - () -> - 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")); } /** @@ -261,7 +268,7 @@ private static List> checkChpType(ChpTypeInput chpTypeInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkEv(EvInput evInput) { + private static List> checkEv(EvInput evInput) { return checkType(evInput.getType()); } @@ -273,12 +280,12 @@ private static List> checkEv(EvInput evInput) { * @param evTypeInput EvTypeInput to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkEvType(EvTypeInput evTypeInput) { + private static Try checkEvType(EvTypeInput evTypeInput) { return Try.ofVoid( () -> detectZeroOrNegativeQuantities( - new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, - evTypeInput)); + new Quantity[] {evTypeInput.geteStorage(), evTypeInput.geteCons()}, evTypeInput), + InvalidEntityException.class); } /** @@ -290,14 +297,14 @@ private static Try checkEvType(EvTypeInput evTypeInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkFixedFeedIn(FixedFeedInInput fixedFeedInInput) { - return List.of( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] {fixedFeedInInput.getsRated()}, fixedFeedInInput)), - Try.ofVoid( - () -> 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())); } /** @@ -309,7 +316,7 @@ private static List> checkFixedFeedIn(FixedFeedInInput fixedFeedInInpu * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkHp(HpInput hpInput) { + private static List> checkHp(HpInput hpInput) { return checkType(hpInput.getType()); } @@ -320,11 +327,12 @@ private static List> checkHp(HpInput hpInput) { * @param hpTypeInput HpTypeInput to validate * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ - private static Try checkHpType(HpTypeInput hpTypeInput) { + private static Try checkHpType(HpTypeInput hpTypeInput) { return Try.ofVoid( () -> detectZeroOrNegativeQuantities( - new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput)); + new Quantity[] {hpTypeInput.getpThermal()}, hpTypeInput), + InvalidEntityException.class); } /** @@ -338,8 +346,8 @@ private static Try checkHpType(HpTypeInput hpTypeInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkLoad(LoadInput loadInput) { - List> exceptions = new ArrayList<>(); + private static List> checkLoad(LoadInput loadInput) { + List> exceptions = new ArrayList<>(); if (loadInput.getLoadProfile() == null) { exceptions.add( @@ -347,13 +355,14 @@ private static List> checkLoad(LoadInput loadInput) { new InvalidEntityException("No standard load profile defined for load", loadInput))); } - exceptions.add( + exceptions.addAll( Try.ofVoid( + InvalidEntityException.class, () -> detectNegativeQuantities( new Quantity[] {loadInput.getsRated(), loadInput.geteConsAnnual()}, - loadInput))); - exceptions.add(Try.ofVoid(() -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); + loadInput), + () -> checkRatedPowerFactor(loadInput, loadInput.getCosPhiRated()))); return exceptions; } @@ -371,18 +380,17 @@ private static List> checkLoad(LoadInput loadInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkPv(PvInput pvInput) { - return List.of( - Try.ofVoid( - () -> detectNegativeQuantities(new Quantity[] {pvInput.getsRated()}, pvInput)), - Try.ofVoid(() -> checkAlbedo(pvInput)), - Try.ofVoid(() -> checkAzimuth(pvInput)), - Try.ofVoid( - () -> - isBetweenZeroAndHundredPercent( - pvInput, pvInput.getEtaConv(), "Efficiency of the converter")), - Try.ofVoid(() -> checkElevationAngle(pvInput)), - Try.ofVoid(() -> 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())); } /** @@ -440,7 +448,7 @@ private static void checkElevationAngle(PvInput pvInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkStorage(StorageInput storageInput) { + private static List> checkStorage(StorageInput storageInput) { return checkType(storageInput.getType()); } @@ -458,8 +466,9 @@ private static List> checkStorage(StorageInput storageInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkStorageType(StorageTypeInput storageTypeInput) { - List> exceptions = new ArrayList<>(); + private static List> checkStorageType( + StorageTypeInput storageTypeInput) { + List> exceptions = new ArrayList<>(); if (storageTypeInput.getLifeCycle() < 0) { exceptions.add( @@ -469,22 +478,19 @@ private static List> checkStorageType(StorageTypeInput storageTypeInpu storageTypeInput))); } - exceptions.add( + exceptions.addAll( Try.ofVoid( + InvalidEntityException.class, () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getEta(), - "Efficiency of the electrical converter"))); - exceptions.add( - Try.ofVoid( + "Efficiency of the electrical converter"), () -> isBetweenZeroAndHundredPercent( storageTypeInput, storageTypeInput.getDod(), - "Maximum permissible depth of discharge"))); - exceptions.add( - Try.ofVoid( + "Maximum permissible depth of discharge"), () -> detectNegativeQuantities( new Quantity[] { @@ -492,9 +498,7 @@ private static List> checkStorageType(StorageTypeInput storageTypeInpu storageTypeInput.getActivePowerGradient(), storageTypeInput.getLifeTime() }, - storageTypeInput))); - exceptions.add( - Try.ofVoid( + storageTypeInput), () -> detectZeroOrNegativeQuantities( new Quantity[] {storageTypeInput.geteStorage()}, storageTypeInput))); @@ -511,7 +515,7 @@ private static List> checkStorageType(StorageTypeInput storageTypeInpu * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkWec(WecInput wecInput) { + private static List> checkWec(WecInput wecInput) { return checkType(wecInput.getType()); } @@ -525,17 +529,16 @@ private static List> checkWec(WecInput wecInput) { * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkWecType(WecTypeInput wecTypeInput) { - return List.of( - Try.ofVoid( - () -> - isBetweenZeroAndHundredPercent( - wecTypeInput, wecTypeInput.getEtaConv(), "Efficiency of the converter")), - Try.ofVoid( - () -> - 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 */ 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 0c3370e52..8b72b41fd 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -32,7 +32,8 @@ private ThermalUnitValidationUtils() { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> check(ThermalUnitInput thermalUnitInput) { + protected static List> check( + ThermalUnitInput thermalUnitInput) { try { checkNonNull(thermalUnitInput, "a thermal unit"); } catch (InvalidEntityException e) { @@ -45,7 +46,7 @@ protected static List> check(ThermalUnitInput thermalUnitInput) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalSinkInput.class.isAssignableFrom(thermalUnitInput.getClass())) { @@ -72,7 +73,8 @@ protected static List> check(ThermalUnitInput thermalUnitInput) { * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - private static List> checkThermalSink(ThermalSinkInput thermalSinkInput) { + private static List> checkThermalSink( + ThermalSinkInput thermalSinkInput) { try { checkNonNull(thermalSinkInput, "a thermal sink"); } catch (InvalidEntityException e) { @@ -85,7 +87,7 @@ private static List> checkThermalSink(ThermalSinkInput thermalSinkInpu e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (ThermalHouseInput.class.isAssignableFrom(thermalSinkInput.getClass())) { @@ -110,7 +112,8 @@ private static List> checkThermalSink(ThermalSinkInput thermalSinkInpu * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - private static List> checkThermalStorage(ThermalStorageInput thermalStorageInput) { + private static List> checkThermalStorage( + ThermalStorageInput thermalStorageInput) { try { checkNonNull(thermalStorageInput, "a thermal storage"); } catch (InvalidEntityException e) { @@ -123,7 +126,7 @@ private static List> checkThermalStorage(ThermalStorageInput thermalSt e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Further checks for subclasses if (CylindricalStorageInput.class.isAssignableFrom(thermalStorageInput.getClass())) { @@ -150,7 +153,8 @@ private static List> checkThermalStorage(ThermalStorageInput thermalSt * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkThermalHouse(ThermalHouseInput thermalHouseInput) { + private static List> checkThermalHouse( + ThermalHouseInput thermalHouseInput) { try { checkNonNull(thermalHouseInput, "a thermal house"); } catch (InvalidEntityException e) { @@ -163,17 +167,16 @@ private static List> checkThermalHouse(ThermalHouseInput thermalHouseI e))); } - List> exceptions = new ArrayList<>(); - exceptions.add( - Try.ofVoid( - () -> - detectNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput))); - exceptions.add( - Try.ofVoid( - () -> - detectZeroOrNegativeQuantities( - new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput))); + List> exceptions = + new ArrayList<>( + Try.ofVoid( + InvalidEntityException.class, + () -> + detectNegativeQuantities( + new Quantity[] {thermalHouseInput.getEthLosses()}, thermalHouseInput), + () -> + detectZeroOrNegativeQuantities( + new Quantity[] {thermalHouseInput.getEthCapa()}, thermalHouseInput))); if (thermalHouseInput .getLowerTemperatureLimit() @@ -204,7 +207,7 @@ private static List> checkThermalHouse(ThermalHouseInput thermalHouseI * @return a list of try objects either containing an {@link InvalidEntityException} or an empty * Success */ - private static List> checkCylindricalStorage( + private static List> checkCylindricalStorage( CylindricalStorageInput cylindricalStorageInput) { try { checkNonNull(cylindricalStorageInput, "a cylindrical storage"); @@ -218,7 +221,7 @@ private static List> checkCylindricalStorage( e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // Check if inlet temperature is higher/equal to outlet temperature if (cylindricalStorageInput.getInletTemp().isLessThan(cylindricalStorageInput.getReturnTemp())) @@ -246,7 +249,8 @@ private static List> checkCylindricalStorage( cylindricalStorageInput.getStorageVolumeLvlMin(), cylindricalStorageInput.getC() }, - cylindricalStorageInput))); + 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 5b2b6a6ed..cea2ff6a7 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -62,14 +62,14 @@ protected static NotImplementedException checkNotImplementedException(Object obj * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - public static Try check(Object obj) { + public static Try check(Object obj) { try { checkNonNull(obj, "an object"); } catch (InvalidEntityException e) { return new Failure<>(e); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (AssetInput.class.isAssignableFrom(obj.getClass())) { exceptions.addAll(checkAsset((AssetInput) obj)); @@ -85,7 +85,11 @@ public static Try check(Object obj) { new FailedValidationException(checkNotImplementedException(obj).getMessage()))); } - List list = (List) Try.getExceptions(exceptions); + List list = + exceptions.stream() + .filter(Try::isFailure) + .map(t -> ((Failure) t).get()) + .toList(); if (!list.isEmpty()) { return new Failure<>(new FailedValidationException(list)); @@ -107,7 +111,7 @@ public static Try check(Object obj) { * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - private static List> checkAsset(AssetInput assetInput) { + private static List> checkAsset(AssetInput assetInput) { try { checkNonNull(assetInput, "an asset"); } catch (InvalidEntityException e) { @@ -118,7 +122,7 @@ private static List> checkAsset(AssetInput assetInput) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetInput.getId() == null) { exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput))); @@ -182,7 +186,8 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) * @return a list of try objects either containing a {@link ValidationException} or an empty * Success */ - private static List> checkAssetType(AssetTypeInput assetTypeInput) { + private static List> checkAssetType( + AssetTypeInput assetTypeInput) { try { checkNonNull(assetTypeInput, "an asset type"); } catch (InvalidEntityException e) { @@ -195,7 +200,7 @@ private static List> checkAssetType(AssetTypeInput assetTypeInput) { e))); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); if (assetTypeInput.getUuid() == null) exceptions.add(new Failure<>(new InvalidEntityException("No UUID assigned", assetTypeInput))); @@ -231,9 +236,10 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla * @return a list of try objects either containing an {@link UnsafeEntityException} or an empty * Success */ - protected static List> checkIds(Set inputs) { + protected static List> checkIds( + Set inputs) { List ids = new ArrayList<>(); - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); inputs.forEach( input -> { 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 0a67537b7..5c0ca003d 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -72,7 +72,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkLine() recognizes all potential errors for a line"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -114,7 +114,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2W recognizes all potential errors for a transformer2W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -160,7 +160,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2WType recognizes all potential errors for a transformer2W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) + Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) then: Exception ex = exceptions.exception() @@ -186,7 +186,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3W recognizes all potential errors for a transformer3W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -226,7 +226,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3WType recognizes all potential errors for a transformer3W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) + Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) then: Exception ex = exceptions.exception() @@ -252,7 +252,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkSwitch recognizes all potential errors for a switch"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize 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 c68efe063..6783461f5 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy @@ -30,7 +30,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.check() recognizes all potential errors for a graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -45,7 +45,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkLineGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -60,7 +60,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkNodeGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize 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 90cd0fc1f..de37fcf9e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy @@ -26,7 +26,7 @@ class MeasurementUnitValidationUtilsTest extends Specification { def "MeasurementUnitValidationUtils.check() recognizes all potential errors for a measurement unit"() { when: - Try exception = MeasurementUnitValidationUtils.check(invalidMeasurementUnit) + Try exception = MeasurementUnitValidationUtils.check(invalidMeasurementUnit) then: exception.failure 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 d3ef346a8..abdb89aa6 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.utils.validation +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.utils.Try import static edu.ie3.util.quantities.PowerSystemUnits.KILOVOLT @@ -34,7 +35,7 @@ class NodeValidationUtilsTest extends Specification { def "The check method recognizes all potential errors for a node"() { when: - List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure}.toList() + List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure}.toList() then: exceptions.size() == expectedSize 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 9c70e39e4..b4394c5ed 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -7,6 +7,7 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.exceptions.NotImplementedException +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.input.NodeInput import edu.ie3.datamodel.models.input.system.characteristic.WecCharacteristicInput import edu.ie3.datamodel.models.input.system.type.* @@ -48,7 +49,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.check() recognizes all potential errors for a system participant"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -97,7 +98,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkType() recognizes all potential errors for a system participant type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidType) + Try exceptions = SystemParticipantValidationUtils.check(invalidType) then: Exception ex = exceptions.exception() @@ -138,7 +139,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkBmType() recognizes all potential errors for a biomass power plant type"() { when: - Try exceptions = ValidationUtils.check(invalidBmType) + Try exceptions = ValidationUtils.check(invalidBmType) then: Exception ex = exceptions.exception() @@ -178,7 +179,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkChpType() recognizes all potential errors for a CHP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) then: Exception ex = exceptions.exception() @@ -220,7 +221,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkEvType() recognizes all potential errors for an EV type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) + Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) then: Exception ex = exceptions.exception() @@ -246,7 +247,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkFixedFeedIn() recognizes all potential errors for an a Fixed Feed-In"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -287,7 +288,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkHpType() recognizes all potential errors for an HP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) + Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) then: Exception ex = exceptions.exception() @@ -313,7 +314,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkLoad() recognizes all potential errors for a load"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -342,7 +343,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkPV() recognizes all potential errors for a PV"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -387,7 +388,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkStorageType() recognizes all potential errors for a storage type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) + Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) then: Exception ex = exceptions.exception() @@ -430,7 +431,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkWecType() recognizes all potential errors for a wec type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) + Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) then: Exception ex = exceptions.exception() @@ -449,7 +450,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipant = new InvalidSystemParticipantInput(node) when: - List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter {it -> it.failure}.toList() then: def e = exceptions.get(0).exception().cause @@ -461,7 +462,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipantInput = new InvalidSystemParticipantTypeInput() when: - Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) + Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) then: def e = exceptions.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 a7632631c..14f9e083e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy @@ -6,6 +6,7 @@ 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 @@ -65,7 +66,7 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkThermalHouse() recognizes all potential errors for a thermal house"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter {it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter { it -> it.failure}.toList() then: exceptions.size() == expectedSize @@ -97,7 +98,7 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkCylindricalStorage() recognizes all potential errors for a thermal cylindrical storage"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter {it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter {it -> it.failure}.toList() then: exceptions.size() == expectedSize 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 3aa34493a..1248e5403 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -6,6 +6,7 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.UnsafeEntityException +import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.input.AssetInput import edu.ie3.datamodel.utils.Try @@ -110,7 +111,7 @@ class ValidationUtilsTest extends Specification { def "If an object can't be identified, a ValidationException is thrown as expected"() { when: - Try actual = ValidationUtils.check(invalidObject) + Try actual = ValidationUtils.check(invalidObject) then: actual.failure @@ -124,7 +125,7 @@ class ValidationUtilsTest extends Specification { def "The validation check method recognizes all potential errors for an asset"() { when: - Try actual = ValidationUtils.check(invalidAsset) + Try actual = ValidationUtils.check(invalidAsset) then: actual.failure @@ -220,7 +221,7 @@ class ValidationUtilsTest extends Specification { def invalidAsset = new InvalidAssetInput() when: - List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 1 @@ -233,7 +234,7 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput() when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 1 @@ -246,7 +247,7 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput(UUID.randomUUID(), null) when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() then: exceptions.size() == 2 @@ -263,7 +264,7 @@ class ValidationUtilsTest extends Specification { ] when: - List> exceptions = ValidationUtils.checkIds(validAssetIds) + List> exceptions = ValidationUtils.checkIds(validAssetIds) then: exceptions.forEach {ex -> ex.success } @@ -277,12 +278,11 @@ class ValidationUtilsTest extends Specification { ] when: - List> exceptions = ValidationUtils.checkIds(invalidAssetIds) + List> exceptions = ValidationUtils.checkIds(invalidAssetIds) then: exceptions.get(0).success exceptions.get(1).failure - exceptions.get(1).exception().class == UnsafeEntityException.class exceptions.get(1).exception().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") } } From 403e326b8328260dfbec6d8fd9f7e5b128648889 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 14:31:07 +0200 Subject: [PATCH 14/39] Fixing some ``sonarqube`` issues. --- .../java/edu/ie3/datamodel/utils/Try.java | 172 +++++----- .../validation/ConnectorValidationUtils.java | 127 +++----- .../validation/GraphicValidationUtils.java | 52 ++- .../GridContainerValidationUtils.java | 300 +++++++----------- .../MeasurementUnitValidationUtils.java | 28 +- .../utils/validation/NodeValidationUtils.java | 50 ++- .../SystemParticipantValidationUtils.java | 84 ++--- .../ThermalUnitValidationUtils.java | 108 +++---- .../utils/validation/ValidationUtils.java | 96 +++--- .../edu/ie3/datamodel/utils/TryTest.groovy | 56 ++++ .../validation/NodeValidationUtilsTest.groovy | 6 +- .../validation/ValidationUtilsTest.groovy | 6 +- 12 files changed, 502 insertions(+), 583 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index acb77fbaa..857cce5f5 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -15,6 +15,7 @@ import java.util.stream.Stream; public abstract class Try { + // fields private final T data; private final E exception; private final boolean isEmpty; @@ -42,6 +43,8 @@ private Try(E ex) { isEmpty = true; } + // static utility methods + /** * Method to create a {@link Try} object easily. * @@ -89,6 +92,96 @@ public static Try ofVoid( } } + /** + * 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 static Try ofVoid(boolean failure, E exception) { + if (failure) { + return Failure.ofVoid(exception); + } else { + return Success.empty(); + } + } + + /** + * 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 + */ + @SafeVarargs + public static List> ofVoid( + Class clazz, VoidSupplier... supplier) { + return Arrays.stream(supplier).map(sup -> Try.ofVoid(sup, clazz)).toList(); + } + + /** + * 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(); + } + + /** + * 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())); + } + + /** + * 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)); + + 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 = 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 -> t.data)); + } + } + + // methods of try object + /** * Returns true if this object is a {@link Success} or false if this object is a {@link Failure}. */ @@ -111,7 +204,7 @@ public boolean isEmpty() { * @throws E if this object is a {@link Failure} */ public T getOrThrow() throws E { - if (data != null) { + if (isSuccess()) { return data; } else { assert exception != null; @@ -223,80 +316,10 @@ public Try transform( } } - /** - * 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())); - } - - /** - * 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)); - - 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 = 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 -> t.data)); - } - } - - /** - * 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 - */ - @SafeVarargs - public static List> ofVoid( - Class clazz, VoidSupplier... supplier) { - return Arrays.stream(supplier).map(sup -> Try.ofVoid(sup, clazz)).toList(); - } - - /** - * 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(); - } - /** Implementation of {@link Try} class. This class is used to present a successful try. */ public static final class Success extends Try { + private static final Success emptySuccess = new Success<>(null); + public Success(T data) { super(data); } @@ -321,8 +344,9 @@ public T get() { * * @param type of exception */ + @SuppressWarnings("unchecked") public static Success empty() { - return new Success<>(null); + return (Success) emptySuccess; } } 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 7348ac592..2daba3812 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -54,19 +54,14 @@ private ConnectorValidationUtils() { * Success */ protected static List> check(ConnectorInput connector) { - try { - checkNonNull(connector, "a connector"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + connector + "} was null", - e))); + Try isNull = checkNonNull(connector, "a connector"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - exceptions.add( - Try.ofVoid(() -> connectsDifferentNodes(connector), InvalidEntityException.class)); + exceptions.add(connectsDifferentNodes(connector)); // Further checks for subclasses if (LineInput.class.isAssignableFrom(connector.getClass())) { @@ -81,7 +76,7 @@ protected static List> check(ConnectorInput co exceptions.add( new Failure<>( new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(connector)))); + "Validation failed due to: ", buildNotImplementedException(connector)))); } return exceptions; @@ -135,14 +130,10 @@ private static List> checkLine(LineInput line) * Success */ protected static List> checkLineType(LineTypeInput lineType) { - try { - checkNonNull(lineType, "a line type"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + lineType + "} was null", - e))); + Try isNull = checkNonNull(lineType, "a line type"); + + if (isNull.isFailure()) { + return List.of(isNull); } return Try.ofVoid( @@ -208,16 +199,11 @@ private static List> checkTransformer2W( */ protected static List> checkTransformer2WType( Transformer2WTypeInput transformer2WType) { - try { - checkNonNull(transformer2WType, "a two winding transformer type"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + transformer2WType - + "} was null", - e))); + Try isNull = + checkNonNull(transformer2WType, "a two winding transformer type"); + + if (isNull.isFailure()) { + return List.of(isNull); } return Try.ofVoid( @@ -268,23 +254,22 @@ private static List> checkTransformer3W( () -> 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()) { - exceptions.add( - new Failure<>( - 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()) { - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Transformer connects nodes in the same subnet", 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( @@ -314,16 +299,11 @@ private static List> checkTransformer3W( */ protected static List> checkTransformer3WType( Transformer3WTypeInput transformer3WType) { - try { - checkNonNull(transformer3WType, "a three winding transformer type"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + transformer3WType - + "} was null", - e))); + Try isNull = + checkNonNull(transformer3WType, "a three winding transformer type"); + + if (isNull.isFailure()) { + return List.of(isNull); } return Try.ofVoid( @@ -365,12 +345,9 @@ protected static List> checkTransformer3WType( * @return a try object either containing an {@link InvalidEntityException} or an empty Success */ private static Try checkSwitch(SwitchInput switchInput) { - if (!switchInput.getNodeA().getVoltLvl().equals(switchInput.getNodeB().getVoltLvl())) { - return Failure.ofVoid( - new InvalidEntityException("Switch connects two different voltage levels", switchInput)); - } else { - return Success.empty(); - } + 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 */ @@ -414,15 +391,12 @@ protected static Try checkConnectivity( ConnectivityInspector inspector = new ConnectivityInspector<>(graph); - if (!inspector.isConnected()) { - return new Failure<>( - new InvalidGridException( - "The grid with subnetNo " - + subGridContainer.getSubnet() - + " is not connected! Please ensure that all elements are connected correctly!")); - } else { - return Success.empty(); - } + return Try.ofVoid( + !inspector.isConnected(), + new InvalidGridException( + "The grid with subnetNo " + + subGridContainer.getSubnet() + + " is not connected! Please ensure that all elements are connected correctly!")); } /** @@ -430,12 +404,13 @@ protected static Try checkConnectivity( * * @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() == connectorInput.getNodeB(), + new InvalidEntityException( + connectorInput.getClass().getSimpleName() + " connects the same node, but shouldn't", + connectorInput)); } /** 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 d13cb8115..8d92338fa 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -10,7 +10,6 @@ import edu.ie3.datamodel.models.input.graphics.LineGraphicInput; import edu.ie3.datamodel.models.input.graphics.NodeGraphicInput; import edu.ie3.datamodel.utils.Try; -import edu.ie3.datamodel.utils.Try.Failure; import java.util.ArrayList; import java.util.List; @@ -34,36 +33,25 @@ private GraphicValidationUtils() { * Success */ protected static List> check(GraphicInput graphicInput) { - try { - checkNonNull(graphicInput, "a graphic input"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + graphicInput + "} was null", - e))); + Try isNull = checkNonNull(graphicInput, "a graphic input"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - if (graphicInput.getGraphicLayer() == null) { - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Graphic Layer of graphic element is not defined", graphicInput))); - } + 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())) { - exceptions.add( - Try.ofVoid( - () -> checkLineGraphicInput((LineGraphicInput) graphicInput), - InvalidEntityException.class)); + exceptions.add(checkLineGraphicInput((LineGraphicInput) graphicInput)); } else if (NodeGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { - exceptions.add( - Try.ofVoid( - () -> checkNodeGraphicInput((NodeGraphicInput) graphicInput), - InvalidEntityException.class)); + exceptions.add(checkNodeGraphicInput((NodeGraphicInput) graphicInput)); } return exceptions; @@ -75,10 +63,12 @@ protected static List> check(GraphicInput grap * * @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)); } /** @@ -88,8 +78,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 c2e4191fb..55fabe117 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -16,10 +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.Failure; +import edu.ie3.datamodel.utils.Try.*; import java.util.*; import java.util.stream.Stream; @@ -47,16 +48,10 @@ private GridContainerValidationUtils() { */ protected static List> check( GridContainer gridContainer) { - try { - checkNonNull(gridContainer, "grid container"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + gridContainer - + "} was null", - e))); + Try isNull = checkNonNull(gridContainer, "grid container"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -64,13 +59,11 @@ private GridContainerValidationUtils() { /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(gridContainer.allEntitiesAsList())); - if (exceptionString.isPresent()) { - exceptions.add( - new Failure<>( - 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( @@ -99,16 +92,10 @@ private GridContainerValidationUtils() { */ protected static List> checkRawGridElements( RawGridElements rawGridElements) { - try { - checkNonNull(rawGridElements, "raw grid elements"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + rawGridElements - + "} was null", - e))); + Try isNull = checkNonNull(rawGridElements, "raw grid elements"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -116,13 +103,12 @@ private GridContainerValidationUtils() { /* sanity check to ensure distinct UUIDs */ Optional exceptionString = checkForDuplicateUuids(new HashSet<>(rawGridElements.allEntitiesAsList())); - if (exceptionString.isPresent()) { - exceptions.add( - new Failure<>( - 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(); @@ -133,11 +119,7 @@ private GridContainerValidationUtils() { .getLines() .forEach( line -> { - try { - checkNodeAvailability(line, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(line, nodes)); exceptions.addAll(ConnectorValidationUtils.check(line)); }); @@ -146,11 +128,7 @@ private GridContainerValidationUtils() { .getTransformer2Ws() .forEach( transformer -> { - try { - checkNodeAvailability(transformer, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(transformer, nodes)); exceptions.addAll(ConnectorValidationUtils.check(transformer)); }); @@ -159,11 +137,7 @@ private GridContainerValidationUtils() { .getTransformer3Ws() .forEach( transformer -> { - try { - checkNodeAvailability(transformer, nodes); - } catch (ValidationException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(transformer, nodes)); exceptions.addAll(ConnectorValidationUtils.check(transformer)); }); @@ -186,11 +160,7 @@ private GridContainerValidationUtils() { .getSwitches() .forEach( switcher -> { - try { - checkNodeAvailability(switcher, validSwitchNodes); - } catch (ValidationException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(switcher, validSwitchNodes)); exceptions.addAll(ConnectorValidationUtils.check(switcher)); }); @@ -199,11 +169,7 @@ private GridContainerValidationUtils() { .getMeasurementUnits() .forEach( measurement -> { - try { - checkNodeAvailability(measurement, nodes); - } catch (ValidationException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(measurement, nodes)); exceptions.add(MeasurementUnitValidationUtils.check(measurement)); }); @@ -243,16 +209,11 @@ protected static List> checkRawGridTypeIds( */ protected static List> checkSystemParticipants( SystemParticipants systemParticipants, Set nodes) { - try { - checkNonNull(systemParticipants, "system participants"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipants - + "} was null", - e))); + Try isNull = + checkNonNull(systemParticipants, "system participants"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -261,13 +222,12 @@ protected static List> checkRawGridTypeIds( Optional exceptionString = ValidationUtils.checkForDuplicateUuids( new HashSet<>(systemParticipants.allEntitiesAsList())); - if (exceptionString.isPresent()) { - exceptions.add( - new Failure<>( - new InvalidGridException( - duplicateUuidsString( - systemParticipants.getClass().getSimpleName(), exceptionString)))); - } + 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)); @@ -299,11 +259,7 @@ protected static List> checkRawGridTypeIds( entity -> { List> exceptions = new ArrayList<>(); - try { - checkNodeAvailability(entity, nodes); - } catch (InvalidGridException e) { - exceptions.add(new Failure<>(e)); - } + exceptions.add(checkNodeAvailability(entity, nodes)); exceptions.addAll(SystemParticipantValidationUtils.check(entity)); return exceptions; @@ -346,142 +302,112 @@ protected static List> checkSystemParticipantsT * @return a list of try objects either containing an {@link ValidationException} or an empty * Success */ - protected static List> checkGraphicElements( + protected static List> checkGraphicElements( GraphicElements graphicElements, Set nodes, Set lines) { - try { - checkNonNull(graphicElements, "graphic elements"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + graphicElements - + "} was null", - e))); + Try isNull = checkNonNull(graphicElements, "graphic elements"); + + if (isNull.isFailure()) { + return List.of(isNull); } - List> exceptions = new ArrayList<>(); + List> exceptions = new ArrayList<>(); // sanity check for distinct uuids Optional exceptionString = checkForDuplicateUuids(new HashSet<>(graphicElements.allEntitiesAsList())); - if (exceptionString.isPresent()) { - exceptions.add( - new Failure<>( - new InvalidGridException( - duplicateUuidsString( - graphicElements.getClass().getSimpleName(), exceptionString)))); - } + exceptions.add( + Try.ofVoid( + exceptionString.isPresent(), + new InvalidGridException( + duplicateUuidsString( + graphicElements.getClass().getSimpleName(), exceptionString)))); graphicElements .getNodeGraphics() .forEach( graphic -> { - try { - GraphicValidationUtils.check(graphic); - } catch (InvalidEntityException e) { - exceptions.add(new Failure<>(e)); - } - if (!nodes.contains(graphic.getNode())) { - exceptions.add( - new Failure<>( - 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 -> { - try { - GraphicValidationUtils.check(graphic); - } catch (InvalidEntityException e) { - exceptions.add(new Failure<>(e)); - } - if (!lines.contains(graphic.getLine())) { - exceptions.add( - new Failure<>( - 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()))); }); return exceptions; } /** - * 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); - } - - /** - * 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 92f73db35..f6d551104 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -10,7 +10,6 @@ import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.MeasurementUnitInput; import edu.ie3.datamodel.utils.Try; -import edu.ie3.datamodel.utils.Try.*; public class MeasurementUnitValidationUtils extends ValidationUtils { @@ -29,24 +28,17 @@ private MeasurementUnitValidationUtils() { */ protected static Try check( MeasurementUnitInput measurementUnit) { - try { - checkNonNull(measurementUnit, "a measurement unit"); - } catch (InvalidEntityException e) { - return new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + measurementUnit + "} was null", - e)); - } + Try isNull = checkNonNull(measurementUnit, "a measurement unit"); - if (!measurementUnit.getP() - && !measurementUnit.getQ() - && !measurementUnit.getVAng() - && !measurementUnit.getVMag()) { - return new Failure<>( - new UnsafeEntityException( - "Measurement Unit does not measure any values", measurementUnit)); - } else { - return Success.empty(); + 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 2c8698412..069566115 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -36,13 +36,10 @@ private NodeValidationUtils() { * Success */ protected static List> check(NodeInput node) { - try { - checkNonNull(node, "a node"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + node + "} was null", e))); + Try isNull = checkNonNull(node, "a node"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -56,24 +53,25 @@ private NodeValidationUtils() { exceptions.add(new Failure<>(invalidEntityException)); } - if (node.getvTarget() - .isLessThanOrEqualTo(Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { - exceptions.add( - new Failure<>( - new InvalidEntityException("Target voltage (p.u.) is not a positive value", node))); - } else if (node.getvTarget() - .isGreaterThan(Quantities.getQuantity(2, StandardUnits.TARGET_VOLTAGE_MAGNITUDE))) { - exceptions.add( - new Failure<>( - new UnsafeEntityException("Target voltage (p.u.) might be too high", node))); - } - if (node.getSubnet() <= 0) - exceptions.add( - new Failure<>(new InvalidEntityException("Subnet can't be zero or negative", node))); - if (node.getGeoPosition() == null) { - exceptions.add( - new Failure<>(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; } @@ -87,7 +85,7 @@ private NodeValidationUtils() { */ private static void checkVoltageLevel(VoltageLevel voltageLevel) throws InvalidEntityException, VoltageLevelException { - checkNonNull(voltageLevel, "a voltage level"); + 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 6325ea0fb..90c216413 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -44,27 +44,21 @@ private SystemParticipantValidationUtils() { */ protected static List> check( SystemParticipantInput systemParticipant) { - try { - checkNonNull(systemParticipant, "a system participant"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipant - + "} was null", - e))); + Try isNull = + checkNonNull(systemParticipant, "a system participant"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - if (systemParticipant.getqCharacteristics() == null) { - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Reactive power characteristics of system participant is not defined", - systemParticipant))); - } + 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())) { @@ -93,7 +87,7 @@ protected static List> check( exceptions.add( new Failure<>( new InvalidEntityException( - "Validation failed due to: ", checkNotImplementedException(systemParticipant)))); + "Validation failed due to: ", buildNotImplementedException(systemParticipant)))); } return exceptions; @@ -116,28 +110,22 @@ protected static List> check( */ protected static List> checkType( SystemParticipantTypeInput systemParticipantTypeInput) { - try { - checkNonNull(systemParticipantTypeInput, "a system participant type"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + systemParticipantTypeInput - + "} was null", - e))); + Try isNull = + checkNonNull(systemParticipantTypeInput, "a system participant type"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - if ((systemParticipantTypeInput.getCapex() == null) - || (systemParticipantTypeInput.getOpex() == null) - || (systemParticipantTypeInput.getsRated() == null)) { - exceptions.add( - new Failure<>( - new InvalidEntityException( - "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); - } + 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( @@ -180,7 +168,7 @@ protected static List> checkType( exceptions.add( new Failure<>( new InvalidEntityException( - checkNotImplementedException(systemParticipantTypeInput).getMessage(), + buildNotImplementedException(systemParticipantTypeInput).getMessage(), systemParticipantTypeInput))); } @@ -349,11 +337,10 @@ private static Try checkHpType(HpTypeInput hpTypeI private static List> checkLoad(LoadInput loadInput) { List> exceptions = new ArrayList<>(); - if (loadInput.getLoadProfile() == null) { - exceptions.add( - new Failure<>( - new InvalidEntityException("No standard load profile defined for load", loadInput))); - } + exceptions.add( + Try.ofVoid( + loadInput.getLoadProfile() == null, + new InvalidEntityException("No standard load profile defined for load", loadInput))); exceptions.addAll( Try.ofVoid( @@ -470,13 +457,12 @@ private static List> checkStorageType( StorageTypeInput storageTypeInput) { List> exceptions = new ArrayList<>(); - if (storageTypeInput.getLifeCycle() < 0) { - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Permissible amount of life cycles of the storage type must be zero or positive", - storageTypeInput))); - } + 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( 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 8b72b41fd..c00affedb 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -34,16 +34,10 @@ private ThermalUnitValidationUtils() { */ protected static List> check( ThermalUnitInput thermalUnitInput) { - try { - checkNonNull(thermalUnitInput, "a thermal unit"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalUnitInput - + "} was null", - e))); + Try isNull = checkNonNull(thermalUnitInput, "a thermal unit"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -57,7 +51,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - checkNotImplementedException(thermalUnitInput).getMessage()))); + buildNotImplementedException(thermalUnitInput).getMessage()))); } return exceptions; @@ -75,16 +69,10 @@ private ThermalUnitValidationUtils() { */ private static List> checkThermalSink( ThermalSinkInput thermalSinkInput) { - try { - checkNonNull(thermalSinkInput, "a thermal sink"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalSinkInput - + "} was null", - e))); + Try isNull = checkNonNull(thermalSinkInput, "a thermal sink"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -96,7 +84,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - checkNotImplementedException(thermalSinkInput).getMessage()))); + buildNotImplementedException(thermalSinkInput).getMessage()))); } return exceptions; @@ -114,16 +102,11 @@ private ThermalUnitValidationUtils() { */ private static List> checkThermalStorage( ThermalStorageInput thermalStorageInput) { - try { - checkNonNull(thermalStorageInput, "a thermal storage"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalStorageInput - + "} was null", - e))); + Try isNull = + checkNonNull(thermalStorageInput, "a thermal storage"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); @@ -135,7 +118,7 @@ private ThermalUnitValidationUtils() { exceptions.add( new Failure<>( new FailedValidationException( - checkNotImplementedException(thermalStorageInput).getMessage()))); + buildNotImplementedException(thermalStorageInput).getMessage()))); } return exceptions; @@ -155,16 +138,10 @@ private ThermalUnitValidationUtils() { */ private static List> checkThermalHouse( ThermalHouseInput thermalHouseInput) { - try { - checkNonNull(thermalHouseInput, "a thermal house"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + thermalHouseInput - + "} was null", - e))); + Try isNull = checkNonNull(thermalHouseInput, "a thermal house"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = @@ -209,36 +186,33 @@ private static List> checkThermalHouse( */ private static List> checkCylindricalStorage( CylindricalStorageInput cylindricalStorageInput) { - try { - checkNonNull(cylindricalStorageInput, "a cylindrical storage"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + cylindricalStorageInput - + "} was null", - e))); + 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())) - exceptions.add( - new Failure<>( - 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())) - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", - 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( 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 cea2ff6a7..d6ba1fedf 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -47,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.", @@ -63,10 +63,10 @@ protected static NotImplementedException checkNotImplementedException(Object obj * Success */ public static Try check(Object obj) { - try { - checkNonNull(obj, "an object"); - } catch (InvalidEntityException e) { - return new Failure<>(e); + Try isNull = checkNonNull(obj, "an object"); + + if (isNull.isFailure()) { + return isNull; } List> exceptions = new ArrayList<>(); @@ -82,7 +82,7 @@ protected static NotImplementedException checkNotImplementedException(Object obj } else { exceptions.add( new Failure<>( - new FailedValidationException(checkNotImplementedException(obj).getMessage()))); + new FailedValidationException(buildNotImplementedException(obj).getMessage()))); } List list = @@ -91,11 +91,7 @@ protected static NotImplementedException checkNotImplementedException(Object obj .map(t -> ((Failure) t).get()) .toList(); - if (!list.isEmpty()) { - return new Failure<>(new FailedValidationException(list)); - } else { - return Success.empty(); - } + return Try.ofVoid(!list.isEmpty(), new FailedValidationException(list)); } /** @@ -112,27 +108,22 @@ protected static NotImplementedException checkNotImplementedException(Object obj * Success */ private static List> checkAsset(AssetInput assetInput) { - try { - checkNonNull(assetInput, "an asset"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" + assetInput + "} was null", - e))); + Try isNull = checkNonNull(assetInput, "an asset"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - if (assetInput.getId() == null) { - exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput))); - } - if (assetInput.getOperationTime() == null) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Operation time of the asset is not defined", assetInput))); - } + exceptions.add( + Try.ofVoid( + assetInput.getId() == null, new InvalidEntityException("No ID assigned", assetInput))); + exceptions.add( + Try.ofVoid( + assetInput.getOperationTime() == null, + 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 @@ -170,7 +161,7 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) exceptions.add( new Failure<>( new FailedValidationException( - checkNotImplementedException(assetInput).getMessage()))); + buildNotImplementedException(assetInput).getMessage()))); } return exceptions; @@ -188,24 +179,22 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) */ private static List> checkAssetType( AssetTypeInput assetTypeInput) { - try { - checkNonNull(assetTypeInput, "an asset type"); - } catch (InvalidEntityException e) { - return List.of( - new Failure<>( - new InvalidEntityException( - "Validation not possible because received object {" - + assetTypeInput - + "} was null", - e))); + Try isNull = checkNonNull(assetTypeInput, "an asset type"); + + if (isNull.isFailure()) { + return List.of(isNull); } List> exceptions = new ArrayList<>(); - if (assetTypeInput.getUuid() == null) - exceptions.add(new Failure<>(new InvalidEntityException("No UUID assigned", assetTypeInput))); - if (assetTypeInput.getId() == null) - exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetTypeInput))); + 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())) @@ -223,7 +212,7 @@ else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getCla exceptions.add( new Failure<>( new FailedValidationException( - checkNotImplementedException(assetTypeInput).getMessage()))); + buildNotImplementedException(assetTypeInput).getMessage()))); } return exceptions; @@ -246,7 +235,6 @@ protected static List> checkIds( String id = input.getId(); if (!ids.contains(id)) { ids.add(id); - exceptions.add(Success.empty()); } else { exceptions.add( new Failure<>( @@ -259,15 +247,23 @@ protected static List> checkIds( } /** - * 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())); } /** diff --git a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index 86d545fc4..d4d564026 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy @@ -117,6 +117,62 @@ class TryTest extends Specification { cause.message == "source exception" } + def "A Try object can be creates by a boolean and an exception"() { + when: + def actual = Try.ofVoid(bool, ex) + + then: + actual.failure == expected + + if (expected) { + actual.exception() == ex + } + + where: + bool | ex | expected + true | new FailureException("failure") | true + false | new FailureException("no failure") | 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.forEach { + 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) 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 abdb89aa6..edc81c329 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -27,10 +27,10 @@ class NodeValidationUtilsTest extends Specification { def node = GridTestData.nodeA when: - NodeValidationUtils.check(node) + List> tries = NodeValidationUtils.check(node) then: - noExceptionThrown() + tries.forEach { it.success} } def "The check method recognizes all potential errors for a node"() { @@ -45,7 +45,7 @@ class NodeValidationUtilsTest extends Specification { where: invalidNode || expectedSize || expectedException - GridTestData.nodeA.copy().voltLvl(null).build() || 1 || new InvalidEntityException("Expected a voltage level, but got nothing. :-(", new NullPointerException()) + 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, 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 1248e5403..41c2ad772 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -281,8 +281,8 @@ class ValidationUtilsTest extends Specification { List> exceptions = ValidationUtils.checkIds(invalidAssetIds) then: - exceptions.get(0).success - exceptions.get(1).failure - exceptions.get(1).exception().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") + exceptions.size() == 1 + exceptions.get(0).failure + exceptions.get(0).exception().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") } } From d6bab5bfba2a1504676345564c35e64f765b9bbe Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 14:48:26 +0200 Subject: [PATCH 15/39] Fixing failing test. --- .../utils/validation/ValidationUtils.java | 51 ++++++++++--------- 1 file changed, 27 insertions(+), 24 deletions(-) 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 d6ba1fedf..47b611edc 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -119,30 +119,33 @@ protected static NotImplementedException buildNotImplementedException(Object obj exceptions.add( Try.ofVoid( assetInput.getId() == null, new InvalidEntityException("No ID assigned", assetInput))); - exceptions.add( - Try.ofVoid( - assetInput.getOperationTime() == null, - 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)) - exceptions.add( - new Failure<>( - new InvalidEntityException( - "Operation start time of the asset has to be before end time", - 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 From fde869992ce9eca98a32b6c167c13c3db00dc278 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 14:59:25 +0200 Subject: [PATCH 16/39] Fixing ``sonatype`` isuue. --- .../java/edu/ie3/datamodel/io/source/WeatherSource.java | 5 ++--- .../ie3/datamodel/io/source/csv/CsvIdCoordinateSource.java | 6 +++--- .../utils/validation/ConnectorValidationUtils.java | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) 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/utils/validation/ConnectorValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java index 2daba3812..d8edc2217 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -407,7 +407,7 @@ protected static Try checkConnectivity( private static Try connectsDifferentNodes( ConnectorInput connectorInput) { return Try.ofVoid( - connectorInput.getNodeA() == connectorInput.getNodeB(), + connectorInput.getNodeA().equals(connectorInput.getNodeB()), new InvalidEntityException( connectorInput.getClass().getSimpleName() + " connects the same node, but shouldn't", connectorInput)); From 8e3365fa3b98415e4935caabe40783891e6c00c4 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 15:22:23 +0200 Subject: [PATCH 17/39] Fixing ``codacy`` isuue. --- .../validation/ConnectorValidationUtilsTest.groovy | 8 ++++---- .../utils/validation/GraphicValidationUtilsTest.groovy | 6 +++--- .../utils/validation/NodeValidationUtilsTest.groovy | 4 ++-- .../SystemParticipantValidationUtilsTest.groovy | 10 +++++----- .../validation/ThermalUnitValidationUtilsTest.groovy | 4 ++-- .../utils/validation/ValidationUtilsTest.groovy | 8 ++++---- 6 files changed, 20 insertions(+), 20 deletions(-) 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 5c0ca003d..22c2d8c03 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -72,7 +72,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkLine() recognizes all potential errors for a line"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidLine).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -114,7 +114,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2W recognizes all potential errors for a transformer2W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer2W).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -186,7 +186,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3W recognizes all potential errors for a transformer3W"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidTransformer3W).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -252,7 +252,7 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkSwitch recognizes all potential errors for a switch"() { when: - List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter {it -> it.failure}.toList() + List> exceptions = ConnectorValidationUtils.check(invalidSwitch).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize 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 6783461f5..fd38a87e1 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy @@ -30,7 +30,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.check() recognizes all potential errors for a graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidGraphicInput).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -45,7 +45,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkLineGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidLineGraphicInput).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -60,7 +60,7 @@ class GraphicValidationUtilsTest extends Specification { def "GraphicValidationUtils.checkNodeGraphicInput() recognizes all potential errors for a line graphic input"() { when: - List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter {it -> it.failure}.toList() + List> exceptions = GraphicValidationUtils.check(invalidNodeGraphicInput).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize 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 edc81c329..8879f29fc 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -30,12 +30,12 @@ class NodeValidationUtilsTest extends Specification { List> tries = NodeValidationUtils.check(node) then: - tries.forEach { it.success} + tries.forEach { it.success } } def "The check method recognizes all potential errors for a node"() { when: - List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure}.toList() + List> exceptions = NodeValidationUtils.check(invalidNode).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize 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 b4394c5ed..8ce72c416 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -49,7 +49,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.check() recognizes all potential errors for a system participant"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidSystemParticipant).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -247,7 +247,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkFixedFeedIn() recognizes all potential errors for an a Fixed Feed-In"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidFixedFeedIn).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -314,7 +314,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkLoad() recognizes all potential errors for a load"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidLoad).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -343,7 +343,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkPV() recognizes all potential errors for a PV"() { when: - List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidPV).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -450,7 +450,7 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipant = new InvalidSystemParticipantInput(node) when: - List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter {it -> it.failure}.toList() + List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter { it -> it.failure }.toList() then: def e = exceptions.get(0).exception().cause 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 14f9e083e..79e16c5ed 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy @@ -66,7 +66,7 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkThermalHouse() recognizes all potential errors for a thermal house"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter { it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidThermalHouse).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize @@ -98,7 +98,7 @@ class ThermalUnitValidationUtilsTest extends Specification { def "ThermalUnitValidationUtils.checkCylindricalStorage() recognizes all potential errors for a thermal cylindrical storage"() { when: - List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter {it -> it.failure}.toList() + List> exceptions = ThermalUnitValidationUtils.check(invalidCylindricalStorage).stream().filter { it -> it.failure }.toList() then: exceptions.size() == expectedSize 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 41c2ad772..13a4f694c 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -221,7 +221,7 @@ class ValidationUtilsTest extends Specification { def invalidAsset = new InvalidAssetInput() when: - List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter { it -> it.failure }.toList() then: exceptions.size() == 1 @@ -234,7 +234,7 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput() when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter { it -> it.failure }.toList() then: exceptions.size() == 1 @@ -247,7 +247,7 @@ class ValidationUtilsTest extends Specification { def invalidAssetType = new InvalidAssetTypeInput(UUID.randomUUID(), null) when: - List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter {it -> it.failure}.toList() + List> exceptions = ValidationUtils.checkAssetType(invalidAssetType).stream().filter { it -> it.failure }.toList() then: exceptions.size() == 2 @@ -267,7 +267,7 @@ class ValidationUtilsTest extends Specification { List> exceptions = ValidationUtils.checkIds(validAssetIds) then: - exceptions.forEach {ex -> ex.success } + exceptions.forEach { ex -> ex.success } } def "Duplicate asset input ids leads to an exception"() { From d574534ec093d8e49967148e8ac1a0752159803d Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 15:35:50 +0200 Subject: [PATCH 18/39] Fixing ``sonarqube`` isuue. --- .../validation/ConnectorValidationUtils.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) 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 d8edc2217..ca038a9f7 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -475,18 +475,18 @@ private static void coordinatesOfLineEqualCoordinatesOfNodes(LineInput line) { || line.getGeoPosition() .getEndPoint() .isWithinDistance(line.getNodeA().getGeoPosition(), ALLOWED_COORDINATE_ERROR))) - logger.debug( - "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))) - logger.debug( - "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); } /** @@ -501,11 +501,9 @@ private static void lineLengthMatchesDistancesBetweenPointsOfLineString(LineInpu && line.getLength() .isGreaterThan( GeoUtils.calcHaversine(line.getGeoPosition()).multiply(ALLOWED_LENGTH_ERROR))) { - logger.debug( - "Line length is more than " - + ALLOWED_LENGTH_ERROR - + "% greater than the calculated distances between points building the line: " - + line); + logger.warn( + "Line length is more than {}% greater than the calculated distances between points building the line: {}", + ALLOWED_LENGTH_ERROR, line); } } From 32bc1bdda50ed7209d9ace437cb95c9ea89bb284 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Thu, 27 Jul 2023 18:22:44 +0200 Subject: [PATCH 19/39] Some improvements. --- .../exceptions/ValidationException.java | 2 +- .../csv/CsvJointGridContainerSource.java | 3 +- .../models/input/container/GridContainer.java | 3 +- .../input/container/InputContainer.java | 3 +- .../input/container/JointGridContainer.java | 4 ++- .../input/container/SubGridContainer.java | 6 ++-- .../utils/ContainerNodeUpdateUtil.java | 8 +++-- .../ie3/datamodel/utils/ContainerUtils.java | 17 ++++++---- .../validation/ConnectorValidationUtils.java | 27 ++++++++------- .../SystemParticipantValidationUtils.java | 12 ++++--- .../utils/validation/ValidationUtils.java | 23 ++++++------- .../edu/ie3/datamodel/utils/TryTest.groovy | 2 +- .../ConnectorValidationUtilsTest.groovy | 9 +++-- .../validation/NodeValidationUtilsTest.groovy | 2 +- ...ystemParticipantValidationUtilsTest.groovy | 33 +++++++++---------- .../validation/ValidationUtilsTest.groovy | 12 +++---- 16 files changed, 89 insertions(+), 77 deletions(-) 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/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/input/container/GridContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/GridContainer.java index b4b296671..187c6ca6a 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 @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.models.input.InputEntity; import java.util.*; @@ -174,6 +175,6 @@ public T graphics(GraphicElements graphics) { protected abstract T childInstance(); @Override - abstract GridContainer build(); + abstract GridContainer build() throws InvalidGridException; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java index b347b2f03..09308859f 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java @@ -5,6 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; +import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.models.input.InputEntity; import java.io.Serializable; import java.util.List; @@ -34,6 +35,6 @@ protected InputContainerCopyBuilder() {} protected abstract InputContainerCopyBuilder childInstance(); /** Returns the altered {@link InputContainer} */ - abstract InputContainer build(); + abstract InputContainer build() throws InvalidGridException; } } 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..ce718f4c2 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 */ 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..11f2b6c09 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); @@ -108,7 +110,7 @@ protected SubGridContainerCopyBuilder childInstance() { } @Override - SubGridContainer build() { + SubGridContainer build() throws InvalidGridException { return new SubGridContainer( getGridName(), subnet, getRawGrid(), getSystemParticipants(), getGraphics()); } 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/validation/ConnectorValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java index ca038a9f7..fb52c02a9 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -419,7 +419,8 @@ private static Try connectsDifferentNodes( * @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( @@ -444,7 +445,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( @@ -512,7 +513,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( @@ -525,7 +527,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( @@ -539,7 +542,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(), @@ -561,7 +564,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(), @@ -588,7 +591,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( @@ -603,7 +606,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( @@ -617,7 +620,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); @@ -629,7 +632,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); @@ -641,7 +644,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( @@ -655,7 +658,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/SystemParticipantValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java index 90c216413..b15b81510 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -385,7 +385,7 @@ private static List> 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 " @@ -399,7 +399,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( @@ -414,7 +414,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() @@ -541,7 +541,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", @@ -556,7 +557,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/ValidationUtils.java b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java index 47b611edc..c8b666e5a 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -59,15 +59,9 @@ protected static NotImplementedException buildNotImplementedException(Object obj * fulfill the checking task, based on the class of the given object. * * @param obj Object to check - * @return a list of try objects either containing a {@link ValidationException} or an empty - * Success */ - public static Try check(Object obj) { - Try isNull = checkNonNull(obj, "an object"); - - if (isNull.isFailure()) { - return isNull; - } + public static void check(Object obj) throws ValidationException { + checkNonNull(obj, "an object").getOrThrow(); List> exceptions = new ArrayList<>(); @@ -91,7 +85,7 @@ protected static NotImplementedException buildNotImplementedException(Object obj .map(t -> ((Failure) t).get()) .toList(); - return Try.ofVoid(!list.isEmpty(), new FailedValidationException(list)); + Try.ofVoid(!list.isEmpty(), new FailedValidationException(list)).getOrThrow(); } /** @@ -276,7 +270,8 @@ protected static Try checkNonNull( * @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"); @@ -290,7 +285,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"); @@ -301,7 +296,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"); @@ -317,7 +313,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/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index d4d564026..cf65e84e3 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy @@ -148,7 +148,7 @@ class TryTest extends Specification { then: failures.size() == 2 - failures.forEach { + failures.every { it.failure } } 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 22c2d8c03..8eba90dac 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -5,7 +5,6 @@ */ package edu.ie3.datamodel.utils.validation -import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.utils.Try import static edu.ie3.datamodel.models.StandardUnits.* @@ -160,10 +159,10 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer2WType recognizes all potential errors for a transformer2W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer2WType) + ConnectorValidationUtils.check(invalidTransformer2WType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -226,10 +225,10 @@ class ConnectorValidationUtilsTest extends Specification { def "ConnectorValidationUtils.checkTransformer3WType recognizes all potential errors for a transformer3W type"() { when: - Try exceptions = ConnectorValidationUtils.check(invalidTransformer3WType) + ConnectorValidationUtils.check(invalidTransformer3WType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: 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 8879f29fc..69493bd84 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -30,7 +30,7 @@ class NodeValidationUtilsTest extends Specification { List> tries = NodeValidationUtils.check(node) then: - tries.forEach { it.success } + tries.every { it.success } } def "The check method recognizes all potential errors for a node"() { 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 8ce72c416..548a7de0b 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -7,7 +7,6 @@ package edu.ie3.datamodel.utils.validation import edu.ie3.datamodel.exceptions.InvalidEntityException import edu.ie3.datamodel.exceptions.NotImplementedException -import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.input.NodeInput import edu.ie3.datamodel.models.input.system.characteristic.WecCharacteristicInput import edu.ie3.datamodel.models.input.system.type.* @@ -98,10 +97,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkType() recognizes all potential errors for a system participant type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidType) + SystemParticipantValidationUtils.check(invalidType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -139,10 +138,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkBmType() recognizes all potential errors for a biomass power plant type"() { when: - Try exceptions = ValidationUtils.check(invalidBmType) + ValidationUtils.check(invalidBmType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -179,10 +178,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkChpType() recognizes all potential errors for a CHP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidChpType) + SystemParticipantValidationUtils.check(invalidChpType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -221,10 +220,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkEvType() recognizes all potential errors for an EV type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidEvType) + SystemParticipantValidationUtils.check(invalidEvType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -288,10 +287,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkHpType() recognizes all potential errors for an HP type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidHpType) + SystemParticipantValidationUtils.check(invalidHpType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -388,10 +387,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkStorageType() recognizes all potential errors for a storage type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidStorageType) + SystemParticipantValidationUtils.check(invalidStorageType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -431,10 +430,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def "SystemParticipantValidationUtils.checkWecType() recognizes all potential errors for a wec type"() { when: - Try exceptions = SystemParticipantValidationUtils.check(invalidWecType) + SystemParticipantValidationUtils.check(invalidWecType) then: - Exception ex = exceptions.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -462,10 +461,10 @@ class SystemParticipantValidationUtilsTest extends Specification { def invalidParticipantInput = new InvalidSystemParticipantTypeInput() when: - Try exceptions = SystemParticipantValidationUtils.check(invalidParticipantInput) + SystemParticipantValidationUtils.check(invalidParticipantInput) then: - def e = exceptions.exception() + Exception e = thrown() e.message.contains("Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented.") } 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 13a4f694c..dff833f47 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -111,11 +111,10 @@ class ValidationUtilsTest extends Specification { def "If an object can't be identified, a ValidationException is thrown as expected"() { when: - Try actual = ValidationUtils.check(invalidObject) + ValidationUtils.check(invalidObject) then: - actual.failure - Throwable ex = actual.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -125,11 +124,10 @@ class ValidationUtilsTest extends Specification { def "The validation check method recognizes all potential errors for an asset"() { when: - Try actual = ValidationUtils.check(invalidAsset) + ValidationUtils.check(invalidAsset) then: - actual.failure - Exception ex = actual.exception() + Exception ex = thrown() ex.message.contains(expectedException.message) where: @@ -267,7 +265,7 @@ class ValidationUtilsTest extends Specification { List> exceptions = ValidationUtils.checkIds(validAssetIds) then: - exceptions.forEach { ex -> ex.success } + exceptions.every { ex -> ex.success } } def "Duplicate asset input ids leads to an exception"() { From 0f7ee8f010b4b5918246add0ca14ceab811f8dd3 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Fri, 28 Jul 2023 16:29:55 +0200 Subject: [PATCH 20/39] Some improvements. --- .../input/container/GraphicElements.java | 7 +---- .../input/container/InputContainer.java | 8 +++--- .../input/container/RawGridElements.java | 15 ++++------- .../input/container/SystemParticipants.java | 27 ++++++++----------- .../models/input/container/ThermalGrid.java | 9 ++----- .../models/input/container/ThermalUnits.java | 7 +---- .../io/source/csv/CsvRawGridSourceTest.groovy | 10 +++---- ...setInput.groovy => DummyAssetInput.groovy} | 13 ++++++--- .../utils/validation/InvalidAssetInput.groovy | 27 ------------------- .../validation/ValidationUtilsTest.groovy | 16 ++++++----- 10 files changed, 49 insertions(+), 90 deletions(-) rename src/test/groovy/edu/ie3/datamodel/utils/validation/{ValidAssetInput.groovy => DummyAssetInput.groovy} (70%) delete mode 100644 src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy 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..59719c83f 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 @@ -126,7 +126,7 @@ protected GraphicElementsCopyBuilder(GraphicElements graphicElements) { */ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphics) { this.nodeGraphics = nodeGraphics; - return childInstance(); + return this; } /** @@ -137,11 +137,6 @@ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphic */ public GraphicElementsCopyBuilder lineGraphics(Set lineGraphics) { this.lineGraphics = lineGraphics; - return childInstance(); - } - - @Override - protected GraphicElementsCopyBuilder childInstance() { return this; } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java index 09308859f..3e983c11e 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java @@ -5,7 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; -import edu.ie3.datamodel.exceptions.InvalidGridException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.InputEntity; import java.io.Serializable; import java.util.List; @@ -32,9 +32,11 @@ abstract class InputContainerCopyBuilder childInstance(); + protected InputContainerCopyBuilder childInstance() { + return this; + } /** Returns the altered {@link InputContainer} */ - abstract InputContainer build() throws InvalidGridException; + abstract InputContainer build() throws ValidationException; } } 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..d96ba39b4 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 @@ -219,7 +219,7 @@ protected RawGridElementsCopyBuilder(RawGridElements rawGridElements) { */ public RawGridElementsCopyBuilder nodes(Set nodes) { this.nodes = nodes; - return childInstance(); + return this; } /** @@ -230,7 +230,7 @@ public RawGridElementsCopyBuilder nodes(Set nodes) { */ public RawGridElementsCopyBuilder lines(Set lines) { this.lines = lines; - return childInstance(); + return this; } /** @@ -241,7 +241,7 @@ public RawGridElementsCopyBuilder lines(Set lines) { */ public RawGridElementsCopyBuilder transformers2Ws(Set transformer2Ws) { this.transformer2Ws = transformer2Ws; - return childInstance(); + return this; } /** @@ -252,7 +252,7 @@ public RawGridElementsCopyBuilder transformers2Ws(Set transf */ public RawGridElementsCopyBuilder transformer3Ws(Set transformer3Ws) { this.transformer3Ws = transformer3Ws; - return childInstance(); + return this; } /** @@ -263,7 +263,7 @@ public RawGridElementsCopyBuilder transformer3Ws(Set transfo */ public RawGridElementsCopyBuilder switches(Set switches) { this.switches = switches; - return childInstance(); + return this; } /** @@ -274,11 +274,6 @@ public RawGridElementsCopyBuilder switches(Set switches) { */ public RawGridElementsCopyBuilder measurementUnits(Set measurementUnits) { this.measurementUnits = measurementUnits; - return childInstance(); - } - - @Override - protected RawGridElementsCopyBuilder childInstance() { return this; } 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..552885f4f 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 @@ -325,7 +325,7 @@ protected SystemParticipantsCopyBuilder(SystemParticipants systemParticipants) { */ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { this.bmPlants = bmPlants; - return childInstance(); + return this; } /** @@ -336,7 +336,7 @@ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { */ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { this.chpPlants = chpPlants; - return childInstance(); + return this; } /** @@ -347,7 +347,7 @@ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { */ public SystemParticipantsCopyBuilder evCS(Set evCS) { this.evCS = evCS; - return childInstance(); + return this; } /** @@ -358,7 +358,7 @@ public SystemParticipantsCopyBuilder evCS(Set evCS) { */ public SystemParticipantsCopyBuilder evs(Set evs) { this.evs = evs; - return childInstance(); + return this; } /** @@ -369,7 +369,7 @@ public SystemParticipantsCopyBuilder evs(Set evs) { */ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeedIns) { this.fixedFeedIns = fixedFeedIns; - return childInstance(); + return this; } /** @@ -380,7 +380,7 @@ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeed */ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { this.heatPumps = heatPumps; - return childInstance(); + return this; } /** @@ -391,7 +391,7 @@ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { */ public SystemParticipantsCopyBuilder loads(Set loads) { this.loads = loads; - return childInstance(); + return this; } /** @@ -402,7 +402,7 @@ public SystemParticipantsCopyBuilder loads(Set loads) { */ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { this.pvPlants = pvPlants; - return childInstance(); + return this; } /** @@ -413,7 +413,7 @@ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { */ public SystemParticipantsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); + return this; } /** @@ -424,7 +424,7 @@ public SystemParticipantsCopyBuilder storages(Set storages) { */ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { this.wecPlants = wecPlants; - return childInstance(); + return this; } /** @@ -435,7 +435,7 @@ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { */ public SystemParticipantsCopyBuilder emSystems(Set emSystems) { this.emSystems = emSystems; - return childInstance(); + return this; } @Override @@ -453,10 +453,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..bb9b0f92b 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 @@ -85,7 +85,7 @@ protected ThermalGridCopyBuilder(ThermalGrid thermalGrid) { */ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { this.bus = bus; - return childInstance(); + return this; } /** @@ -96,7 +96,7 @@ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { */ public ThermalGridCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** @@ -107,11 +107,6 @@ public ThermalGridCopyBuilder houses(Set houses) { */ public ThermalGridCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalGridCopyBuilder childInstance() { return this; } 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..494215730 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 @@ -73,7 +73,7 @@ protected ThermalUnitsCopyBuilder(ThermalUnits thermalUnits) { */ public ThermalUnitsCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** @@ -84,11 +84,6 @@ public ThermalUnitsCopyBuilder houses(Set houses) { */ public ThermalUnitsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalUnitsCopyBuilder childInstance() { return this; } 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..a532ad4bc 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 @@ -19,6 +19,7 @@ import edu.ie3.datamodel.models.input.container.RawGridElements import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import edu.ie3.test.common.GridTestData as rgtd +import org.junit.runner.notification.Failure import spock.lang.Shared import spock.lang.Specification @@ -171,7 +172,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } @@ -371,7 +372,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } actualSet.stream().map { @@ -521,9 +522,8 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { - it.success - } + actualSet.first().failure + actualSet.last().success actualSet.stream().map { it.data() }.toList().containsAll(expectedSet) diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy similarity index 70% rename from src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy rename to src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy index 70dff1c30..d7f647f27 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy @@ -9,12 +9,19 @@ import edu.ie3.datamodel.models.input.AssetInput import java.time.ZonedDateTime -class ValidAssetInput extends AssetInput { - - ValidAssetInput(String id) { +class DummyAssetInput extends AssetInput { + DummyAssetInput(String id) { super(UUID.randomUUID(), id) } + static DummyAssetInput valid(String id) { + return new DummyAssetInput(id) + } + + static DummyAssetInput invalid() { + return new DummyAssetInput("invalid_asset") + } + @Override boolean inOperationOn(ZonedDateTime date) { throw new UnsupportedOperationException("This is a dummy class") diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy deleted file mode 100644 index 085dda21e..000000000 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy +++ /dev/null @@ -1,27 +0,0 @@ -/* - * © 2021. TU Dortmund University, - * Institute of Energy Systems, Energy Efficiency and Energy Economics, - * Research group Distribution grid planning and operation - */ -package edu.ie3.datamodel.utils.validation - -import edu.ie3.datamodel.models.input.AssetInput - -import java.time.ZonedDateTime - -class InvalidAssetInput extends AssetInput { - - InvalidAssetInput() { - super(UUID.randomUUID(), "invalid_asset") - } - - @Override - boolean inOperationOn(ZonedDateTime date) { - throw new UnsupportedOperationException("This is a dummy class") - } - - @Override - UniqueEntityBuilder copy() { - throw new UnsupportedOperationException("This is a dummy class") - } -} 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 dff833f47..361cca445 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -14,6 +14,8 @@ 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.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 @@ -216,7 +218,7 @@ class ValidationUtilsTest extends Specification { def "Checking an unsupported asset leads to an exception"() { given: - def invalidAsset = new InvalidAssetInput() + def invalidAsset = invalid() when: List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter { it -> it.failure }.toList() @@ -224,7 +226,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 1 def e = exceptions.get(0).exception() - e.message.contains("Cannot validate object of class 'InvalidAssetInput', as no routine is implemented.") + e.message.contains("Cannot validate object of class 'DummyAssetInput', as no routine is implemented.") } def "Checking an unsupported asset type leads to an exception"() { @@ -256,9 +258,9 @@ class ValidationUtilsTest extends Specification { def "Checking if asset input ids are unique"() { given: Set validAssetIds = [ - new ValidAssetInput("first"), - new ValidAssetInput("second"), - new ValidAssetInput("third") + valid("first"), + valid("second"), + valid("third") ] when: @@ -271,8 +273,8 @@ class ValidationUtilsTest extends Specification { def "Duplicate asset input ids leads to an exception"() { given: Set invalidAssetIds = [ - new InvalidAssetInput(), - new InvalidAssetInput() + invalid(), + invalid() ] when: From 807ac08b4947a155b9a235f6f329237326010a9d Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Fri, 28 Jul 2023 16:32:35 +0200 Subject: [PATCH 21/39] Some improvements. --- .../input/container/GraphicElements.java | 7 +---- .../input/container/InputContainer.java | 8 +++--- .../input/container/RawGridElements.java | 15 ++++------- .../input/container/SystemParticipants.java | 27 ++++++++----------- .../models/input/container/ThermalGrid.java | 9 ++----- .../models/input/container/ThermalUnits.java | 7 +---- .../io/source/csv/CsvRawGridSourceTest.groovy | 10 +++---- ...setInput.groovy => DummyAssetInput.groovy} | 13 ++++++--- .../utils/validation/InvalidAssetInput.groovy | 27 ------------------- .../validation/ValidationUtilsTest.groovy | 16 ++++++----- 10 files changed, 49 insertions(+), 90 deletions(-) rename src/test/groovy/edu/ie3/datamodel/utils/validation/{ValidAssetInput.groovy => DummyAssetInput.groovy} (70%) delete mode 100644 src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy 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..59719c83f 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 @@ -126,7 +126,7 @@ protected GraphicElementsCopyBuilder(GraphicElements graphicElements) { */ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphics) { this.nodeGraphics = nodeGraphics; - return childInstance(); + return this; } /** @@ -137,11 +137,6 @@ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphic */ public GraphicElementsCopyBuilder lineGraphics(Set lineGraphics) { this.lineGraphics = lineGraphics; - return childInstance(); - } - - @Override - protected GraphicElementsCopyBuilder childInstance() { return this; } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java index 09308859f..3e983c11e 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java @@ -5,7 +5,7 @@ */ package edu.ie3.datamodel.models.input.container; -import edu.ie3.datamodel.exceptions.InvalidGridException; +import edu.ie3.datamodel.exceptions.ValidationException; import edu.ie3.datamodel.models.input.InputEntity; import java.io.Serializable; import java.util.List; @@ -32,9 +32,11 @@ abstract class InputContainerCopyBuilder childInstance(); + protected InputContainerCopyBuilder childInstance() { + return this; + } /** Returns the altered {@link InputContainer} */ - abstract InputContainer build() throws InvalidGridException; + abstract InputContainer build() throws ValidationException; } } 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..d96ba39b4 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 @@ -219,7 +219,7 @@ protected RawGridElementsCopyBuilder(RawGridElements rawGridElements) { */ public RawGridElementsCopyBuilder nodes(Set nodes) { this.nodes = nodes; - return childInstance(); + return this; } /** @@ -230,7 +230,7 @@ public RawGridElementsCopyBuilder nodes(Set nodes) { */ public RawGridElementsCopyBuilder lines(Set lines) { this.lines = lines; - return childInstance(); + return this; } /** @@ -241,7 +241,7 @@ public RawGridElementsCopyBuilder lines(Set lines) { */ public RawGridElementsCopyBuilder transformers2Ws(Set transformer2Ws) { this.transformer2Ws = transformer2Ws; - return childInstance(); + return this; } /** @@ -252,7 +252,7 @@ public RawGridElementsCopyBuilder transformers2Ws(Set transf */ public RawGridElementsCopyBuilder transformer3Ws(Set transformer3Ws) { this.transformer3Ws = transformer3Ws; - return childInstance(); + return this; } /** @@ -263,7 +263,7 @@ public RawGridElementsCopyBuilder transformer3Ws(Set transfo */ public RawGridElementsCopyBuilder switches(Set switches) { this.switches = switches; - return childInstance(); + return this; } /** @@ -274,11 +274,6 @@ public RawGridElementsCopyBuilder switches(Set switches) { */ public RawGridElementsCopyBuilder measurementUnits(Set measurementUnits) { this.measurementUnits = measurementUnits; - return childInstance(); - } - - @Override - protected RawGridElementsCopyBuilder childInstance() { return this; } 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..552885f4f 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 @@ -325,7 +325,7 @@ protected SystemParticipantsCopyBuilder(SystemParticipants systemParticipants) { */ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { this.bmPlants = bmPlants; - return childInstance(); + return this; } /** @@ -336,7 +336,7 @@ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { */ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { this.chpPlants = chpPlants; - return childInstance(); + return this; } /** @@ -347,7 +347,7 @@ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { */ public SystemParticipantsCopyBuilder evCS(Set evCS) { this.evCS = evCS; - return childInstance(); + return this; } /** @@ -358,7 +358,7 @@ public SystemParticipantsCopyBuilder evCS(Set evCS) { */ public SystemParticipantsCopyBuilder evs(Set evs) { this.evs = evs; - return childInstance(); + return this; } /** @@ -369,7 +369,7 @@ public SystemParticipantsCopyBuilder evs(Set evs) { */ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeedIns) { this.fixedFeedIns = fixedFeedIns; - return childInstance(); + return this; } /** @@ -380,7 +380,7 @@ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeed */ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { this.heatPumps = heatPumps; - return childInstance(); + return this; } /** @@ -391,7 +391,7 @@ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { */ public SystemParticipantsCopyBuilder loads(Set loads) { this.loads = loads; - return childInstance(); + return this; } /** @@ -402,7 +402,7 @@ public SystemParticipantsCopyBuilder loads(Set loads) { */ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { this.pvPlants = pvPlants; - return childInstance(); + return this; } /** @@ -413,7 +413,7 @@ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { */ public SystemParticipantsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); + return this; } /** @@ -424,7 +424,7 @@ public SystemParticipantsCopyBuilder storages(Set storages) { */ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { this.wecPlants = wecPlants; - return childInstance(); + return this; } /** @@ -435,7 +435,7 @@ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { */ public SystemParticipantsCopyBuilder emSystems(Set emSystems) { this.emSystems = emSystems; - return childInstance(); + return this; } @Override @@ -453,10 +453,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..bb9b0f92b 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 @@ -85,7 +85,7 @@ protected ThermalGridCopyBuilder(ThermalGrid thermalGrid) { */ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { this.bus = bus; - return childInstance(); + return this; } /** @@ -96,7 +96,7 @@ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { */ public ThermalGridCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** @@ -107,11 +107,6 @@ public ThermalGridCopyBuilder houses(Set houses) { */ public ThermalGridCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalGridCopyBuilder childInstance() { return this; } 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..494215730 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 @@ -73,7 +73,7 @@ protected ThermalUnitsCopyBuilder(ThermalUnits thermalUnits) { */ public ThermalUnitsCopyBuilder houses(Set houses) { this.houses = houses; - return childInstance(); + return this; } /** @@ -84,11 +84,6 @@ public ThermalUnitsCopyBuilder houses(Set houses) { */ public ThermalUnitsCopyBuilder storages(Set storages) { this.storages = storages; - return childInstance(); - } - - @Override - protected ThermalUnitsCopyBuilder childInstance() { return this; } 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..a532ad4bc 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 @@ -19,6 +19,7 @@ import edu.ie3.datamodel.models.input.container.RawGridElements import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import edu.ie3.test.common.GridTestData as rgtd +import org.junit.runner.notification.Failure import spock.lang.Shared import spock.lang.Specification @@ -171,7 +172,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } @@ -371,7 +372,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { + actualSet.every { it.success } actualSet.stream().map { @@ -521,9 +522,8 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.forEach { - it.success - } + actualSet.first().failure + actualSet.last().success actualSet.stream().map { it.data() }.toList().containsAll(expectedSet) diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy similarity index 70% rename from src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy rename to src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy index 70dff1c30..d7f647f27 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidAssetInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy @@ -9,12 +9,19 @@ import edu.ie3.datamodel.models.input.AssetInput import java.time.ZonedDateTime -class ValidAssetInput extends AssetInput { - - ValidAssetInput(String id) { +class DummyAssetInput extends AssetInput { + DummyAssetInput(String id) { super(UUID.randomUUID(), id) } + static DummyAssetInput valid(String id) { + return new DummyAssetInput(id) + } + + static DummyAssetInput invalid() { + return new DummyAssetInput("invalid_asset") + } + @Override boolean inOperationOn(ZonedDateTime date) { throw new UnsupportedOperationException("This is a dummy class") diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy deleted file mode 100644 index 085dda21e..000000000 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/InvalidAssetInput.groovy +++ /dev/null @@ -1,27 +0,0 @@ -/* - * © 2021. TU Dortmund University, - * Institute of Energy Systems, Energy Efficiency and Energy Economics, - * Research group Distribution grid planning and operation - */ -package edu.ie3.datamodel.utils.validation - -import edu.ie3.datamodel.models.input.AssetInput - -import java.time.ZonedDateTime - -class InvalidAssetInput extends AssetInput { - - InvalidAssetInput() { - super(UUID.randomUUID(), "invalid_asset") - } - - @Override - boolean inOperationOn(ZonedDateTime date) { - throw new UnsupportedOperationException("This is a dummy class") - } - - @Override - UniqueEntityBuilder copy() { - throw new UnsupportedOperationException("This is a dummy class") - } -} 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 dff833f47..361cca445 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -14,6 +14,8 @@ 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.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 @@ -216,7 +218,7 @@ class ValidationUtilsTest extends Specification { def "Checking an unsupported asset leads to an exception"() { given: - def invalidAsset = new InvalidAssetInput() + def invalidAsset = invalid() when: List> exceptions = ValidationUtils.checkAsset(invalidAsset).stream().filter { it -> it.failure }.toList() @@ -224,7 +226,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 1 def e = exceptions.get(0).exception() - e.message.contains("Cannot validate object of class 'InvalidAssetInput', as no routine is implemented.") + e.message.contains("Cannot validate object of class 'DummyAssetInput', as no routine is implemented.") } def "Checking an unsupported asset type leads to an exception"() { @@ -256,9 +258,9 @@ class ValidationUtilsTest extends Specification { def "Checking if asset input ids are unique"() { given: Set validAssetIds = [ - new ValidAssetInput("first"), - new ValidAssetInput("second"), - new ValidAssetInput("third") + valid("first"), + valid("second"), + valid("third") ] when: @@ -271,8 +273,8 @@ class ValidationUtilsTest extends Specification { def "Duplicate asset input ids leads to an exception"() { given: Set invalidAssetIds = [ - new InvalidAssetInput(), - new InvalidAssetInput() + invalid(), + invalid() ] when: From 363927ca56633ecd73b7165e03c9c91321b6e3fb Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Fri, 28 Jul 2023 16:45:16 +0200 Subject: [PATCH 22/39] Fixing failing test. --- .../edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy | 2 -- 1 file changed, 2 deletions(-) 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 a532ad4bc..908deaf47 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 @@ -522,8 +522,6 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() - actualSet.first().failure - actualSet.last().success actualSet.stream().map { it.data() }.toList().containsAll(expectedSet) From 673e9d3fe2da6d1b1b46f387edb53fc2dc99cd83 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Fri, 28 Jul 2023 16:52:47 +0200 Subject: [PATCH 23/39] Fixing ``codacy`` issue. --- .../edu/ie3/datamodel/io/source/csv/CsvRawGridSourceTest.groovy | 1 - 1 file changed, 1 deletion(-) 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 908deaf47..2c9dd57dd 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 @@ -19,7 +19,6 @@ import edu.ie3.datamodel.models.input.container.RawGridElements import edu.ie3.datamodel.utils.Try import edu.ie3.test.common.GridTestData import edu.ie3.test.common.GridTestData as rgtd -import org.junit.runner.notification.Failure import spock.lang.Shared import spock.lang.Specification From ecd43a91ded96a47bbedac4f1083936e27ecd5fd Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Fri, 28 Jul 2023 21:56:36 +0200 Subject: [PATCH 24/39] Suggestion: Optimized structure of Try Removed rarely used methods of Try Enhanced tests for Try --- .../java/edu/ie3/datamodel/utils/Try.java | 215 +++++++++--------- .../LineGraphicInputFactoryTest.groovy | 8 +- .../NodeGraphicInputFactoryTest.groovy | 8 +- .../input/AssetInputEntityFactoryTest.groovy | 38 ++-- .../CylindricalStorageInputFactoryTest.groovy | 4 +- .../factory/input/LineInputFactoryTest.groovy | 12 +- .../MeasurementUnitInputFactoryTest.groovy | 4 +- .../factory/input/NodeInputFactoryTest.groovy | 4 +- .../input/OperatorInputFactoryTest.groovy | 4 +- .../input/SwitchInputFactoryTest.groovy | 4 +- .../input/ThermalBusInputFactoryTest.groovy | 4 +- .../input/ThermalHouseInputFactoryTest.groovy | 4 +- .../Transformer2WInputFactoryTest.groovy | 4 +- .../Transformer3WInputFactoryTest.groovy | 4 +- .../participant/BmInputFactoryTest.groovy | 4 +- .../participant/ChpInputFactoryTest.groovy | 4 +- .../participant/EmInputFactoryTest.groovy | 12 +- .../participant/EvInputFactoryTest.groovy | 4 +- .../participant/EvcsInputFactoryTest.groovy | 8 +- .../FixedFeedInInputFactoryTest.groovy | 6 +- .../participant/HpInputFactoryTest.groovy | 4 +- .../participant/LoadInputFactoryTest.groovy | 4 +- .../participant/PvInputFactoryTest.groovy | 4 +- .../StorageInputFactoryTest.groovy | 4 +- .../participant/WecInputFactoryTest.groovy | 4 +- .../result/ConnectorResultFactoryTest.groovy | 12 +- .../FlexOptionsResultFactoryTest.groovy | 6 +- .../result/NodeResultFactoryTest.groovy | 6 +- .../result/SwitchResultFactoryTest.groovy | 4 +- .../SystemParticipantResultFactoryTest.groovy | 18 +- .../result/ThermalResultFactoryTest.groovy | 8 +- .../CosmoIdCoordinateFactoryTest.groovy | 4 +- .../IconIdCoordinateFactoryTest.groovy | 4 +- .../typeinput/LineTypeInputFactoryTest.groovy | 4 +- ...stemParticipantTypeInputFactoryTest.groovy | 26 +-- .../Transformer2WTypeInputFactoryTest.groovy | 4 +- .../Transformer3WTypeInputFactoryTest.groovy | 4 +- .../io/source/EntitySourceTest.groovy | 2 +- .../io/source/csv/CsvGraphicSourceTest.groovy | 6 +- .../io/source/csv/CsvRawGridSourceTest.groovy | 12 +- .../csv/CsvSystemParticipantSourceTest.groovy | 68 +++--- .../source/csv/CsvTimeSeriesSourceTest.groovy | 2 +- .../edu/ie3/datamodel/utils/TryTest.groovy | 95 ++++---- .../ConnectorValidationUtilsTest.groovy | 8 +- .../GraphicValidationUtilsTest.groovy | 6 +- .../MeasurementUnitValidationUtilsTest.groovy | 2 +- .../validation/NodeValidationUtilsTest.groovy | 2 +- ...ystemParticipantValidationUtilsTest.groovy | 10 +- .../ThermalUnitValidationUtilsTest.groovy | 4 +- .../validation/ValidationUtilsTest.groovy | 8 +- 50 files changed, 350 insertions(+), 350 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index 857cce5f5..edac75b3c 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -15,33 +15,6 @@ import java.util.stream.Stream; public abstract class Try { - // fields - 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 @@ -165,7 +138,7 @@ public static Try, FailureException> scanStre assert successes != null && failures != null; if (!failures.isEmpty()) { - E first = failures.get(0).exception; + E first = ((Failure) failures.get(0)).exception; return new Failure<>( new FailureException( @@ -176,7 +149,7 @@ public static Try, FailureException> scanStre + first, first.getCause())); } else { - return new Success<>(successes.stream().map(t -> t.data)); + return new Success<>(successes.stream().map(t -> ((Success) t).data)); } } @@ -192,61 +165,19 @@ public static Try, FailureException> scanStre */ public abstract boolean isFailure(); - /** Returns true if this object is either a {@link Success} or a {@link Failure}. */ - public boolean isEmpty() { - return isEmpty; - } - /** * 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 T getOrThrow() throws E { - if (isSuccess()) { - return data; - } else { - assert exception != null; - throw exception; - } - } - - /** - * This method will return the stored data if this object is a {@link Success} or the given value. - * - * @param value that should be returned if this object is a {@link Failure} - * @return either the stored data or the given value - */ - public T getOrElse(T value) { - return data != null ? data : value; - } + public abstract T getOrThrow() throws E; /** Returns an option for data. */ - public Optional getData() { - return data != null ? Optional.of(data) : Optional.empty(); - } + public abstract Optional getData(); /** Returns an option for an exception. */ - public Optional getException() { - return exception != null ? Optional.of(exception) : Optional.empty(); - } - - /** - * Returns the data. WARNING: This method is for internal usage only and should therefore not be - * called for other purposes. - */ - T data() { - return data; - } - - /** - * Returns the exception. WARNING: This method is for internal usage only and should therefore not - * be called for other purposes. - */ - E exception() { - return exception; - } + public abstract Optional getException(); // functional methods @@ -268,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 @@ -282,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 @@ -294,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 @@ -307,21 +231,20 @@ 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 final boolean isEmpty; + private static final Success emptySuccess = new Success<>(null); public Success(T data) { - super(data); + this.data = data; + this.isEmpty = data == null; } @Override @@ -334,9 +257,53 @@ public boolean isFailure() { return false; } + /** Returns true if this object is either a {@link Success} or a {@link Failure}. */ + public boolean isEmpty() { + return isEmpty; + } + + @Override + public T getOrThrow() throws E { + return data; + } + + @Override + public Optional getData() { + return data != null ? Optional.of(data) : Optional.empty(); + } + + @Override + public Optional getException() { + return Optional.empty(); + } + + @SuppressWarnings("unchecked") + @Override + public Try flatMap(Function> mapper) { + Try, E> t = transformS(mapper); + return t instanceof Success, ?> success ? success.get() : (Try) t; + } + + @Override + public Try transformS(Function successFunc) { + return new Success<>(successFunc.apply(data)); + } + + @Override + public Try transformF( + Function failureFunc) { + return new Success<>(data); + } + + @Override + public Try transform( + Function successFunc, Function failureFunc) { + return new Success<>(successFunc.apply(data)); + } + /** Returns the stored data. */ public T get() { - return data(); + return data; } /** @@ -352,8 +319,12 @@ public static Success empty() { /** 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); + super(); + this.exception = e; } @Override @@ -366,9 +337,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; } /** @@ -393,18 +402,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()); - } } /** 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..dbe201a8e 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" + 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 2c9dd57dd..2ad9c33f1 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 @@ -175,7 +175,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { 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"() { @@ -375,7 +375,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { 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"() { @@ -522,7 +522,7 @@ class CsvRawGridSourceTest extends Specification implements CsvTestDataMeta { then: "everything is fine" actualSet.size() == expectedSet.size() actualSet.stream().map { - it.data() + it.data.get() }.toList().containsAll(expectedSet) } 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/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index cf65e84e3..f72d8759d 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") @@ -125,7 +118,7 @@ class TryTest extends Specification { actual.failure == expected if (expected) { - actual.exception() == ex + actual.exception.get() == ex } where: @@ -179,7 +172,7 @@ class TryTest extends Specification { then: actual.success - actual.empty + ((Try.Success) actual).empty actual.data.empty } @@ -212,7 +205,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"() { @@ -229,7 +221,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"() { @@ -245,7 +237,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"() { @@ -261,34 +253,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"() { @@ -296,15 +287,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 8eba90dac..b331ad4fc 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -75,7 +75,7 @@ class ConnectorValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message @@ -117,7 +117,7 @@ class ConnectorValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message @@ -189,7 +189,7 @@ class ConnectorValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: @@ -255,7 +255,7 @@ class ConnectorValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: 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 fd38a87e1..aefd2825b 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/GraphicValidationUtilsTest.groovy @@ -34,7 +34,7 @@ class GraphicValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message @@ -49,7 +49,7 @@ class GraphicValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message @@ -64,7 +64,7 @@ class GraphicValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message 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 de37fcf9e..39ea3ec89 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtilsTest.groovy @@ -30,7 +30,7 @@ class MeasurementUnitValidationUtilsTest extends Specification { then: exception.failure - Exception ex = exception.exception() + 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 69493bd84..198779672 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -39,7 +39,7 @@ class NodeValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message 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 548a7de0b..138fc2470 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -52,7 +52,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: @@ -250,7 +250,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: @@ -317,7 +317,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: @@ -346,7 +346,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.message == expectedException.message where: @@ -452,7 +452,7 @@ class SystemParticipantValidationUtilsTest extends Specification { List> exceptions = SystemParticipantValidationUtils.check(invalidParticipant).stream().filter { it -> it.failure }.toList() then: - def e = exceptions.get(0).exception().cause + def e = exceptions.get(0).exception.get().cause e.message == "Cannot validate object of class 'InvalidSystemParticipantInput', as no routine is implemented." } 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 79e16c5ed..5b991a565 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtilsTest.groovy @@ -70,7 +70,7 @@ class ThermalUnitValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message @@ -102,7 +102,7 @@ class ThermalUnitValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize - Exception ex = exceptions.get(0).exception() + Exception ex = exceptions.get(0).exception.get() ex.class == expectedException.class ex.message == expectedException.message 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 361cca445..304e2169e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -225,7 +225,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 1 - def e = exceptions.get(0).exception() + def e = exceptions.get(0).exception.get() e.message.contains("Cannot validate object of class 'DummyAssetInput', as no routine is implemented.") } @@ -238,7 +238,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 1 - def e = exceptions.get(0).exception() + def e = exceptions.get(0).exception.get() e.message.contains("Cannot validate object of class 'InvalidAssetTypeInput', as no routine is implemented.") } @@ -251,7 +251,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 2 - def e = exceptions.get(0).exception() + def e = exceptions.get(0).exception.get() e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") } @@ -283,6 +283,6 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 1 exceptions.get(0).failure - exceptions.get(0).exception().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") + exceptions.get(0).exception.get().message.contains("Entity may be unsafe because of: There is already an entity with the id invalid_asset") } } From ce7d1485bd422681aac7d38220b76373fa33f984 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Fri, 28 Jul 2023 22:19:00 +0200 Subject: [PATCH 25/39] Fixing CsvRawGridSourceTest --- .../io/source/csv/CsvRawGridSourceTest.groovy | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) 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 2ad9c33f1..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 @@ -497,33 +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.stream().map { - it.data.get() - }.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"() { From a2e0063e1ff0ef079a362dedf6dd567410ef3f47 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Fri, 28 Jul 2023 22:35:06 +0200 Subject: [PATCH 26/39] Fixing code smell --- src/main/java/edu/ie3/datamodel/utils/Try.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index edac75b3c..6df8bc7e7 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -264,7 +264,7 @@ public boolean isEmpty() { @Override public T getOrThrow() throws E { - return data; + return get(); } @Override From b52d845acc09e32c0db201ae2203a97a42a2e754 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Sun, 30 Jul 2023 13:51:07 +0200 Subject: [PATCH 27/39] Fixing codacy issue --- .../utils/validation/ValidationUtilsTest.groovy | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) 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 304e2169e..45e10c547 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -5,28 +5,23 @@ */ package edu.ie3.datamodel.utils.validation -import edu.ie3.datamodel.exceptions.UnsafeEntityException -import edu.ie3.datamodel.exceptions.ValidationException -import edu.ie3.datamodel.models.input.AssetInput -import edu.ie3.datamodel.utils.Try - -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.InvalidEntityException +import edu.ie3.datamodel.exceptions.NotImplementedException +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 From 06b406692642dd2ddb6ba1e93a77117d58c07ed5 Mon Sep 17 00:00:00 2001 From: staudtMarius Date: Sun, 30 Jul 2023 14:00:20 +0200 Subject: [PATCH 28/39] Minor changes. --- src/main/java/edu/ie3/datamodel/utils/Try.java | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/utils/Try.java b/src/main/java/edu/ie3/datamodel/utils/Try.java index 6df8bc7e7..03e44fa83 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -15,7 +15,6 @@ import java.util.stream.Stream; public abstract class Try { - // static utility methods /** @@ -236,15 +235,12 @@ public abstract Try transform( /** 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 final boolean isEmpty; private static final Success emptySuccess = new Success<>(null); public Success(T data) { this.data = data; - this.isEmpty = data == null; } @Override @@ -257,9 +253,9 @@ public boolean isFailure() { return false; } - /** Returns true if this object is either a {@link Success} or a {@link Failure}. */ + /** Returns true if this object is an empty {@link Success}. */ public boolean isEmpty() { - return isEmpty; + return data == null; } @Override @@ -269,7 +265,7 @@ public T getOrThrow() throws E { @Override public Optional getData() { - return data != null ? Optional.of(data) : Optional.empty(); + return !isEmpty() ? Optional.of(data) : Optional.empty(); } @Override @@ -319,11 +315,9 @@ public static Success empty() { /** 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(); this.exception = e; } From 7014bb627a5bfea137af8e0ef6a6243007349456 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 13:23:19 +0200 Subject: [PATCH 29/39] Renaming childInstance() to the more fitting thisInstance() Removed unnecessary type parameters and method definitions --- .../input/container/GraphicElements.java | 7 ++-- .../models/input/container/GridContainer.java | 33 +++++++++---------- .../input/container/InputContainer.java | 16 +++------ .../input/container/JointGridContainer.java | 2 +- .../input/container/RawGridElements.java | 15 ++++----- .../input/container/SubGridContainer.java | 6 ++-- .../input/container/SystemParticipants.java | 25 +++++++------- .../models/input/container/ThermalGrid.java | 10 +++--- .../models/input/container/ThermalUnits.java | 8 ++--- 9 files changed, 53 insertions(+), 69 deletions(-) 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 59719c83f..df3e39753 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 { + extends 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,7 +121,7 @@ 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; @@ -133,7 +132,7 @@ public GraphicElementsCopyBuilder nodeGraphics(Set nodeGraphic * 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; 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 187c6ca6a..e624fa4e0 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 @@ -87,8 +87,8 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - protected abstract static class GridContainerCopyBuilder> - extends InputContainerCopyBuilder { + protected abstract static class GridContainerCopyBuilder> + extends InputContainerCopyBuilder { private String gridName; private RawGridElements rawGrid; private SystemParticipants systemParticipants; @@ -100,7 +100,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 @@ -26,17 +26,9 @@ public interface InputContainer extends Serializable { * @version 3.1 * @since 14.02.23 */ - abstract class InputContainerCopyBuilder> { + abstract class InputContainerCopyBuilder> { - /** Constructor for {@link InputContainerCopyBuilder}. */ - protected InputContainerCopyBuilder() {} - - /** Returns a child instance of {@link InputContainerCopyBuilder} */ - protected InputContainerCopyBuilder childInstance() { - return this; - } - - /** Returns the altered {@link InputContainer} */ - abstract InputContainer build() throws ValidationException; + /** Returns the altered {@link InputContainer} of type {@link C} */ + abstract C 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 ce718f4c2..b8567a318 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 @@ -107,7 +107,7 @@ protected JointGridContainerCopyBuilder(JointGridContainer jointGridContainer) { } @Override - protected JointGridContainerCopyBuilder childInstance() { + protected JointGridContainerCopyBuilder thisInstance() { return this; } 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 d96ba39b4..d9b856e78 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 @@ -188,7 +188,7 @@ public int hashCode() { * @since 14.02.23 */ public static class RawGridElementsCopyBuilder - extends InputContainerCopyBuilder { + extends InputContainerCopyBuilder { private Set nodes; private Set lines; private Set transformer2Ws; @@ -202,7 +202,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,7 +214,7 @@ 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; @@ -226,7 +225,7 @@ public RawGridElementsCopyBuilder nodes(Set nodes) { * 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; @@ -237,7 +236,7 @@ public RawGridElementsCopyBuilder lines(Set lines) { * 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; @@ -248,7 +247,7 @@ public RawGridElementsCopyBuilder transformers2Ws(Set transf * 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; @@ -259,7 +258,7 @@ public RawGridElementsCopyBuilder transformer3Ws(Set transfo * 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; @@ -270,7 +269,7 @@ public RawGridElementsCopyBuilder switches(Set switches) { * 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; 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 11f2b6c09..4446ead39 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 @@ -97,15 +97,15 @@ 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; } 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 552885f4f..21df3e9da 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 { + extends 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,7 +320,7 @@ 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; @@ -332,7 +331,7 @@ public SystemParticipantsCopyBuilder bmPlants(Set bmPlants) { * 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; @@ -343,7 +342,7 @@ public SystemParticipantsCopyBuilder chpPlants(Set chpPlants) { * 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; @@ -354,7 +353,7 @@ public SystemParticipantsCopyBuilder evCS(Set evCS) { * 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; @@ -365,7 +364,7 @@ public SystemParticipantsCopyBuilder evs(Set evs) { * 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; @@ -376,7 +375,7 @@ public SystemParticipantsCopyBuilder fixedFeedIn(Set fixedFeed * 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; @@ -387,7 +386,7 @@ public SystemParticipantsCopyBuilder heatPumps(Set heatPumps) { * 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; @@ -398,7 +397,7 @@ public SystemParticipantsCopyBuilder loads(Set loads) { * 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; @@ -409,7 +408,7 @@ public SystemParticipantsCopyBuilder pvPlants(Set pvPlants) { * 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; @@ -420,7 +419,7 @@ public SystemParticipantsCopyBuilder storages(Set storages) { * 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; @@ -431,7 +430,7 @@ public SystemParticipantsCopyBuilder wecPlants(Set wecPlants) { * 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; 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 bb9b0f92b..10eeb6716 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 extends 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,7 +79,7 @@ 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; @@ -92,7 +90,7 @@ public ThermalGridCopyBuilder bus(ThermalBusInput bus) { * 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; @@ -103,7 +101,7 @@ public ThermalGridCopyBuilder houses(Set houses) { * 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; 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 494215730..ce71a2197 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 @@ -49,8 +49,7 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalUnitsCopyBuilder - extends InputContainerCopyBuilder { + public static class ThermalUnitsCopyBuilder extends InputContainerCopyBuilder { private Set houses; private Set storages; @@ -60,7 +59,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,7 +67,7 @@ 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; @@ -80,7 +78,7 @@ public ThermalUnitsCopyBuilder houses(Set houses) { * 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; From fd688fbf680ab9bd00c18a66912f7b46a9b29980 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 13:54:56 +0200 Subject: [PATCH 30/39] Fixing code smell --- .../ie3/datamodel/models/input/container/GraphicElements.java | 4 ++-- .../ie3/datamodel/models/input/container/GridContainer.java | 4 ++-- .../ie3/datamodel/models/input/container/InputContainer.java | 4 ++-- .../datamodel/models/input/container/JointGridContainer.java | 2 +- .../ie3/datamodel/models/input/container/RawGridElements.java | 4 ++-- .../datamodel/models/input/container/SubGridContainer.java | 2 +- .../datamodel/models/input/container/SystemParticipants.java | 2 +- .../edu/ie3/datamodel/models/input/container/ThermalGrid.java | 4 ++-- .../ie3/datamodel/models/input/container/ThermalUnits.java | 4 ++-- 9 files changed, 15 insertions(+), 15 deletions(-) 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 df3e39753..e7073c39c 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; @@ -140,7 +140,7 @@ public GraphicElementsCopyBuilder lineGraphics(Set lineGraphic } @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 e624fa4e0..39ba4cd85 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 @@ -88,7 +88,7 @@ public String toString() { * @since 14.02.23 */ protected abstract static class GridContainerCopyBuilder> - extends InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private String gridName; private RawGridElements rawGrid; private SystemParticipants systemParticipants; @@ -174,6 +174,6 @@ public B graphics(GraphicElements graphics) { protected abstract B thisInstance(); @Override - abstract GridContainer build() throws InvalidGridException; + public abstract GridContainer build() throws InvalidGridException; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java index a2755cbfb..f3108447f 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java @@ -26,9 +26,9 @@ public interface InputContainer extends Serializable { * @version 3.1 * @since 14.02.23 */ - abstract class InputContainerCopyBuilder> { + interface InputContainerCopyBuilder> { /** Returns the altered {@link InputContainer} of type {@link C} */ - abstract C build() throws ValidationException; + C 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 b8567a318..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 @@ -112,7 +112,7 @@ protected JointGridContainerCopyBuilder thisInstance() { } @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 d9b856e78..eba9a56b3 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 @@ -188,7 +188,7 @@ public int hashCode() { * @since 14.02.23 */ public static class RawGridElementsCopyBuilder - extends InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set nodes; private Set lines; private Set transformer2Ws; @@ -277,7 +277,7 @@ public RawGridElementsCopyBuilder measurementUnits(Set mea } @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 4446ead39..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 @@ -110,7 +110,7 @@ protected SubGridContainerCopyBuilder thisInstance() { } @Override - SubGridContainer build() throws InvalidGridException { + 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 21df3e9da..354688ba1 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; 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 10eeb6716..60accdcfa 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,7 +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; @@ -109,7 +109,7 @@ public ThermalGridCopyBuilder storages(Set storages) { } @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 ce71a2197..2855d9ed3 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 @@ -49,7 +49,7 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalUnitsCopyBuilder extends InputContainerCopyBuilder { + public static class ThermalUnitsCopyBuilder implements InputContainerCopyBuilder { private Set houses; private Set storages; @@ -86,7 +86,7 @@ public ThermalUnitsCopyBuilder storages(Set storages) { } @Override - ThermalUnits build() { + public ThermalUnits build() { return new ThermalUnits(houses, storages); } } From 26c9aabaae24c7ec15a2900eb1fa1746140cac13 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 14:10:23 +0200 Subject: [PATCH 31/39] Renaming remaining childInstance() methods --- .../ie3/datamodel/models/UniqueEntity.java | 8 +++---- .../datamodel/models/input/AssetInput.java | 20 ++++++++---------- .../models/input/MeasurementUnitInput.java | 2 +- .../ie3/datamodel/models/input/NodeInput.java | 2 +- .../datamodel/models/input/OperatorInput.java | 2 +- .../input/connector/ConnectorInput.java | 21 ++++++++----------- .../models/input/connector/LineInput.java | 2 +- .../models/input/connector/SwitchInput.java | 2 +- .../input/connector/Transformer2WInput.java | 2 +- .../input/connector/Transformer3WInput.java | 2 +- .../input/connector/TransformerInput.java | 17 +++++++-------- .../models/input/graphics/GraphicInput.java | 14 ++++++------- .../input/graphics/LineGraphicInput.java | 2 +- .../input/graphics/NodeGraphicInput.java | 2 +- .../models/input/system/BmInput.java | 2 +- .../models/input/system/ChpInput.java | 2 +- .../models/input/system/EmInput.java | 2 +- .../models/input/system/EvInput.java | 2 +- .../models/input/system/EvcsInput.java | 2 +- .../models/input/system/FixedFeedInInput.java | 2 +- .../models/input/system/HpInput.java | 2 +- .../models/input/system/LoadInput.java | 2 +- .../models/input/system/PvInput.java | 2 +- .../models/input/system/StorageInput.java | 2 +- .../input/system/SystemParticipantInput.java | 15 +++++++------ .../models/input/system/WecInput.java | 2 +- .../thermal/CylindricalStorageInput.java | 3 +-- .../models/input/thermal/ThermalBusInput.java | 3 +-- .../input/thermal/ThermalHouseInput.java | 3 +-- .../input/thermal/ThermalUnitInput.java | 10 ++++----- .../input/AssetInputEntityFactoryTest.groovy | 6 ------ .../utils/validation/DummyAssetInput.groovy | 5 ----- 32 files changed, 71 insertions(+), 94 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java b/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java index 030f9dc61..563c99d66 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 + protected 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..4b9d85f6a 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/AssetInput.java @@ -58,8 +58,6 @@ public String getId() { return id; } - public abstract UniqueEntityBuilder copy(); - @Override public boolean equals(Object o) { if (this == o) return true; @@ -95,8 +93,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - protected abstract static class AssetInputCopyBuilder> - extends UniqueEntityCopyBuilder { + protected abstract static class AssetInputCopyBuilder> + extends UniqueEntityCopyBuilder { private String id; private OperatorInput operator; @@ -109,19 +107,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 +138,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..bb7115b12 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/MeasurementUnitInput.java @@ -206,7 +206,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..4d4c32888 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/NodeInput.java @@ -226,7 +226,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..35ef3dfe2 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 @@ -73,9 +73,6 @@ public NodeInput getNodeB() { return nodeB; } - @Override - public abstract ConnectorInputCopyBuilder copy(); - @Override public List allNodes() { return List.of(getNodeA(), getNodeB()); @@ -127,8 +124,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class ConnectorInputCopyBuilder> - extends AssetInputCopyBuilder { + abstract static class ConnectorInputCopyBuilder> + extends AssetInputCopyBuilder { private NodeInput nodeA; private NodeInput nodeB; @@ -141,19 +138,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 +169,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..bce6eed60 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 @@ -223,7 +223,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..fe9aa6d12 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 @@ -126,7 +126,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..d71297674 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 @@ -160,7 +160,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..e97e44a37 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 @@ -335,7 +335,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..825a201cc 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 @@ -80,9 +80,6 @@ public int getTapPos() { return tapPos; } - @Override - public abstract TransformerInputCopyBuilder copy(); - @Override public boolean equals(Object o) { if (this == o) return true; @@ -127,8 +124,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class TransformerInputCopyBuilder> - extends ConnectorInputCopyBuilder { + abstract static class TransformerInputCopyBuilder> + extends ConnectorInputCopyBuilder { private int tapPos; private boolean autoTap; @@ -139,14 +136,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 +158,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/graphics/GraphicInput.java b/src/main/java/edu/ie3/datamodel/models/input/graphics/GraphicInput.java index a7648c522..50406681f 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 @@ -71,8 +71,8 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - protected abstract static class GraphicInputCopyBuilder> - extends UniqueEntityCopyBuilder { + protected abstract static class GraphicInputCopyBuilder> + extends UniqueEntityCopyBuilder { private String graphicLayer; private LineString path; @@ -83,14 +83,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 +105,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..e14cf1119 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 @@ -72,7 +72,6 @@ public List allNodes() { return Collections.singletonList(node); } - @Override public abstract SystemParticipantInputCopyBuilder copy(); @Override @@ -116,8 +115,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 +127,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 +149,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..f7406c0b0 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 @@ -106,7 +106,6 @@ public ComparableQuantity getC() { return c; } - @Override public CylindricalStorageInputCopyBuilder copy() { return new CylindricalStorageInputCopyBuilder(this); } @@ -222,7 +221,7 @@ public CylindricalStorageInputCopyBuilder c(ComparableQuantity getLowerTemperatureLimit() { return lowerTemperatureLimit; } - @Override public ThermalHouseInputCopyBuilder copy() { return new ThermalHouseInputCopyBuilder(this); } @@ -228,7 +227,7 @@ public ThermalHouseInputCopyBuilder lowerTemperatureLimit( } @Override - protected ThermalHouseInputCopyBuilder childInstance() { + protected ThermalHouseInputCopyBuilder thisInstance() { return this; } } 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/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy b/src/test/groovy/edu/ie3/datamodel/io/factory/input/AssetInputEntityFactoryTest.groovy index dbe201a8e..99a28fbe2 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 @@ -305,12 +305,6 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe TestAssetInput(UUID uuid, String id, OperatorInput operator, OperationTime operationTime) { super(uuid, id, operator, operationTime) } - - @Override - UniqueEntityBuilder copy() { - throw new NotImplementedException( - "Copying of " + this.getClass().simpleName + " entities is not supported yet!") - } } private static class TestAssetInputFactory extends AssetInputEntityFactory { diff --git a/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy index d7f647f27..efcf8016f 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy @@ -26,9 +26,4 @@ class DummyAssetInput extends AssetInput { boolean inOperationOn(ZonedDateTime date) { throw new UnsupportedOperationException("This is a dummy class") } - - @Override - UniqueEntityBuilder copy() { - throw new UnsupportedOperationException("This is a dummy class") - } } From 0f8a3906b927bd29cde8d3b2797800077e45d5ec Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 14:27:33 +0200 Subject: [PATCH 32/39] Further simplifications --- .../datamodel/models/input/container/GraphicElements.java | 2 +- .../datamodel/models/input/container/GridContainer.java | 6 +----- .../datamodel/models/input/container/InputContainer.java | 8 ++++---- .../datamodel/models/input/container/RawGridElements.java | 2 +- .../models/input/container/SystemParticipants.java | 2 +- .../ie3/datamodel/models/input/container/ThermalGrid.java | 2 +- .../datamodel/models/input/container/ThermalUnits.java | 2 +- 7 files changed, 10 insertions(+), 14 deletions(-) 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 e7073c39c..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 - implements InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set nodeGraphics; private Set 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 39ba4cd85..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 @@ -5,7 +5,6 @@ */ package edu.ie3.datamodel.models.input.container; -import edu.ie3.datamodel.exceptions.InvalidGridException; import edu.ie3.datamodel.models.input.InputEntity; import java.util.*; @@ -88,7 +87,7 @@ public String toString() { * @since 14.02.23 */ protected abstract static class GridContainerCopyBuilder> - implements InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private String gridName; private RawGridElements rawGrid; private SystemParticipants systemParticipants; @@ -172,8 +171,5 @@ public B graphics(GraphicElements graphics) { /** Returns the current instance of builder with the correct subclass type */ protected abstract B thisInstance(); - - @Override - public abstract GridContainer build() throws InvalidGridException; } } diff --git a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java index f3108447f..82d12f152 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java +++ b/src/main/java/edu/ie3/datamodel/models/input/container/InputContainer.java @@ -17,7 +17,7 @@ public interface InputContainer 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 @@ -26,9 +26,9 @@ public interface InputContainer extends Serializable { * @version 3.1 * @since 14.02.23 */ - interface InputContainerCopyBuilder> { + interface InputContainerCopyBuilder { - /** Returns the altered {@link InputContainer} of type {@link C} */ - C build() throws ValidationException; + /** Returns the altered {@link InputContainer} */ + InputContainer build() throws ValidationException; } } 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 eba9a56b3..384292158 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 @@ -188,7 +188,7 @@ public int hashCode() { * @since 14.02.23 */ public static class RawGridElementsCopyBuilder - implements InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set nodes; private Set lines; private Set transformer2Ws; 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 354688ba1..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 - implements InputContainerCopyBuilder { + implements InputContainerCopyBuilder { private Set bmPlants; private Set chpPlants; private Set evCS; 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 60accdcfa..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,7 +59,7 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalGridCopyBuilder implements InputContainerCopyBuilder { + public static class ThermalGridCopyBuilder implements InputContainerCopyBuilder { private ThermalBusInput bus; private Set houses; private Set 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 2855d9ed3..80144260c 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 @@ -49,7 +49,7 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalUnitsCopyBuilder implements InputContainerCopyBuilder { + public static class ThermalUnitsCopyBuilder implements InputContainerCopyBuilder { private Set houses; private Set storages; From 7d621198b6d7c4853cf67f418a9e8516d50a4fad Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 16:57:02 +0200 Subject: [PATCH 33/39] Adding some @Override notations and abstract method definitions --- src/main/java/edu/ie3/datamodel/models/UniqueEntity.java | 2 +- .../java/edu/ie3/datamodel/models/input/AssetInput.java | 4 +++- .../ie3/datamodel/models/input/MeasurementUnitInput.java | 1 + src/main/java/edu/ie3/datamodel/models/input/NodeInput.java | 1 + .../datamodel/models/input/connector/ConnectorInput.java | 5 ++++- .../edu/ie3/datamodel/models/input/connector/LineInput.java | 1 + .../ie3/datamodel/models/input/connector/SwitchInput.java | 1 + .../models/input/connector/Transformer2WInput.java | 1 + .../models/input/connector/Transformer3WInput.java | 1 + .../datamodel/models/input/container/RawGridElements.java | 3 +-- .../ie3/datamodel/models/input/container/ThermalUnits.java | 3 ++- .../ie3/datamodel/models/input/graphics/GraphicInput.java | 4 +++- .../models/input/system/SystemParticipantInput.java | 1 + .../models/input/thermal/CylindricalStorageInput.java | 1 + .../datamodel/models/input/thermal/ThermalHouseInput.java | 1 + .../ie3/datamodel/models/input/thermal/ThermalInput.java | 3 +++ .../io/factory/input/AssetInputEntityFactoryTest.groovy | 6 ++++++ .../datamodel/models/input/graphics/GraphicInputTest.groovy | 5 +++++ .../ie3/datamodel/utils/validation/DummyAssetInput.groovy | 5 +++++ .../utils/validation/InvalidSystemParticipantInput.groovy | 2 +- 20 files changed, 43 insertions(+), 8 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java b/src/main/java/edu/ie3/datamodel/models/UniqueEntity.java index 563c99d66..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; 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 4b9d85f6a..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,6 +58,8 @@ public String getId() { return id; } + public abstract AssetInputCopyBuilder copy(); + @Override public boolean equals(Object o) { if (this == o) return true; @@ -93,7 +95,7 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - protected abstract static class AssetInputCopyBuilder> + public abstract static class AssetInputCopyBuilder> extends UniqueEntityCopyBuilder { private String id; 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 bb7115b12..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); } 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 4d4c32888..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); } 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 35ef3dfe2..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 @@ -73,6 +73,9 @@ public NodeInput getNodeB() { return nodeB; } + @Override + public abstract ConnectorInputCopyBuilder copy(); + @Override public List allNodes() { return List.of(getNodeA(), getNodeB()); @@ -124,7 +127,7 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class ConnectorInputCopyBuilder> + public abstract static class ConnectorInputCopyBuilder> extends AssetInputCopyBuilder { private NodeInput nodeA; 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 bce6eed60..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); } 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 fe9aa6d12..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); } 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 d71297674..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); } 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 e97e44a37..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); } 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 384292158..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 - implements InputContainerCopyBuilder { + public static class RawGridElementsCopyBuilder implements InputContainerCopyBuilder { private Set nodes; private Set lines; private Set transformer2Ws; 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 80144260c..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 @@ -49,7 +49,8 @@ public String toString() { * @version 3.1 * @since 14.02.23 */ - public static class ThermalUnitsCopyBuilder implements InputContainerCopyBuilder { + public static class ThermalUnitsCopyBuilder + implements InputContainerCopyBuilder { private Set houses; private Set 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 50406681f..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,13 +65,15 @@ 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> + public abstract static class GraphicInputCopyBuilder> extends UniqueEntityCopyBuilder { private String graphicLayer; 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 e14cf1119..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 @@ -72,6 +72,7 @@ public List allNodes() { return Collections.singletonList(node); } + @Override public abstract SystemParticipantInputCopyBuilder copy(); @Override 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 f7406c0b0..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 @@ -106,6 +106,7 @@ public ComparableQuantity getC() { return c; } + @Override public CylindricalStorageInputCopyBuilder copy() { return new CylindricalStorageInputCopyBuilder(this); } diff --git a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalHouseInput.java b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalHouseInput.java index 3157831f2..9ff6aba7f 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalHouseInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalHouseInput.java @@ -106,6 +106,7 @@ public ComparableQuantity getLowerTemperatureLimit() { return lowerTemperatureLimit; } + @Override public ThermalHouseInputCopyBuilder copy() { return new ThermalHouseInputCopyBuilder(this); } diff --git a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalInput.java b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalInput.java index 688f6fdec..6e6a83443 100644 --- a/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalInput.java +++ b/src/main/java/edu/ie3/datamodel/models/input/thermal/ThermalInput.java @@ -34,4 +34,7 @@ protected ThermalInput( protected ThermalInput(UUID uuid, String id) { super(uuid, id); } + + @Override + public abstract AssetInputCopyBuilder copy(); } 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 99a28fbe2..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 @@ -305,6 +305,12 @@ class AssetInputEntityFactoryTest extends Specification implements FactoryTestHe TestAssetInput(UUID uuid, String id, OperatorInput operator, OperationTime operationTime) { super(uuid, id, operator, operationTime) } + + @Override + AssetInputCopyBuilder copy() { + throw new NotImplementedException( + "Copying of " + this.getClass().simpleName + " entities is not supported yet!") + } } private static class TestAssetInputFactory extends AssetInputEntityFactory { 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/validation/DummyAssetInput.groovy b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy index efcf8016f..899c6279f 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/DummyAssetInput.groovy @@ -26,4 +26,9 @@ class DummyAssetInput extends AssetInput { boolean inOperationOn(ZonedDateTime date) { throw new UnsupportedOperationException("This is a dummy class") } + + @Override + AssetInputCopyBuilder copy() { + throw new UnsupportedOperationException("This is a dummy class") + } } 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") } } From ac7564a4f5bc06446b874ced8def13d1ce9ae97a Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 17:20:40 +0200 Subject: [PATCH 34/39] Reinstated removed method --- .../datamodel/models/input/connector/TransformerInput.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 825a201cc..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 @@ -80,6 +80,9 @@ public int getTapPos() { return tapPos; } + @Override + public abstract TransformerInputCopyBuilder> copy(); + @Override public boolean equals(Object o) { if (this == o) return true; @@ -124,7 +127,7 @@ public String toString() { * @version 0.1 * @since 05.06.20 */ - abstract static class TransformerInputCopyBuilder> + public abstract static class TransformerInputCopyBuilder> extends ConnectorInputCopyBuilder { private int tapPos; From b2df229ac3146cfa243ec5ec109392308e3c6edc Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 19:00:30 +0200 Subject: [PATCH 35/39] Improved formatting of failure messages Reinstated narrower checking of syspart. validation --- .../exceptions/FailedValidationException.java | 4 +- .../exceptions/InvalidEntityException.java | 5 +- .../ie3/datamodel/utils/ExceptionUtils.java | 4 +- .../java/edu/ie3/datamodel/utils/Try.java | 15 +++++- .../validation/ConnectorValidationUtils.java | 31 ++++++----- .../validation/GraphicValidationUtils.java | 12 +++-- .../GridContainerValidationUtils.java | 46 ++++++++++------- .../MeasurementUnitValidationUtils.java | 4 +- .../utils/validation/NodeValidationUtils.java | 9 ++-- .../SystemParticipantValidationUtils.java | 23 +++++---- .../ThermalUnitValidationUtils.java | 14 ++--- .../utils/validation/ValidationUtils.java | 20 ++++---- ...ystemParticipantValidationUtilsTest.groovy | 51 +++++++++++++------ 13 files changed, 151 insertions(+), 87 deletions(-) diff --git a/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java index d519d8cfc..0fc60cd13 100644 --- a/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java +++ b/src/main/java/edu/ie3/datamodel/exceptions/FailedValidationException.java @@ -17,7 +17,9 @@ 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: " + ExceptionUtils.getMessages(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/utils/ExceptionUtils.java b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java index 1ff2de169..018580d20 100644 --- a/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/ExceptionUtils.java @@ -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 03e44fa83..0d1c571d5 100644 --- a/src/main/java/edu/ie3/datamodel/utils/Try.java +++ b/src/main/java/edu/ie3/datamodel/utils/Try.java @@ -72,9 +72,10 @@ public static Try ofVoid( * @return a {@link Try} * @param type of exception */ - public static Try ofVoid(boolean failure, E exception) { + public static Try ofVoid( + boolean failure, ExceptionSupplier exception) { if (failure) { - return Failure.ofVoid(exception); + return Failure.ofVoid(exception.get()); } else { return Success.empty(); } @@ -418,4 +419,14 @@ public interface TrySupplier { 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 fb52c02a9..696f4ac9d 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ConnectorValidationUtils.java @@ -259,8 +259,9 @@ private static List> checkTransformer3W( 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))); + () -> + new InvalidEntityException( + "Transformer connects nodes of the same voltage level", transformer3W))); // Check if transformer connects different subnets exceptions.add( @@ -268,8 +269,9 @@ private static List> checkTransformer3W( 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))); + () -> + new InvalidEntityException( + "Transformer connects nodes in the same subnet", transformer3W))); exceptions.add( Try.ofVoid( @@ -347,7 +349,9 @@ protected static List> checkTransformer3WType( 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)); + () -> + 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 */ @@ -393,10 +397,11 @@ protected static Try checkConnectivity( return Try.ofVoid( !inspector.isConnected(), - new InvalidGridException( - "The grid with subnetNo " - + subGridContainer.getSubnet() - + " is not connected! Please ensure that all elements are connected correctly!")); + () -> + new InvalidGridException( + "The grid with subnetNo " + + subGridContainer.getSubnet() + + " is not connected! Please ensure that all elements are connected correctly!")); } /** @@ -408,9 +413,11 @@ 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)); + () -> + new InvalidEntityException( + connectorInput.getClass().getSimpleName() + + " connects the same node, but shouldn't", + connectorInput)); } /** 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 8d92338fa..e47eadf61 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GraphicValidationUtils.java @@ -44,8 +44,9 @@ protected static List> check(GraphicInput grap exceptions.add( Try.ofVoid( graphicInput.getGraphicLayer() == null, - new InvalidEntityException( - "Graphic Layer of graphic element is not defined", graphicInput))); + () -> + new InvalidEntityException( + "Graphic Layer of graphic element is not defined", graphicInput))); // Further checks for subclasses if (LineGraphicInput.class.isAssignableFrom(graphicInput.getClass())) { @@ -67,8 +68,9 @@ private static Try checkLineGraphicInput( LineGraphicInput lineGraphicInput) { return Try.ofVoid( lineGraphicInput.getPath() == null, - new InvalidEntityException( - "Path of line graphic element is not defined", lineGraphicInput)); + () -> + new InvalidEntityException( + "Path of line graphic element is not defined", lineGraphicInput)); } /** @@ -82,6 +84,6 @@ private static Try checkNodeGraphicInput( NodeGraphicInput nodeGraphicInput) { return Try.ofVoid( nodeGraphicInput.getPoint() == null, - new InvalidEntityException("Point of node graphic is not defined", nodeGraphicInput)); + () -> 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 55fabe117..9f2447d0b 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/GridContainerValidationUtils.java @@ -62,8 +62,10 @@ private GridContainerValidationUtils() { exceptions.add( Try.ofVoid( exceptionString.isPresent(), - new InvalidGridException( - duplicateUuidsString(gridContainer.getClass().getSimpleName(), exceptionString)))); + () -> + new InvalidGridException( + duplicateUuidsString( + gridContainer.getClass().getSimpleName(), exceptionString)))); exceptions.addAll(checkRawGridElements(gridContainer.getRawGrid())); exceptions.addAll( @@ -106,9 +108,10 @@ private GridContainerValidationUtils() { exceptions.add( Try.ofVoid( exceptionString.isPresent(), - new InvalidGridException( - duplicateUuidsString( - rawGridElements.getClass().getSimpleName(), exceptionString)))); + () -> + new InvalidGridException( + duplicateUuidsString( + rawGridElements.getClass().getSimpleName(), exceptionString)))); /* Checking nodes */ Set nodes = rawGridElements.getNodes(); @@ -225,9 +228,10 @@ protected static List> checkRawGridTypeIds( exceptions.add( Try.ofVoid( exceptionString.isPresent(), - new InvalidGridException( - duplicateUuidsString( - systemParticipants.getClass().getSimpleName(), exceptionString)))); + () -> + new InvalidGridException( + duplicateUuidsString( + systemParticipants.getClass().getSimpleName(), exceptionString)))); exceptions.addAll(checkSystemParticipants(systemParticipants.getBmPlants(), nodes)); exceptions.addAll(checkSystemParticipants(systemParticipants.getChpPlants(), nodes)); @@ -318,9 +322,10 @@ protected static List> checkSystemParticipantsT exceptions.add( Try.ofVoid( exceptionString.isPresent(), - new InvalidGridException( - duplicateUuidsString( - graphicElements.getClass().getSimpleName(), exceptionString)))); + () -> + new InvalidGridException( + duplicateUuidsString( + graphicElements.getClass().getSimpleName(), exceptionString)))); graphicElements .getNodeGraphics() @@ -330,7 +335,9 @@ protected static List> checkSystemParticipantsT exceptions.add( Try.ofVoid( !nodes.contains(graphic.getNode()), - buildGraphicExceptionMessage(graphic, "node", graphic.getNode().getUuid()))); + () -> + buildGraphicExceptionMessage( + graphic, "node", graphic.getNode().getUuid()))); }); graphicElements @@ -341,7 +348,9 @@ protected static List> checkSystemParticipantsT exceptions.add( Try.ofVoid( !lines.contains(graphic.getLine()), - buildGraphicExceptionMessage(graphic, "line", graphic.getLine().getUuid()))); + () -> + buildGraphicExceptionMessage( + graphic, "line", graphic.getLine().getUuid()))); }); return exceptions; @@ -381,11 +390,12 @@ private static Try checkNodeAvailability( return Try.ofVoid( available, - new InvalidGridException( - input.getClass().getSimpleName() - + " " - + input - + " is connected to a node that is not in the set of nodes.")); + () -> + new InvalidGridException( + input.getClass().getSimpleName() + + " " + + input + + " is connected to a node that is not in the set of nodes.")); } /** 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 f6d551104..318cfd13f 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/MeasurementUnitValidationUtils.java @@ -39,6 +39,8 @@ private MeasurementUnitValidationUtils() { && !measurementUnit.getQ() && !measurementUnit.getVAng() && !measurementUnit.getVMag(), - new UnsafeEntityException("Measurement Unit does not measure any values", measurementUnit)); + () -> + 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 069566115..37f948c95 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/NodeValidationUtils.java @@ -58,20 +58,21 @@ private NodeValidationUtils() { node.getvTarget() .isLessThanOrEqualTo( Quantities.getQuantity(0, StandardUnits.TARGET_VOLTAGE_MAGNITUDE)), - new InvalidEntityException("Target voltage (p.u.) is not a positive value", node))); + () -> + 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))); + () -> 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))); + () -> 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))); + () -> new InvalidEntityException("GeoPosition of node is null", node))); return exceptions; } 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 b15b81510..b2e0bc896 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtils.java @@ -56,9 +56,10 @@ protected static List> check( exceptions.add( Try.ofVoid( systemParticipant.getqCharacteristics() == null, - new InvalidEntityException( - "Reactive power characteristics of system participant is not defined", - systemParticipant))); + () -> + new InvalidEntityException( + "Reactive power characteristics of system participant is not defined", + systemParticipant))); // Further checks for subclasses if (BmInput.class.isAssignableFrom(systemParticipant.getClass())) { @@ -124,8 +125,9 @@ protected static List> checkType( (systemParticipantTypeInput.getCapex() == null) || (systemParticipantTypeInput.getOpex() == null) || (systemParticipantTypeInput.getsRated() == null), - new InvalidEntityException( - "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); + () -> + new InvalidEntityException( + "At least one of capex, opex, or sRated is null", systemParticipantTypeInput))); try { exceptions.add( @@ -340,7 +342,9 @@ private static List> checkLoad(LoadInput loadI exceptions.add( Try.ofVoid( loadInput.getLoadProfile() == null, - new InvalidEntityException("No standard load profile defined for load", loadInput))); + () -> + new InvalidEntityException( + "No standard load profile defined for load", loadInput))); exceptions.addAll( Try.ofVoid( @@ -460,9 +464,10 @@ private static List> checkStorageType( exceptions.add( Try.ofVoid( storageTypeInput.getLifeCycle() < 0, - new InvalidEntityException( - "Permissible amount of life cycles of the storage type must be zero or positive", - storageTypeInput))); + () -> + new InvalidEntityException( + "Permissible amount of life cycles of the storage type must be zero or positive", + storageTypeInput))); exceptions.addAll( Try.ofVoid( 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 c00affedb..8dd2b39f0 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ThermalUnitValidationUtils.java @@ -201,18 +201,20 @@ private static List> checkCylindricalStorage( cylindricalStorageInput .getInletTemp() .isLessThan(cylindricalStorageInput.getReturnTemp()), - new InvalidEntityException( - "Inlet temperature of the cylindrical storage cannot be lower than outlet temperature", - cylindricalStorageInput))); + () -> + 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 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))); + () -> + new InvalidEntityException( + "Minimum permissible storage volume of the cylindrical storage cannot be higher than overall available storage volume", + cylindricalStorageInput))); exceptions.add( Try.ofVoid( 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 c8b666e5a..c09607a0d 100644 --- a/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java +++ b/src/main/java/edu/ie3/datamodel/utils/validation/ValidationUtils.java @@ -85,7 +85,7 @@ public static void check(Object obj) throws ValidationException { .map(t -> ((Failure) t).get()) .toList(); - Try.ofVoid(!list.isEmpty(), new FailedValidationException(list)).getOrThrow(); + Try.ofVoid(!list.isEmpty(), () -> new FailedValidationException(list)).getOrThrow(); } /** @@ -112,7 +112,8 @@ public static void check(Object obj) throws ValidationException { exceptions.add( Try.ofVoid( - assetInput.getId() == null, new InvalidEntityException("No ID assigned", assetInput))); + assetInput.getId() == null, + () -> new InvalidEntityException("No ID assigned", assetInput))); if (assetInput.getOperationTime() == null) { exceptions.add( @@ -187,11 +188,11 @@ else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass())) exceptions.add( Try.ofVoid( assetTypeInput.getUuid() == null, - new InvalidEntityException("No UUID assigned", assetTypeInput))); + () -> new InvalidEntityException("No UUID assigned", assetTypeInput))); exceptions.add( Try.ofVoid( assetTypeInput.getId() == null, - new InvalidEntityException("No ID assigned", assetTypeInput))); + () -> new InvalidEntityException("No ID assigned", assetTypeInput))); // Further checks for subclasses if (LineTypeInput.class.isAssignableFrom(assetTypeInput.getClass())) @@ -256,11 +257,12 @@ 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())); + () -> + new InvalidEntityException( + "Validation not possible because received object was null. Expected " + + expectedDescription + + ", but got nothing. :-(", + new NullPointerException())); } /** 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 138fc2470..52e29df18 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -53,6 +53,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize Exception ex = exceptions.get(0).exception.get() + ex.class == expectedException.class ex.message == expectedException.message where: @@ -100,8 +101,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidType || expectedException @@ -141,8 +144,10 @@ class SystemParticipantValidationUtilsTest extends Specification { ValidationUtils.check(invalidBmType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidBmType || expectedException @@ -181,8 +186,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidChpType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidChpType || expectedException @@ -223,8 +230,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidEvType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidEvType || expectedException @@ -251,6 +260,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize Exception ex = exceptions.get(0).exception.get() + ex.class == expectedException.class ex.message == expectedException.message where: @@ -290,8 +300,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidHpType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidHpType || expectedException @@ -318,6 +330,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize Exception ex = exceptions.get(0).exception.get() + ex.class == expectedException.class ex.message == expectedException.message where: @@ -347,6 +360,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: exceptions.size() == expectedSize Exception ex = exceptions.get(0).exception.get() + ex.class == expectedException.class ex.message == expectedException.message where: @@ -390,8 +404,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidStorageType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidStorageType || expectedException @@ -433,8 +449,10 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidWecType) then: - Exception ex = thrown() - ex.message.contains(expectedException.message) + Throwable topEx = thrown() + Throwable ex = topEx.cause + ex.class == expectedException.class + ex.message == expectedException.message where: invalidWecType || expectedException @@ -464,8 +482,9 @@ class SystemParticipantValidationUtilsTest extends Specification { SystemParticipantValidationUtils.check(invalidParticipantInput) then: - Exception e = thrown() - e.message.contains("Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented.") + Throwable topEx = thrown() + Throwable e = topEx.cause + e.message == "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." } def "Checking electric vehicle charging stations leads to an exception"() { From 47d307b57716ef7015de5ee64e5e5319aa29952d Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 19:05:11 +0200 Subject: [PATCH 36/39] Fixing test --- .../validation/SystemParticipantValidationUtilsTest.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 52e29df18..6f9cc47aa 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/SystemParticipantValidationUtilsTest.groovy @@ -484,7 +484,7 @@ class SystemParticipantValidationUtilsTest extends Specification { then: Throwable topEx = thrown() Throwable e = topEx.cause - e.message == "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." + e.message.contains "Cannot validate object of class 'InvalidSystemParticipantTypeInput', as no routine is implemented." } def "Checking electric vehicle charging stations leads to an exception"() { From 0767e271629e03cbad159b7489ebba59b8a76336 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 19:12:17 +0200 Subject: [PATCH 37/39] Fixing ValidationUtilsTest --- .../utils/validation/ValidationUtilsTest.groovy | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 45e10c547..e059a012c 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -11,8 +11,8 @@ 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.FailedValidationException import edu.ie3.datamodel.exceptions.InvalidEntityException -import edu.ie3.datamodel.exceptions.NotImplementedException import edu.ie3.datamodel.exceptions.UnsafeEntityException import edu.ie3.datamodel.exceptions.ValidationException import edu.ie3.datamodel.models.OperationTime @@ -116,7 +116,7 @@ class ValidationUtilsTest extends Specification { 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.getClass().getSimpleName() + "', as no routine is implemented.") } def "The validation check method recognizes all potential errors for an asset"() { @@ -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,7 +208,7 @@ 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"() { @@ -247,7 +247,7 @@ class ValidationUtilsTest extends Specification { then: exceptions.size() == 2 def e = exceptions.get(0).exception.get() - e.message.startsWith("Entity is invalid because of: No ID assigned [AssetTypeInput") + e.message.startsWith("Entity is invalid because of: \nNo ID assigned [AssetTypeInput") } def "Checking if asset input ids are unique"() { From e80502b014ad58a94e137cfa49cdcb7047de7e85 Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 19:21:31 +0200 Subject: [PATCH 38/39] Fixing TryTest --- src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy index f72d8759d..4a0ff0762 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/TryTest.groovy @@ -112,7 +112,8 @@ class TryTest extends Specification { def "A Try object can be creates by a boolean and an exception"() { when: - def actual = Try.ofVoid(bool, ex) + def ex = new FailureException("failure") + def actual = Try.ofVoid(bool, () -> ex) then: actual.failure == expected @@ -122,9 +123,9 @@ class TryTest extends Specification { } where: - bool | ex | expected - true | new FailureException("failure") | true - false | new FailureException("no failure") | false + bool || expected + true || true + false || false } def "A list of Tries is returned when applying a multiple VoidSupplier to Try#ofVoid()"() { From a66754e92941c5a6668d250580286f88bf3e694e Mon Sep 17 00:00:00 2001 From: Sebastian Peter Date: Mon, 31 Jul 2023 19:48:49 +0200 Subject: [PATCH 39/39] Codacy issues --- .../ConnectorValidationUtilsTest.groovy | 21 +++++++------------ .../validation/NodeValidationUtilsTest.groovy | 10 ++++----- .../validation/ValidationUtilsTest.groovy | 2 +- 3 files changed, 12 insertions(+), 21 deletions(-) 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 b331ad4fc..97a2ff4a8 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ConnectorValidationUtilsTest.groovy @@ -5,33 +5,26 @@ */ package edu.ie3.datamodel.utils.validation -import edu.ie3.datamodel.utils.Try - 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"() { 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 198779672..f17b2ae3e 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/NodeValidationUtilsTest.groovy @@ -5,18 +5,16 @@ */ package edu.ie3.datamodel.utils.validation -import edu.ie3.datamodel.exceptions.ValidationException -import edu.ie3.datamodel.utils.Try - 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 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 e059a012c..26c43982d 100644 --- a/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy +++ b/src/test/groovy/edu/ie3/datamodel/utils/validation/ValidationUtilsTest.groovy @@ -116,7 +116,7 @@ class ValidationUtilsTest extends Specification { where: invalidObject || expectedException - new Coordinate(10, 10) || new FailedValidationException("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"() {