id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
unknown
repo_stars
int64
10
44.3k
repo_language
stringclasses
8 values
repo_languages
stringclasses
296 values
repo_license
stringclasses
2 values
752
workcraft/workcraft/1205/1204
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1204
https://github.com/workcraft/workcraft/pull/1205
https://github.com/workcraft/workcraft/pull/1205
1
fixes
Use MPSat continuations to extend violation trace for output persistency check
Legacy code in Workcraft detects non-persistent signals after the violation trace using some heuristics at composition STG. This may produce incorrect extension of the projection traces to the component STG ([env.stg.work.zip](https://github.com/workcraft/workcraft/files/6188778/env.stg.work.zip) [xor.circuit.work.zip](https://github.com/workcraft/workcraft/files/6188779/xor.circuit.work.zip)) Recent MPSat versions report "continuations" after the violation trace, that include dummies leading to the enabled signal events. These should be used for reliable detection of non-persistent signals, especially when extending a projection trace to the component STG.
3ceb719ec8d6348bc5d026c97eb876f9d34e9b72
2336a6a02415412abfa0b910c347a059fe787566
https://github.com/workcraft/workcraft/compare/3ceb719ec8d6348bc5d026c97eb876f9d34e9b72...2336a6a02415412abfa0b910c347a059fe787566
diff --git a/workcraft/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat_verification/tasks/OutputPersistencyOutputInterpreter.java b/workcraft/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat_verification/tasks/OutputPersistencyOutputInterpreter.java index ed5878c38..e63f3919e 100644 --- a/workcraft/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat_verification/tasks/OutputPersistencyOutputInterpreter.java +++ b/workcraft/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat_verification/tasks/OutputPersistencyOutputInterpreter.java @@ -1,5 +1,6 @@ package org.workcraft.plugins.mpsat_verification.tasks; +import org.workcraft.plugins.mpsat_verification.projection.Enabledness; import org.workcraft.plugins.mpsat_verification.utils.CompositionUtils; import org.workcraft.plugins.pcomp.ComponentData; import org.workcraft.plugins.pcomp.tasks.PcompOutput; @@ -10,9 +11,11 @@ import org.workcraft.plugins.stg.DummyTransition; import org.workcraft.plugins.stg.Signal; import org.workcraft.plugins.stg.SignalTransition; import org.workcraft.plugins.stg.StgModel; +import org.workcraft.plugins.stg.utils.LabelParser; import org.workcraft.tasks.ExportOutput; import org.workcraft.traces.Solution; import org.workcraft.traces.Trace; +import org.workcraft.types.Triple; import org.workcraft.utils.LogUtils; import org.workcraft.workspace.WorkspaceEntry; @@ -29,11 +32,9 @@ class OutputPersistencyOutputInterpreter extends ReachabilityOutputInterpreter { @Override public List<Solution> processSolutions(List<Solution> solutions) { List<Solution> result = new LinkedList<>(); - ComponentData data = getComponentData(); StgModel stg = getStg(); - HashMap<Place, Integer> marking = PetriUtils.getMarking(stg); - + HashMap<Place, Integer> initialMarking = PetriUtils.getMarking(stg); for (Solution solution : solutions) { Trace trace = solution.getMainTrace(); LogUtils.logMessage("Violation trace: " + trace); @@ -42,30 +43,45 @@ class OutputPersistencyOutputInterpreter extends ReachabilityOutputInterpreter { LogUtils.logMessage("Projection trace: " + trace); } if (!PetriUtils.fireTrace(stg, trace)) { - PetriUtils.setMarking(stg, marking); + PetriUtils.setMarking(stg, initialMarking); throw new RuntimeException("Cannot execute trace: " + trace); } - // Check if any local signal gets disabled by firing other signal event - HashSet<String> enabledLocalSignals = getEnabledLocalSignals(stg); - for (SignalTransition transition : getEnabledSignalTransitions(stg)) { - stg.fire(transition); - HashSet<String> nonpersistentLocalSignals = new HashSet<>(enabledLocalSignals); - nonpersistentLocalSignals.remove(transition.getSignalName()); - nonpersistentLocalSignals.removeAll(getEnabledLocalSignals(stg)); + // Check if any local signal gets disabled by firing continuations + Enabledness enabledness = CompositionUtils.getEnabledness(solution.getContinuations(), data); + for (String enabledTransitionRef : enabledness.keySet()) { + HashSet<String> nonpersistentLocalSignals = getNonpersistentLocalSignals(stg, + enabledness.get(enabledTransitionRef), enabledTransitionRef); + if (!nonpersistentLocalSignals.isEmpty()) { String comment = getMessageWithList("Non-persistent signal", nonpersistentLocalSignals); - String transitionRef = stg.getNodeReference(transition); - String msg = getMessageWithList("Event '" + transitionRef + "' disables signal", nonpersistentLocalSignals); + String msg = getMessageWithList("Event '" + enabledTransitionRef + "' disables signal", nonpersistentLocalSignals); LogUtils.logWarning(msg); Trace processedTrace = new Trace(trace); - processedTrace.add(transitionRef); + processedTrace.add(enabledTransitionRef); Solution processedSolution = new Solution(processedTrace, null, comment); result.add(processedSolution); } - stg.unFire(transition); } - PetriUtils.setMarking(stg, marking); + PetriUtils.setMarking(stg, initialMarking); + } + return result; + } + + private HashSet<String> getNonpersistentLocalSignals(StgModel stg, Trace continuationTrace, String enabledTransitionRef) { + HashSet<String> result = new HashSet<>(); + continuationTrace.add(enabledTransitionRef); + HashSet<String> enabledLocalSignals = getEnabledLocalSignals(stg); + HashMap<Place, Integer> marking = PetriUtils.getMarking(stg); + if (PetriUtils.fireTrace(stg, continuationTrace)) { + result.addAll(enabledLocalSignals); + Triple<String, SignalTransition.Direction, Integer> r = LabelParser.parseSignalTransition(enabledTransitionRef); + if (r != null) { + result.remove(r.getFirst()); + } + HashSet<String> stillEnabledLocalSignals = getEnabledLocalSignals(stg); + result.removeAll(stillEnabledLocalSignals); } + PetriUtils.setMarking(stg, marking); return result; }
['workcraft/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat_verification/tasks/OutputPersistencyOutputInterpreter.java']
{'.java': 1}
1
1
0
0
1
6,056,800
1,231,440
165,124
1,687
2,970
556
48
1
668
70
141
3
2
0
"1970-01-01T00:26:56"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
753
workcraft/workcraft/1196/1195
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1195
https://github.com/workcraft/workcraft/pull/1196
https://github.com/workcraft/workcraft/pull/1196
1
closes
Limit grid density
Grid density may become excessive for small viewport. A solution is to suppress grid if there is too many crosses/lines to draw.
c8f3d21efbb8b96693e7dcd5c83c5fab0ab93cc1
85d7d42c30113e8a0f256c5b8d7c52c9549ca7a5
https://github.com/workcraft/workcraft/compare/c8f3d21efbb8b96693e7dcd5c83c5fab0ab93cc1...85d7d42c30113e8a0f256c5b8d7c52c9549ca7a5
diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Grid.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Grid.java index 999f6b86c..1548f1af9 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Grid.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Grid.java @@ -13,116 +13,27 @@ import java.util.LinkedList; * as well as to handle the coordinate "snapping". */ public class Grid implements ViewportListener { - protected double minorIntervalFactor = 0.1; - protected double intervalScaleFactor = 2; - protected double maxThreshold = 5; - protected double minThreshold = 2.5; + private static final int MAX_GRID_COUNT = 128; + private static final double MINOR_INTERVAL_FACTOR = 0.1; + private static final double INTERVAL_SCALE_FACTOR = 2; + private static final double MAX_THRESHOLD = 5; + private static final double MIN_THRESHOLD = 2.5; - protected Path2D minorLinesPath; - protected Path2D majorLinesPath; + private final double[][] majorPositions = new double[2][]; + private final double[][] minorPositions = new double[2][]; + private final int[][] majorScreenPositions = new int[2][]; + private final int[][] minorScreenPositions = new int[2][]; + private final Stroke stroke = new BasicStroke(); - protected double[][] majorLinePositions; - protected double[][] minorLinePositions; - - protected int[][] majorLinePositionsScreen; - protected int[][] minorLinePositionsScreen; - - protected Stroke stroke; - - protected double majorInterval = 10.0; - - /** - * Set the interval of major grid lines in user-space units. - * @param majorInterval - * The new interval of major grid lines - */ - public void setMajorInterval(double majorInterval) { - this.majorInterval = majorInterval; - } - - /** - * @return - * Dynamic interval scaling factor - */ - public double getIntervalScaleFactor() { - return intervalScaleFactor; - } - - /** - * Set the dynamic interval scale factor. The major grid line interval will be multiplied or divided by this amount - * when applying dynamic grid scaling. - * @param intervalScaleFactor - */ - public void setIntervalScaleFactor(double intervalScaleFactor) { - this.intervalScaleFactor = intervalScaleFactor; - } - - /** - * @return - * The interval magnification threshold - */ - public double getMagThreshold() { - return maxThreshold; - } - - /** - * Set the interval magnification threshold. The grid interval will be increased by <code>intervalScaleFactor</code> if more than <code>magThreshold</code> - * major grid intervals become visible across the vertical dimension of the viewport. - * @param magThreshold - * The new interval magnification threshold. - */ - public void setMagThreshold(double magThreshold) { - this.maxThreshold = magThreshold; - } - - /** - * @return - * The interval minimisation threshold. - */ - public double getMinThreshold() { - return minThreshold; - } - - /** - * Set the interval minimisation threshold. The grid interval will be decreased by <code>intervalScaleFactor</code> if less than <i>minThreshold</i> - * major grid intervals become visible across the vertical dimension of the viewport. - * major grid intervals become visible. - * @param minThreshold - */ - public void setMinThreshold(double minThreshold) { - this.minThreshold = minThreshold; - } + private double majorInterval = 10.0; + private Path2D minorShape = new Path2D.Double(); + private Path2D majorShape = new Path2D.Double(); /** * The list of listeners to be notified in case of grid parameters change. */ - protected LinkedList<GridListener> listeners; - - /** - * Constructs a grid with default parameters: - * <ul> - * <li> Major grid lines interval = 10 units - * <li> Minor grid lines frequency = 10 per major line interval - * <li> Dynamic scaling factor = 2 - * <li> Dynamic magnification threshold = 5 (see <code>setMagThreshold</code>) - * <li> Dynamic minimisation threshold = 2.5 (see <code>setMinThreshold</code>) - * </ul> - **/ - public Grid() { - minorLinesPath = new Path2D.Double(); - majorLinesPath = new Path2D.Double(); - - minorLinePositions = new double[2][]; - majorLinePositions = new double[2][]; - - minorLinePositionsScreen = new int[2][]; - majorLinePositionsScreen = new int[2][]; - - listeners = new LinkedList<>(); - - stroke = new BasicStroke(); - } + private final LinkedList<GridListener> listeners = new LinkedList<>(); /** * Recalculates visible grid lines based on the viewport parameters. @@ -144,19 +55,19 @@ public class Grid implements ViewportListener { // Dynamic line interval scaling double visibleHeight = visibleUL.getY() - visibleLR.getY(); if (majorInterval > 0) { - while (visibleHeight / majorInterval > maxThreshold) { - majorInterval *= intervalScaleFactor; + while (visibleHeight / majorInterval > MAX_THRESHOLD) { + majorInterval *= INTERVAL_SCALE_FACTOR; } - while (visibleHeight / majorInterval < minThreshold) { - majorInterval /= intervalScaleFactor; + while (visibleHeight / majorInterval < MIN_THRESHOLD) { + majorInterval /= INTERVAL_SCALE_FACTOR; } } if (EditorCommonSettings.getLightGrid()) { - updateGridMinorCrosses(viewport, majorInterval * minorIntervalFactor); + updateGridMinorCrosses(viewport, majorInterval * MINOR_INTERVAL_FACTOR); updateGridMajorCrosses(viewport, majorInterval); } else { - updateGridMinorLines(viewport, majorInterval * minorIntervalFactor); + updateGridMinorLines(viewport, majorInterval * MINOR_INTERVAL_FACTOR); updateGridMajorLines(viewport, majorInterval); } @@ -166,94 +77,72 @@ public class Grid implements ViewportListener { } private void updateGridMinorCrosses(Viewport viewport, double interval) { - minorLinesPath = new Path2D.Double(); + minorShape = new Path2D.Double(); double radius = Math.max(1.0, EditorCommonSettings.getFontSize() * SizeHelper.getScreenDpmm() / 30.0); - updateGridCrosses(viewport, interval, radius, minorLinePositions, minorLinePositionsScreen, minorLinesPath); + updateGridCrosses(viewport, interval, radius, minorPositions, minorScreenPositions, minorShape); } private void updateGridMajorCrosses(Viewport viewport, double interval) { - majorLinesPath = new Path2D.Double(); + majorShape = new Path2D.Double(); double radius = Math.max(1.0, EditorCommonSettings.getFontSize() * SizeHelper.getScreenDpmm() / 20.0); - updateGridCrosses(viewport, interval, radius, majorLinePositions, majorLinePositionsScreen, majorLinesPath); + updateGridCrosses(viewport, interval, radius, majorPositions, majorScreenPositions, majorShape); } private void updateGridCrosses(Viewport viewport, double interval, double crossRadius, - double[][] linePositions, int[][] linePositionsScreen, Path2D linesPath) { - - Rectangle view = viewport.getShape(); - - // Compute the visible user space area from the viewport - Point2D visibleUL = new Point2D.Double(); - Point2D visibleLR = new Point2D.Double(); - Point viewLL = new Point(view.x, view.height + view.y); - Point viewUR = new Point(view.width + view.x, view.y); - viewport.getInverseTransform().transform(viewLL, visibleUL); - viewport.getInverseTransform().transform(viewUR, visibleLR); - - // Compute the leftmost, rightmost, topmost and bottom visible grid lines - int bottom = (int) Math.ceil(visibleLR.getY() / interval); - int top = (int) Math.floor(visibleUL.getY() / interval); - int left = (int) Math.ceil(visibleUL.getX() / interval); - int right = (int) Math.floor(visibleLR.getX() / interval); - - // Build the gridlines positions, store them as user-space coordinates, - // screen-space coordinates, and as a drawable path (in screen-space) - final int countMinH = Math.max(0, right - left + 1); - linePositions[0] = new double[countMinH]; - linePositionsScreen[0] = new int[countMinH]; - - final int countMinV = Math.max(0, top - bottom + 1); - linePositions[1] = new double[countMinV]; - linePositionsScreen[1] = new int[countMinV]; - - Point2D p = new Point2D.Double(); - Point2D pScreen = new Point2D.Double(); - for (int x = left; x <= right; x++) { - linePositions[0][x - left] = x * interval; - p.setLocation(x * interval, 0); - viewport.getTransform().transform(p, pScreen); - linePositionsScreen[0][x - left] = (int) pScreen.getX(); - } - - for (int y = bottom; y <= top; y++) { - linePositions[1][y - bottom] = y * interval; - p.setLocation(0, y * interval); - viewport.getTransform().transform(p, pScreen); - linePositionsScreen[1][y - bottom] = (int) pScreen.getY(); - } - - for (int x = left; x <= right; x++) { - int xScreen = linePositionsScreen[0][x - left]; - for (int y = bottom; y <= top; y++) { - int yScreen = linePositionsScreen[1][y - bottom]; - linesPath.moveTo(xScreen - crossRadius, yScreen); - linesPath.lineTo(xScreen + crossRadius, yScreen); - linesPath.moveTo(xScreen, yScreen - crossRadius); - linesPath.lineTo(xScreen, yScreen + crossRadius); + double[][] positions, int[][] screenPositions, Path2D shape) { + + updateGridPositions(viewport, interval, positions, screenPositions); + + for (int xIndex = 0; xIndex < screenPositions[0].length; xIndex++) { + int xScreen = screenPositions[0][xIndex]; + for (int yIndex = 0; yIndex < screenPositions[1].length; yIndex++) { + int yScreen = screenPositions[1][yIndex]; + shape.moveTo(xScreen - crossRadius, yScreen); + shape.lineTo(xScreen + crossRadius, yScreen); + shape.moveTo(xScreen, yScreen - crossRadius); + shape.lineTo(xScreen, yScreen + crossRadius); } } } private void updateGridMinorLines(Viewport viewport, double interval) { - minorLinesPath = new Path2D.Double(); - updateGridLines(viewport, interval, minorLinePositions, minorLinePositionsScreen, minorLinesPath); + minorShape = new Path2D.Double(); + updateGridLines(viewport, interval, minorPositions, minorScreenPositions, minorShape); } private void updateGridMajorLines(Viewport viewport, double interval) { - majorLinesPath = new Path2D.Double(); - updateGridLines(viewport, interval, majorLinePositions, majorLinePositionsScreen, majorLinesPath); + majorShape = new Path2D.Double(); + updateGridLines(viewport, interval, majorPositions, majorScreenPositions, majorShape); } private void updateGridLines(Viewport viewport, double interval, - double[][] linePositions, int[][] linePositionsScreen, Path2D linesPath) { + double[][] positions, int[][] screenPositions, Path2D shape) { + + updateGridPositions(viewport, interval, positions, screenPositions); - // Compute the visible user space area from the viewport Rectangle view = viewport.getShape(); - Point2D visibleUL = new Point2D.Double(); - Point2D visibleLR = new Point2D.Double(); + for (int xIndex = 0; xIndex < screenPositions[0].length; xIndex++) { + int xScreen = screenPositions[0][xIndex]; + shape.moveTo(xScreen, view.y + view.height); + shape.lineTo(xScreen, view.y); + } + + for (int yIndex = 0; yIndex < screenPositions[1].length; yIndex++) { + int yScreen = screenPositions[1][yIndex]; + shape.moveTo(view.x, yScreen); + shape.lineTo(view.x + view.width, yScreen); + } + } + + private Rectangle getGridBounds(Viewport viewport, double interval) { + Rectangle view = viewport.getShape(); + Point viewLL = new Point(view.x, view.height + view.y); - Point viewUR = new Point(view.width + view.x, view.y); + Point2D visibleUL = new Point2D.Double(); viewport.getInverseTransform().transform(viewLL, visibleUL); + + Point viewUR = new Point(view.width + view.x, view.y); + Point2D visibleLR = new Point2D.Double(); viewport.getInverseTransform().transform(viewUR, visibleLR); // Compute the leftmost, rightmost, topmost and bottom visible grid lines @@ -261,36 +150,41 @@ public class Grid implements ViewportListener { int top = (int) Math.floor(visibleUL.getY() / interval); int left = (int) Math.ceil(visibleUL.getX() / interval); int right = (int) Math.floor(visibleLR.getX() / interval); + return new Rectangle(left, bottom, right - left, top - bottom); + } - // Build the gridlines positions, store them as user-space coordinates, - // screen-space coordinates, and as a drawable path (in screen-space) - final int countMajH = Math.max(0, right - left + 1); - linePositions[0] = new double[countMajH]; - linePositionsScreen[0] = new int[countMajH]; - - final int countMajV = Math.max(0, top - bottom + 1); - linePositions[1] = new double[countMajV]; - linePositionsScreen[1] = new int[countMajV]; + private void updateGridPositions(Viewport viewport, double interval, + double[][] positions, int[][] screenPositions) { Point2D p = new Point2D.Double(); Point2D pScreen = new Point2D.Double(); - for (int x = left; x <= right; x++) { - linePositions[0][x - left] = x * interval; - p.setLocation(x * interval, 0); - viewport.getTransform().transform(p, pScreen); - linePositionsScreen[0][x - left] = (int) pScreen.getX(); - linesPath.moveTo((int) pScreen.getX(), viewLL.getY()); - linesPath.lineTo((int) pScreen.getX(), viewUR.getY()); + Rectangle r = getGridBounds(viewport, interval); + + // Build the gridlines positions, store them as user-space coordinates, + // screen-space coordinates, and as a drawable path (in screen-space) + int xCount = Math.max(0, r.width + 1); + int yCount = Math.max(0, r.height + 1); + if ((xCount > MAX_GRID_COUNT) || (yCount > MAX_GRID_COUNT)) { + xCount = 0; + yCount = 0; } - for (int y = bottom; y <= top; y++) { - linePositions[1][y - bottom] = y * interval; - p.setLocation(0, y * interval); + positions[0] = new double[xCount]; + screenPositions[0] = new int[xCount]; + for (int xIndex = 0; xIndex < xCount; xIndex++) { + p.setLocation((r.x + xIndex) * interval, 0); + positions[0][xIndex] = p.getX(); viewport.getTransform().transform(p, pScreen); - linePositionsScreen[1][y - bottom] = (int) pScreen.getY(); + screenPositions[0][xIndex] = (int) pScreen.getX(); + } - linesPath.moveTo(viewLL.getX(), pScreen.getY()); - linesPath.lineTo(viewUR.getX(), pScreen.getY()); + positions[1] = new double[yCount]; + screenPositions[1] = new int[yCount]; + for (int yIndex = 0; yIndex < yCount; yIndex++) { + p.setLocation(0, (r.y + yIndex) * interval); + positions[1][yIndex] = p.getY(); + viewport.getTransform().transform(p, pScreen); + screenPositions[1][yIndex] = (int) pScreen.getY(); } } @@ -303,22 +197,9 @@ public class Grid implements ViewportListener { public void draw(Graphics2D g) { g.setStroke(stroke); g.setColor(EditorCommonSettings.getGridColor()); - g.draw(minorLinesPath); + g.draw(minorShape); g.setColor(EditorCommonSettings.getGridColor().darker()); - g.draw(majorLinesPath); - } - - /** - * Returns minor grid lines positions <i>in user space, double precision</i> as a 2-dimensional array. First row of the array contains x-coordinates of the vertical grid lines, - * second row contains y-coordinates of the horizontal grid lines. - * - * @return - * getMinorLinePositions()[0] - the array containing vertical grid lines positions - * getMinorLinePositions()[1] - the array containing horizontal grid lines positions - * - */ - public double[][] getMinorLinePositions() { - return minorLinePositions; + g.draw(majorShape); } /** @@ -326,24 +207,24 @@ public class Grid implements ViewportListener { * second row contains y-coordinates of the horizontal grid lines. * * @return - * getMajorLinePositions()[0] - the array containing vertical grid lines positions - * getMajorLinePositions()[1] - the array containing horizontal grid lines positions + * getMajorPositions()[0] - the array containing vertical grid lines positions + * getMajorPositions()[1] - the array containing horizontal grid lines positions * */ - public double[][] getMajorLinePositions() { - return majorLinePositions; + public double[][] getMajorPositions() { + return majorPositions; } /** * Returns minor grid lines positions <i>in screen space space, integer precision</i> as a 2-dimensional array. * First row of the array contains x-coordinates of the vertical grid lines, second row contains y-coordinates of the horizontal grid lines, * @return - * getMinorLinePositionsScreen()[0] - the array containing vertical grid lines positions - * getMinorLinePositionsScreen()[1] - the array containing horizontal grid lines positions + * getMinorScreenPositions()[0] - the array containing vertical grid lines positions + * getMinorScreenPositions()[1] - the array containing horizontal grid lines positions * */ - public int[][] getMinorLinePositionsScreen() { - return minorLinePositionsScreen; + public int[][] getMinorScreenPositions() { + return minorScreenPositions; } /** @@ -351,12 +232,12 @@ public class Grid implements ViewportListener { * second row contains X-coordinates of the vertical grid lines. * * @return - * getMajorLinePositionsScreen()[0] - the array containing vertical grid lines positions - * getMajorLinePositionsScreen()[1] - the array containing horizontal grid lines positions + * getMajorScreenPositions()[0] - the array containing vertical grid lines positions + * getMajorScreenPositions()[1] - the array containing horizontal grid lines positions * */ - public int[][] getMajorLinePositionsScreen() { - return majorLinePositionsScreen; + public int[][] getMajorScreenPositions() { + return majorScreenPositions; } @Override @@ -393,7 +274,7 @@ public class Grid implements ViewportListener { * @return snapped coordinate value */ public double snapCoordinate(double x) { - double m = majorInterval * minorIntervalFactor; + double m = majorInterval * MINOR_INTERVAL_FACTOR; return Math.floor(x / m + 0.5) * m; } diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Ruler.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Ruler.java index 94c1f2f24..c0c566ab3 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Ruler.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Ruler.java @@ -139,14 +139,14 @@ public class Ruler implements GridListener { @Override public void gridChanged(Grid grid) { - int[][] minorLinesScreen = grid.getMinorLinePositionsScreen(); + int[][] minorLinesScreen = grid.getMinorScreenPositions(); horizontalMinorTicks = minorLinesScreen[0]; verticalMinorTicks = minorLinesScreen[1]; - int[][] majorLinesScreen = grid.getMajorLinePositionsScreen(); + int[][] majorLinesScreen = grid.getMajorScreenPositions(); horizontalMajorTicks = majorLinesScreen[0]; verticalMajorTicks = majorLinesScreen[1]; - double[][] majorLines = grid.getMajorLinePositions(); + double[][] majorLines = grid.getMajorPositions(); horizontalMajorCaptions = new String[majorLines[0].length]; verticalMajorCaptions = new String[majorLines[1].length]; diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Viewport.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Viewport.java index f2e0abe45..71f66825b 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Viewport.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Viewport.java @@ -24,27 +24,27 @@ public class Viewport { * The scaling factor per zoom level. Increasing the zoom level by 1 will effectively magnify all * objects by this factor, while decreasing it by 1 will shrink all objects by the same factor. */ - protected static final double SCALE_FACTOR = Math.pow(2, 1.0 / 8); + private static final double SCALE_FACTOR = Math.pow(2, 1.0 / 8); /** * The origin point in user space. */ - protected static final Point2D ORIGIN = new Point2D.Double(0, 0); + private static final Point2D ORIGIN = new Point2D.Double(0, 0); /** * Current horizontal view translation in user space. */ - protected double tx = 0.0; + private double tx = 0.0; /** * Current vertical view translation in user space. */ - protected double ty = 0.0; + private double ty = 0.0; /** * Current view scale factor. */ - protected double s = DEFAULT_SCALE; + private double s = DEFAULT_SCALE; /** * The transformation from user space to screen space such that the point (0, 0) in user space is @@ -53,12 +53,12 @@ public class Viewport { * vertical coordinate of the viewport, and the coordinates on the X axis are mapped in such a way * as to preserve the aspect ratio of the objects displayed. */ - protected AffineTransform userToScreenTransform; + private AffineTransform userToScreenTransform; /** * The transformation of the user space that takes into account the current pan and zoom values. */ - protected AffineTransform viewTransform; + private AffineTransform viewTransform; /** * The concatenation of the user-to-screen and pan/zoom transforms. @@ -73,18 +73,18 @@ public class Viewport { /** * The current viewport shape. */ - protected Rectangle shape; + private Rectangle shape; /** * The list of listeners to be notified in case of viewport parameters change. */ - protected LinkedList<ViewportListener> listeners; + private LinkedList<ViewportListener> listeners; /** * Called when the viewport parameters such as pan and zoom are changed. Updates the corresponding * transforms, and notifies the change listeners. */ - protected void viewChanged() { + private void viewChanged() { viewTransform.setToIdentity(); viewTransform.scale(s, s); viewTransform.translate(tx, ty);
['workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Grid.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Viewport.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/editor/Ruler.java']
{'.java': 3}
3
3
0
0
3
6,049,423
1,230,136
164,994
1,684
17,200
3,815
355
3
128
22
26
1
0
0
"1970-01-01T00:26:55"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
754
workcraft/workcraft/1192/1191
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1191
https://github.com/workcraft/workcraft/pull/1192
https://github.com/workcraft/workcraft/pull/1192
1
fixes
Tool control icons do not size correctly when base font size is modified
Tool control icons are loaded together with their plugins, which happens before configuration variables are read from `config.xml`. As a result the tool control buttons may have incorrect icon size in case _Base font size_ is changed (its default value is used instead). A solution is to load the tool control icons only when the corresponding tool is activated for the first time.
3a71ed6ce6f8fbebf57cda5c2ae6adc144b23939
92be3eacedb34f1c6d0c346c4547707e5e9054e3
https://github.com/workcraft/workcraft/compare/3a71ed6ce6f8fbebf57cda5c2ae6adc144b23939...92be3eacedb34f1c6d0c346c4547707e5e9054e3
diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/CycleAnalyserTool.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/CycleAnalyserTool.java index 450dbb23a..6f75b58ec 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/CycleAnalyserTool.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/CycleAnalyserTool.java @@ -70,22 +70,22 @@ public class CycleAnalyserTool extends AbstractGraphEditorTool { private JPanel getBreakControlsPanel(final GraphEditor editor) { JButton tagPathBreakerSelfloopPinsButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-cycle-selfloop_pins.svg"), + "images/circuit-cycle-selfloop_pins.svg", "Path breaker all self-loops", l -> changePathBreaker(editor, c -> CycleUtils.tagPathBreakerSelfloopPins(c))); JButton tagPathBreakerAutoAppendButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-cycle-auto_append.svg"), + "images/circuit-cycle-auto_append.svg", "Auto-append path breaker pins as necessary to complete cycle breaking", l -> changePathBreaker(editor, c -> CycleUtils.tagPathBreakerAutoAppend(c))); JButton tagPathBreakerAutoDiscardButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-cycle-auto_discard.svg"), + "images/circuit-cycle-auto_discard.svg", "Auto-discard path breaker pins that are redundant for cycle breaking", l -> changePathBreaker(editor, c -> CycleUtils.tagPathBreakerAutoDiscard(c))); JButton tagPathBreakerClearAllButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-cycle-clear_all.svg"), + "images/circuit-cycle-clear_all.svg", "Clear all path breaker pins", l -> changePathBreaker(editor, c -> CycleUtils.tagPathBreakerClearAll(c))); diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java index 0e2e952b6..25e4e3f83 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java @@ -71,34 +71,34 @@ public class InitialisationAnalyserTool extends AbstractGraphEditorTool { private JPanel getForcedControlsPanel(final GraphEditor editor) { JButton tagForceInitInputPortsButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-input_ports.svg"), - "Force init all input ports (environment responsibility)"); - tagForceInitInputPortsButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitInputPorts)); + "images/circuit-initialisation-input_ports.svg", + "Force init all input ports (environment responsibility)", + l -> changeForceInit(editor, ResetUtils::tagForceInitInputPorts)); JButton tagForceInitNecessaryPinsButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-problematic_pins.svg"), - "Force init output pins with problematic initial state"); - tagForceInitNecessaryPinsButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitProblematicPins)); + "images/circuit-initialisation-problematic_pins.svg", + "Force init output pins with problematic initial state", + l -> changeForceInit(editor, ResetUtils::tagForceInitProblematicPins)); JButton tagForceInitSequentialPinsButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-sequential_pins.svg"), - "Force init output pins of sequential gates"); - tagForceInitSequentialPinsButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitSequentialPins)); + "images/circuit-initialisation-sequential_pins.svg", + "Force init output pins of sequential gates", + l -> changeForceInit(editor, ResetUtils::tagForceInitSequentialPins)); JButton tagForceInitAutoAppendButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-auto_append.svg"), - "Auto-append force init pins as necessary to complete initialisation"); - tagForceInitAutoAppendButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitAutoAppend)); + "images/circuit-initialisation-auto_append.svg", + "Auto-append force init pins as necessary to complete initialisation", + l -> changeForceInit(editor, ResetUtils::tagForceInitAutoAppend)); JButton tagForceInitAutoDiscardButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-auto_discard.svg"), - "Auto-discard force init pins that are redundant for initialisation"); - tagForceInitAutoDiscardButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitAutoDiscard)); + "images/circuit-initialisation-auto_discard.svg", + "Auto-discard force init pins that are redundant for initialisation", + l -> changeForceInit(editor, ResetUtils::tagForceInitAutoDiscard)); JButton tagForceInitClearAllButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/circuit-initialisation-clear_all.svg"), - "Clear all force init ports and pins"); - tagForceInitClearAllButton.addActionListener(l -> changeForceInit(editor, ResetUtils::tagForceInitClearAll)); + "images/circuit-initialisation-clear_all.svg", + "Clear all force init ports and pins", + l -> changeForceInit(editor, ResetUtils::tagForceInitClearAll)); JPanel buttonPanel = new JPanel(); buttonPanel.add(tagForceInitInputPortsButton); diff --git a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tools/CpogSelectionTool.java b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tools/CpogSelectionTool.java index 6351537d3..3064a224a 100644 --- a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tools/CpogSelectionTool.java +++ b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tools/CpogSelectionTool.java @@ -40,6 +40,9 @@ import java.util.concurrent.ConcurrentLinkedQueue; public class CpogSelectionTool extends SelectionTool { + private static final String GROUP_ICON = "images/selection-page.svg"; + private static final String GROUP_HINT = "Combine selection as a scenario (Alt-G)"; + private static final double minRadius = 2.0; private static final double expandRadius = 2.0; @@ -211,10 +214,7 @@ public class CpogSelectionTool extends SelectionTool { panel.add(expressionScroll, BorderLayout.CENTER); panel.add(buttonPanel, BorderLayout.SOUTH); - JButton groupPageButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-page.svg"), - "Combine selection as a scenario (Alt-G)", - event -> groupPageAction(editor)); + JButton groupPageButton = GuiUtils.createIconButton(GROUP_ICON, GROUP_HINT, event -> groupPageAction(editor)); JPanel groupPanel = getGroupPanel(); if (groupPanel != null) { diff --git a/workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/tools/PolicySelectionTool.java b/workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/tools/PolicySelectionTool.java index 0948e1050..ed997b67c 100644 --- a/workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/tools/PolicySelectionTool.java +++ b/workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/tools/PolicySelectionTool.java @@ -23,6 +23,12 @@ import java.util.Set; public class PolicySelectionTool extends SelectionTool { + private static final String BUNDLE_ICON = "images/policy-selection-bundle.svg"; + private static final String UNBUNDLE_ICON = "images/policy-selection-unbundle.svg"; + + private static final String BUNDLE_HINT = "Bundle selected transitions (" + DesktopApi.getMenuKeyName() + "-B)"; + private static final String UNBUNDLE_HINT = "Unbundle selected transitions (" + DesktopApi.getMenuKeyName() + "+Shift-B)"; + public PolicySelectionTool() { super(true, false, true, true); } @@ -30,17 +36,8 @@ public class PolicySelectionTool extends SelectionTool { @Override public void updateControlsToolbar(JToolBar toolbar, final GraphEditor editor) { super.updateControlsToolbar(toolbar, editor); - - JButton bundleButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/policy-selection-bundle.svg"), - "Bundle selected transitions (" + DesktopApi.getMenuKeyName() + "-B)", - event -> selectionBundle(editor)); - - JButton unbundleButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/policy-selection-unbundle.svg"), - "Unbundle selected transitions (" + DesktopApi.getMenuKeyName() + "+Shift-B)", - event -> selectionUnbundle(editor)); - + JButton bundleButton = GuiUtils.createIconButton(BUNDLE_ICON, BUNDLE_HINT, event -> selectionBundle(editor)); + JButton unbundleButton = GuiUtils.createIconButton(UNBUNDLE_ICON, UNBUNDLE_HINT, event -> selectionUnbundle(editor)); toolbar.add(bundleButton); toolbar.add(unbundleButton); toolbar.addSeparator(); diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/MainWindowIconManager.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/MainWindowIconManager.java index 5cafe78bd..5faa424a4 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/MainWindowIconManager.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/MainWindowIconManager.java @@ -1,6 +1,5 @@ package org.workcraft.gui; -import org.workcraft.dom.visual.SizeHelper; import org.workcraft.utils.GuiUtils; import javax.swing.*; @@ -34,10 +33,9 @@ public class MainWindowIconManager { } public static void apply(final MainWindow window) { - int size = SizeHelper.getIconSize(); Thread thread = new Thread(() -> { - ImageIcon activeSvg = GuiUtils.createIconFromSVG("images/icon.svg", size, size, Color.WHITE); - ImageIcon inactiveSvg = GuiUtils.createIconFromSVG("images/icon-inactive.svg", size, size, Color.WHITE); + ImageIcon activeSvg = GuiUtils.createIconFromSVG("images/icon.svg"); + ImageIcon inactiveSvg = GuiUtils.createIconFromSVG("images/icon-inactive.svg"); final Image activeIcon = activeSvg.getImage(); final Image inactiveIcon = inactiveSvg.getImage(); try { diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SelectionTool.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SelectionTool.java index e94e1dc98..bd385e6e5 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SelectionTool.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SelectionTool.java @@ -35,6 +35,25 @@ import java.util.*; public class SelectionTool extends AbstractGraphEditorTool { + public static final String GROUP_ICON = "images/selection-group.svg"; + public static final String GROUP_HINT = "Group selection (" + DesktopApi.getMenuKeyName() + "-G)"; + public static final String PAGE_ICON = "images/selection-page.svg"; + public static final String PAGE_HHINT = "Combine selection into a page (Alt-G)"; + public static final String UNGROUP_ICON = "images/selection-ungroup.svg"; + public static final String UNGROUP_HINT = "Ungroup selection (" + DesktopApi.getMenuKeyName() + "+Shift-G)"; + public static final String UP_LEVEL_ICON = "images/selection-level_up.svg"; + public static final String UP_LEVEL_HINT = "Level up (PageUp)"; + public static final String DOWN_LEVEL_ICON = "images/selection-level_down.svg"; + public static final String DOWN_LEVEL_HINT = "Level down (PageDown)"; + public static final String HORIZONTAL_FLIP_ICON = "images/selection-flip_horizontal.svg"; + public static final String HORIZONTAL_FLIP_HINT = "Flip horizontal"; + public static final String VERTICAL_FLIP_ICON = "images/selection-flip_vertical.svg"; + public static final String VERTICAL_FLIP_HINT = "Flip vertical"; + public static final String CW_ROTATE_ICON = "images/selection-rotate_clockwise.svg"; + public static final String CW_ROTATE_HINT = "Rotate clockwise"; + public static final String CCW_ROTATE_ICON = "images/selection-rotate_counterclockwise.svg"; + public static final String CCW_ROTATE_HINT = "Rotate counterclockwise"; + public enum DrugState { NONE, MOVE, SELECT } public enum SelectionMode { NONE, ADD, REMOVE, REPLACE } @@ -97,10 +116,7 @@ public class SelectionTool extends AbstractGraphEditorTool { super.updateControlsToolbar(toolbar, editor); if (enableGrouping) { - JButton groupButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-group.svg"), - "Group selection (" + DesktopApi.getMenuKeyName() + "-G)"); - groupButton.addActionListener(event -> { + JButton groupButton = GuiUtils.createIconButton(GROUP_ICON, GROUP_HINT, event -> { groupSelection(editor); editor.requestFocus(); }); @@ -108,10 +124,7 @@ public class SelectionTool extends AbstractGraphEditorTool { } if (enablePaging) { - JButton groupPageButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-page.svg"), - "Combine selection into a page (Alt-G)"); - groupPageButton.addActionListener(event -> { + JButton groupPageButton = GuiUtils.createIconButton(PAGE_ICON, PAGE_HHINT, event -> { pageSelection(editor); editor.requestFocus(); }); @@ -119,28 +132,19 @@ public class SelectionTool extends AbstractGraphEditorTool { } if (enableGrouping || enablePaging) { - JButton ungroupButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-ungroup.svg"), - "Ungroup selection (" + DesktopApi.getMenuKeyName() + "+Shift-G)"); - ungroupButton.addActionListener(event -> { + JButton ungroupButton = GuiUtils.createIconButton(UNGROUP_ICON, UNGROUP_HINT, event -> { ungroupSelection(editor); editor.requestFocus(); }); toolbar.add(ungroupButton); - JButton levelUpButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-level_up.svg"), - "Level up (PageUp)"); - levelUpButton.addActionListener(event -> { + JButton levelUpButton = GuiUtils.createIconButton(UP_LEVEL_ICON, UP_LEVEL_HINT, event -> { changeLevelUp(editor); editor.requestFocus(); }); toolbar.add(levelUpButton); - JButton levelDownButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-level_down.svg"), - "Level down (PageDown)"); - levelDownButton.addActionListener(event -> { + JButton levelDownButton = GuiUtils.createIconButton(DOWN_LEVEL_ICON, DOWN_LEVEL_HINT, event -> { changeLevelDown(editor); editor.requestFocus(); }); @@ -150,19 +154,13 @@ public class SelectionTool extends AbstractGraphEditorTool { toolbar.addSeparator(); } if (enableFlipping) { - JButton flipHorizontalButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-flip_horizontal.svg"), - "Flip horizontal"); - flipHorizontalButton.addActionListener(event -> { + JButton flipHorizontalButton = GuiUtils.createIconButton(HORIZONTAL_FLIP_ICON, HORIZONTAL_FLIP_HINT, event -> { flipSelectionHorizontal(editor); editor.requestFocus(); }); toolbar.add(flipHorizontalButton); - JButton flipVerticalButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-flip_vertical.svg"), - "Flip vertical"); - flipVerticalButton.addActionListener(event -> { + JButton flipVerticalButton = GuiUtils.createIconButton(VERTICAL_FLIP_ICON, VERTICAL_FLIP_HINT, event -> { flipSelectionVertical(editor); editor.requestFocus(); }); @@ -170,19 +168,13 @@ public class SelectionTool extends AbstractGraphEditorTool { } if (enableRotating) { - JButton rotateClockwiseButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-rotate_clockwise.svg"), - "Rotate clockwise"); - rotateClockwiseButton.addActionListener(event -> { + JButton rotateClockwiseButton = GuiUtils.createIconButton(CW_ROTATE_ICON, CW_ROTATE_HINT, event -> { rotateSelectionClockwise(editor); editor.requestFocus(); }); toolbar.add(rotateClockwiseButton); - JButton rotateCounterclockwiseButton = GuiUtils.createIconButton( - GuiUtils.createIconFromSVG("images/selection-rotate_counterclockwise.svg"), - "Rotate counterclockwise"); - rotateCounterclockwiseButton.addActionListener(event -> { + JButton rotateCounterclockwiseButton = GuiUtils.createIconButton(CCW_ROTATE_ICON, CCW_ROTATE_HINT, event -> { rotateSelectionCounterclockwise(editor); editor.requestFocus(); }); diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SimulationTool.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SimulationTool.java index 368257d60..36d24c2c4 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SimulationTool.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SimulationTool.java @@ -36,18 +36,18 @@ import java.util.Map; public abstract class SimulationTool extends AbstractGraphEditorTool implements ClipboardOwner { - private static final ImageIcon PLAY_ICON = GuiUtils.createIconFromSVG("images/simulation-play.svg"); - private static final ImageIcon PAUSE_ICON = GuiUtils.createIconFromSVG("images/simulation-pause.svg"); - private static final ImageIcon BACKWARD_ICON = GuiUtils.createIconFromSVG("images/simulation-backward.svg"); - private static final ImageIcon FORWARD_ICON = GuiUtils.createIconFromSVG("images/simulation-forward.svg"); - private static final ImageIcon RECORD_ICON = GuiUtils.createIconFromSVG("images/simulation-record.svg"); - private static final ImageIcon STOP_ICON = GuiUtils.createIconFromSVG("images/simulation-stop.svg"); - private static final ImageIcon EJECT_ICON = GuiUtils.createIconFromSVG("images/simulation-eject.svg"); - private static final ImageIcon TIMING_DIAGRAM_ICON = GuiUtils.createIconFromSVG("images/simulation-trace-graph.svg"); - private static final ImageIcon COPY_STATE_ICON = GuiUtils.createIconFromSVG("images/simulation-trace-copy.svg"); - private static final ImageIcon PASTE_STATE_ICON = GuiUtils.createIconFromSVG("images/simulation-trace-paste.svg"); - private static final ImageIcon MERGE_TRACE_ICON = GuiUtils.createIconFromSVG("images/simulation-trace-merge.svg"); - private static final ImageIcon SAVE_INITIAL_STATE_ICON = GuiUtils.createIconFromSVG("images/simulation-marking-save.svg"); + private static final String PLAY_ICON = "images/simulation-play.svg"; + private static final String PAUSE_ICON = "images/simulation-pause.svg"; + private static final String BACKWARD_ICON = "images/simulation-backward.svg"; + private static final String FORWARD_ICON = "images/simulation-forward.svg"; + private static final String RECORD_ICON = "images/simulation-record.svg"; + private static final String STOP_ICON = "images/simulation-stop.svg"; + private static final String EJECT_ICON = "images/simulation-eject.svg"; + private static final String TIMING_DIAGRAM_ICON = "images/simulation-trace-graph.svg"; + private static final String COPY_STATE_ICON = "images/simulation-trace-copy.svg"; + private static final String PASTE_STATE_ICON = "images/simulation-trace-paste.svg"; + private static final String MERGE_TRACE_ICON = "images/simulation-trace-merge.svg"; + private static final String SAVE_INITIAL_STATE_ICON = "images/simulation-marking-save.svg"; private static final String PLAY_HINT = "Play through the trace"; private static final String PAUSE_HINT = "Pause trace playback"; @@ -104,153 +104,125 @@ public abstract class SimulationTool extends AbstractGraphEditorTool implements return panel; } - playButton = GuiUtils.createIconButton(PLAY_ICON, PLAY_HINT); - backwardButton = GuiUtils.createIconButton(BACKWARD_ICON, BACKWARD_HINT); - forwardButton = GuiUtils.createIconButton(FORWARD_ICON, FORWARD_HINT); - recordButton = GuiUtils.createIconButton(RECORD_ICON, RECORD_HINT); - ejectButton = GuiUtils.createIconButton(EJECT_ICON, EJECT_HINT); - - speedSlider = new SpeedSlider(); - - JButton generateGraphButton = GuiUtils.createIconButton(TIMING_DIAGRAM_ICON, TIMING_DIAGRAM_HINT); - JButton copyStateButton = GuiUtils.createIconButton(COPY_STATE_ICON, COPY_STATE_HINT); - JButton pasteStateButton = GuiUtils.createIconButton(PASTE_STATE_ICON, PASTE_STATE_HINT); - JButton mergeTraceButton = GuiUtils.createIconButton(MERGE_TRACE_ICON, MERGE_TRACE_HINT); - JButton saveInitStateButton = GuiUtils.createIconButton(SAVE_INITIAL_STATE_ICON, SAVE_INITIAL_STATE_HINT); - - JPanel simulationControl = new JPanel(); - simulationControl.add(playButton); - simulationControl.add(backwardButton); - simulationControl.add(forwardButton); - simulationControl.add(recordButton); - simulationControl.add(ejectButton); - GuiUtils.setButtonPanelLayout(simulationControl, playButton.getPreferredSize()); - - JPanel speedControl = new JPanel(); - speedControl.add(speedSlider); - GuiUtils.setButtonPanelLayout(speedControl, speedSlider.getPreferredSize()); - - JPanel traceControl = new JPanel(); - if (enableTraceGraph) { - traceControl.add(generateGraphButton); - } - traceControl.add(copyStateButton); - traceControl.add(pasteStateButton); - traceControl.add(mergeTraceButton); - traceControl.add(saveInitStateButton); - GuiUtils.setButtonPanelLayout(simulationControl, copyStateButton.getPreferredSize()); - - controlPanel = new JPanel(); - controlPanel.setLayout(new WrapLayout()); - controlPanel.add(simulationControl); - controlPanel.add(speedControl); - controlPanel.add(traceControl); - - traceTable = new JTable(new TraceTableModel()); - traceTable.getTableHeader().setDefaultRenderer(new FlatHeaderRenderer()); - traceTable.getTableHeader().setReorderingAllowed(false); - traceTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - traceTable.setRowHeight(SizeHelper.getComponentHeightFromFont(traceTable.getFont())); - traceTable.setDefaultRenderer(Object.class, new TraceTableCellRenderer()); - - tracePane = new JScrollPane(); - tracePane.setViewportView(traceTable); - tracePane.setMinimumSize(new Dimension(1, 50)); - - statePane = new JScrollPane(); - statePane.setMinimumSize(new Dimension(1, 50)); - - splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tracePane, statePane); - splitPane.setOneTouchExpandable(true); - splitPane.setResizeWeight(0.5); - - infoPanel = new JPanel(); - infoPanel.setLayout(new BorderLayout()); - infoPanel.add(splitPane, BorderLayout.CENTER); - speedSlider.addChangeListener(e -> { - if (timer != null) { - timer.stop(); - int delay = speedSlider.getDelay(); - timer.setInitialDelay(delay); - timer.setDelay(delay); - timer.start(); - } - updateState(editor); - editor.requestFocus(); - }); - - recordButton.addActionListener(event -> { + playButton = GuiUtils.createIconButton(PLAY_ICON, PLAY_HINT, event -> { if (timer == null) { - timer = new Timer(speedSlider.getDelay(), event1 -> stepRandom(editor)); + timer = new Timer(speedSlider.getDelay(), event1 -> stepForward(editor)); timer.start(); - random = true; - } else if (random) { + random = false; + } else if (!random) { timer.stop(); timer = null; random = false; } else { - random = true; + random = false; } updateState(editor); editor.requestFocus(); }); - playButton.addActionListener(event -> { + backwardButton = GuiUtils.createIconButton(BACKWARD_ICON, BACKWARD_HINT, event -> { + stepBackward(editor); + editor.requestFocus(); + }); + + forwardButton = GuiUtils.createIconButton(FORWARD_ICON, FORWARD_HINT, event -> { + stepForward(editor); + editor.requestFocus(); + }); + + recordButton = GuiUtils.createIconButton(RECORD_ICON, RECORD_HINT, event -> { if (timer == null) { - timer = new Timer(speedSlider.getDelay(), event1 -> stepForward(editor)); + timer = new Timer(speedSlider.getDelay(), event1 -> stepRandom(editor)); timer.start(); - random = false; - } else if (!random) { + random = true; + } else if (random) { timer.stop(); timer = null; random = false; } else { - random = false; + random = true; } updateState(editor); editor.requestFocus(); }); - ejectButton.addActionListener(event -> { + ejectButton = GuiUtils.createIconButton(EJECT_ICON, EJECT_HINT, event -> { clearTraces(editor); editor.requestFocus(); }); - backwardButton.addActionListener(event -> { - stepBackward(editor); - editor.requestFocus(); - }); - - forwardButton.addActionListener(event -> { - stepForward(editor); + speedSlider = new SpeedSlider(); + speedSlider.addChangeListener(e -> { + if (timer != null) { + timer.stop(); + int delay = speedSlider.getDelay(); + timer.setInitialDelay(delay); + timer.setDelay(delay); + timer.start(); + } + updateState(editor); editor.requestFocus(); }); - generateGraphButton.addActionListener(event -> { + JButton generateGraphButton = GuiUtils.createIconButton(TIMING_DIAGRAM_ICON, TIMING_DIAGRAM_HINT, event -> { generateTraceGraph(editor); editor.requestFocus(); }); - copyStateButton.addActionListener(event -> { + JButton copyStateButton = GuiUtils.createIconButton(COPY_STATE_ICON, COPY_STATE_HINT, event -> { copyState(editor); editor.requestFocus(); }); - pasteStateButton.addActionListener(event -> { + JButton pasteStateButton = GuiUtils.createIconButton(PASTE_STATE_ICON, PASTE_STATE_HINT, event -> { pasteState(editor); editor.requestFocus(); }); - mergeTraceButton.addActionListener(event -> { + JButton mergeTraceButton = GuiUtils.createIconButton(MERGE_TRACE_ICON, MERGE_TRACE_HINT, event -> { mergeTrace(editor); editor.requestFocus(); }); - saveInitStateButton.addActionListener(event -> { + JButton saveInitStateButton = GuiUtils.createIconButton(SAVE_INITIAL_STATE_ICON, SAVE_INITIAL_STATE_HINT, event -> { savedState = readUnderlyingModelState(); editor.requestFocus(); }); + JPanel simulationControl = new JPanel(); + simulationControl.add(playButton); + simulationControl.add(backwardButton); + simulationControl.add(forwardButton); + simulationControl.add(recordButton); + simulationControl.add(ejectButton); + GuiUtils.setButtonPanelLayout(simulationControl, playButton.getPreferredSize()); + + JPanel speedControl = new JPanel(); + speedControl.add(speedSlider); + GuiUtils.setButtonPanelLayout(speedControl, speedSlider.getPreferredSize()); + + JPanel traceControl = new JPanel(); + if (enableTraceGraph) { + traceControl.add(generateGraphButton); + } + traceControl.add(copyStateButton); + traceControl.add(pasteStateButton); + traceControl.add(mergeTraceButton); + traceControl.add(saveInitStateButton); + GuiUtils.setButtonPanelLayout(simulationControl, copyStateButton.getPreferredSize()); + + controlPanel = new JPanel(); + controlPanel.setLayout(new WrapLayout()); + controlPanel.add(simulationControl); + controlPanel.add(speedControl); + controlPanel.add(traceControl); + + traceTable = new JTable(new TraceTableModel()); + traceTable.getTableHeader().setDefaultRenderer(new FlatHeaderRenderer()); + traceTable.getTableHeader().setReorderingAllowed(false); + traceTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + traceTable.setRowHeight(SizeHelper.getComponentHeightFromFont(traceTable.getFont())); + traceTable.setDefaultRenderer(Object.class, new TraceTableCellRenderer()); traceTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { @@ -285,6 +257,21 @@ public abstract class SimulationTool extends AbstractGraphEditorTool implements } }); + tracePane = new JScrollPane(); + tracePane.setViewportView(traceTable); + tracePane.setMinimumSize(new Dimension(1, 50)); + + statePane = new JScrollPane(); + statePane.setMinimumSize(new Dimension(1, 50)); + + splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tracePane, statePane); + splitPane.setOneTouchExpandable(true); + splitPane.setResizeWeight(0.5); + + infoPanel = new JPanel(); + infoPanel.setLayout(new BorderLayout()); + infoPanel.add(splitPane, BorderLayout.CENTER); + panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(controlPanel, BorderLayout.NORTH); @@ -349,26 +336,26 @@ public abstract class SimulationTool extends AbstractGraphEditorTool implements public void updateState(final GraphEditor editor) { if (timer == null) { - playButton.setIcon(PLAY_ICON); + playButton.setIcon(GuiUtils.createIconFromSVG(PLAY_ICON)); playButton.setToolTipText(PLAY_HINT); - recordButton.setIcon(RECORD_ICON); + recordButton.setIcon(GuiUtils.createIconFromSVG(RECORD_ICON)); recordButton.setToolTipText(RECORD_HINT); } else { if (random) { - playButton.setIcon(PLAY_ICON); + playButton.setIcon(GuiUtils.createIconFromSVG(PLAY_ICON)); playButton.setToolTipText(PLAY_HINT); - recordButton.setIcon(STOP_ICON); + recordButton.setIcon(GuiUtils.createIconFromSVG(STOP_ICON)); recordButton.setToolTipText(STOP_HINT); timer.setDelay(speedSlider.getDelay()); } else if (branchTrace.canProgress() || (branchTrace.isEmpty() && mainTrace.canProgress())) { - playButton.setIcon(PAUSE_ICON); + playButton.setIcon(GuiUtils.createIconFromSVG(PAUSE_ICON)); playButton.setToolTipText(PAUSE_HINT); - recordButton.setIcon(RECORD_ICON); + recordButton.setIcon(GuiUtils.createIconFromSVG(RECORD_ICON)); timer.setDelay(speedSlider.getDelay()); } else { - playButton.setIcon(PLAY_ICON); + playButton.setIcon(GuiUtils.createIconFromSVG(PLAY_ICON)); playButton.setToolTipText(PLAY_HINT); - recordButton.setIcon(RECORD_ICON); + recordButton.setIcon(GuiUtils.createIconFromSVG(RECORD_ICON)); recordButton.setToolTipText(RECORD_HINT); timer.stop(); timer = null; diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/GuiUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/GuiUtils.java index 1dd8a9c6c..a601555d6 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/GuiUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/GuiUtils.java @@ -81,16 +81,7 @@ public class GuiUtils { return ImageIO.read(res); } - public static ImageIcon createIconFromImage(String path) { - URL res = ClassLoader.getSystemResource(path); - if (res == null) { - System.err.println("Missing icon: " + path); - return null; - } - return new ImageIcon(res); - } - - public static ImageIcon createIconFromSVG(String path, int width, int height, Color background) { + private static ImageIcon createIconFromSVG(String path, int width, int height, Color background) { try { System.setProperty("org.apache.batik.warn_destination", "false"); Document document; @@ -139,23 +130,14 @@ public class GuiUtils { } } - public static ImageIcon createIconFromSVG(String path) { + public static ImageIcon createIconFromSVG(String svgPath) { int iconSize = SizeHelper.getToolIconSize(); - return createIconFromSVG(path, iconSize, iconSize); - } - - public static ImageIcon createIconFromSVG(String path, int width, int height) { - return createIconFromSVG(path, width, height, null); - } - - public static Cursor createCursorFromImage(String path) { - ImageIcon icon = createIconFromImage(path); - return createCursorFromIcon(icon, path); + return createIconFromSVG(svgPath, iconSize, iconSize, null); } - public static Cursor createCursorFromSVG(String path) { - ImageIcon icon = createIconFromSVG(path); - return createCursorFromIcon(icon, path); + public static Cursor createCursorFromSVG(String svgPath) { + ImageIcon icon = createIconFromSVG(svgPath); + return createCursorFromIcon(icon, svgPath); } public static Cursor createCursorFromIcon(ImageIcon icon, String name) { @@ -181,7 +163,8 @@ public class GuiUtils { return toolkit.createCustomCursor(cursorImage, hotSpot, name); } - public static JButton createIconButton(Icon icon, String toolTip, ActionListener action) { + public static JButton createIconButton(String svgPath, String toolTip, ActionListener action) { + ImageIcon icon = createIconFromSVG(svgPath); JButton button = createIconButton(icon, toolTip); button.addActionListener(action); return button;
['workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SelectionTool.java', 'workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/CycleAnalyserTool.java', 'workcraft/WorkcraftCore/src/org/workcraft/utils/GuiUtils.java', 'workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java', 'workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/tools/PolicySelectionTool.java', 'workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tools/CpogSelectionTool.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/tools/SimulationTool.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/MainWindowIconManager.java']
{'.java': 8}
8
8
0
0
8
6,048,903
1,229,827
164,984
1,684
24,654
4,679
397
8
381
63
72
1
0
0
"1970-01-01T00:26:54"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
769
workcraft/workcraft/590/587
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/587
https://github.com/workcraft/workcraft/pull/590
https://github.com/workcraft/workcraft/pull/590
1
closes
Changing colour of tokens in DFS simulation
Color of tokens in DFS simulation is not changing as specified in global preferences.
d93096de7a2dbe295aa1ed2962188a1d5cc67fa1
72e144632497a58296b962aadf6774ed617aaa90
https://github.com/workcraft/workcraft/compare/d93096de7a2dbe295aa1ed2962188a1d5cc67fa1...72e144632497a58296b962aadf6774ed617aaa90
diff --git a/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java b/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java index e91f9fb20..331ba1805 100644 --- a/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java +++ b/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java @@ -21,23 +21,29 @@ package org.workcraft.plugins.petri.tools; +import java.awt.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import org.workcraft.dom.Connection; import org.workcraft.dom.Node; import org.workcraft.dom.math.MathModel; import org.workcraft.dom.visual.VisualNode; import org.workcraft.dom.visual.connections.VisualConnection; +import org.workcraft.gui.Coloriser; import org.workcraft.gui.ExceptionDialog; import org.workcraft.gui.graph.tools.GraphEditor; import org.workcraft.gui.graph.tools.SimulationTool; import org.workcraft.plugins.petri.PetriNetModel; import org.workcraft.plugins.petri.Place; import org.workcraft.plugins.petri.Transition; +import org.workcraft.plugins.petri.VisualPetriNet; import org.workcraft.plugins.petri.VisualPlace; import org.workcraft.plugins.petri.VisualReplicaPlace; +import org.workcraft.plugins.petri.VisualTransition; +import org.workcraft.util.ColorGenerator; import org.workcraft.util.LogUtils; public class PetriSimulationTool extends SimulationTool { @@ -135,26 +141,28 @@ public class PetriSimulationTool extends SimulationTool { public boolean fire(String ref) { boolean result = false; Transition transition = null; + PetriNetModel petri = getUnderlyingPetri(); if (ref != null) { - final Node node = getUnderlyingPetri().getNodeByReference(ref); + final Node node = petri.getNodeByReference(ref); if (node instanceof Transition) { transition = (Transition) node; } } if (isEnabledNode(transition)) { HashMap<Place, Integer> capacity = new HashMap<>(); - for (Node node: getUnderlyingPetri().getPostset(transition)) { + for (Node node: petri.getPostset(transition)) { if (node instanceof Place) { Place place = (Place) node; capacity.put(place, place.getCapacity()); } } - getUnderlyingPetri().fire(transition); - for (Node node: getUnderlyingPetri().getPostset(transition)) { + petri.fire(transition); + coloriseTokens(transition); + for (Node node: petri.getPostset(transition)) { if (node instanceof Place) { Place place = (Place) node; if (place.getCapacity() > capacity.get(place)) { - String placeRef = getUnderlyingPetri().getNodeReference(place); + String placeRef = petri.getNodeReference(place); LogUtils.logWarningLine("Capacity of place '" + placeRef + "' is incresed to " + place.getCapacity() + "."); } } @@ -188,4 +196,37 @@ public class PetriSimulationTool extends SimulationTool { return "Click on a highlighted transition to fire it."; } + protected void coloriseTokens(Transition transition) { + VisualPetriNet visualPetri = (VisualPetriNet) getUnderlyingModel(); + VisualTransition vt = visualPetri.getVisualTransition(transition); + if (vt == null) return; + Color tokenColor = Color.black; + ColorGenerator tokenColorGenerator = vt.getTokenColorGenerator(); + if (tokenColorGenerator != null) { + // generate token colour + tokenColor = tokenColorGenerator.updateColor(); + } else { + // combine preset token colours + for (Connection c: visualPetri.getConnections(vt)) { + if ((c.getSecond() == vt) && (c instanceof VisualConnection)) { + VisualConnection vc = (VisualConnection) c; + if (vc.isTokenColorPropagator() && (vc.getFirst() instanceof VisualPlace)) { + VisualPlace vp = (VisualPlace) vc.getFirst(); + tokenColor = Coloriser.colorise(tokenColor, vp.getTokenColor()); + } + } + } + } + // propagate the colour to postset tokens + for (Connection c: visualPetri.getConnections(vt)) { + if ((c.getFirst() == vt) && (c instanceof VisualConnection)) { + VisualConnection vc = (VisualConnection) c; + if (vc.isTokenColorPropagator() && (vc.getSecond() instanceof VisualPlace)) { + VisualPlace vp = (VisualPlace) vc.getFirst(); + vp.setTokenColor(tokenColor); + } + } + } + } + }
['PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java']
{'.java': 1}
1
1
0
0
1
4,930,081
1,002,433
138,460
1,300
2,630
523
51
1
86
14
15
2
0
0
"1970-01-01T00:24:36"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
757
workcraft/workcraft/986/985
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/985
https://github.com/workcraft/workcraft/pull/986
https://github.com/workcraft/workcraft/pull/986
1
fixes
Trace conversion to DTD misses first level if initial state is high
To reproduce, create a simulation trace "a-" and convert it to DTD -- the resultant waveform misses the initial high level.
d724afdc9b7ff2f684132c17f3bae10fef577d31
16a79af9a87ab9a3a2e21f76e85782e490f27b1e
https://github.com/workcraft/workcraft/compare/d724afdc9b7ff2f684132c17f3bae10fef577d31...16a79af9a87ab9a3a2e21f76e85782e490f27b1e
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java index ede94d41e..8db61a816 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java @@ -818,7 +818,8 @@ public class VerilogImporter implements Importer { try { component.setIsZeroDelay(true); } catch (ArgumentException e) { - LogUtils.logWarning("Component '" + verilogInstance.name + "': " + e.getMessage()); + LogUtils.logWarning(e.getMessage() + + " Zero delay attribute is ignored for component '" + verilogInstance.name + "'."); } } } diff --git a/DtdPlugin/src/org/workcraft/plugins/dtd/VisualDtd.java b/DtdPlugin/src/org/workcraft/plugins/dtd/VisualDtd.java index fbffe2452..b01b48317 100644 --- a/DtdPlugin/src/org/workcraft/plugins/dtd/VisualDtd.java +++ b/DtdPlugin/src/org/workcraft/plugins/dtd/VisualDtd.java @@ -395,9 +395,6 @@ public class VisualDtd extends AbstractVisualModel { VisualConnection beforeLevel = null; try { beforeLevel = connect(event, edge); - if (connection instanceof VisualLevelConnection) { - color = ((VisualLevelConnection) connection).getColor(); - } beforeLevel.setColor(color); } catch (InvalidConnectionException e) { } diff --git a/GraphPlugin/src/org/workcraft/plugins/graph/Graph.java b/GraphPlugin/src/org/workcraft/plugins/graph/Graph.java index 88af073f7..6e677169b 100644 --- a/GraphPlugin/src/org/workcraft/plugins/graph/Graph.java +++ b/GraphPlugin/src/org/workcraft/plugins/graph/Graph.java @@ -58,7 +58,7 @@ public class Graph extends AbstractMathModel { if (srcModel == null) { srcModel = this; } - HierarchyReferenceManager refManager = (HierarchyReferenceManager) getReferenceManager(); + HierarchyReferenceManager refManager = getReferenceManager(); NameManager nameManagerer = refManager.getNameManager(null); for (MathNode srcNode: srcChildren) { if (srcNode instanceof Vertex) { diff --git a/StgPlugin/src/org/workcraft/plugins/stg/converters/StgToDtdConverter.java b/StgPlugin/src/org/workcraft/plugins/stg/converters/StgToDtdConverter.java index e010c77d5..9efaeb760 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/converters/StgToDtdConverter.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/converters/StgToDtdConverter.java @@ -7,6 +7,7 @@ import org.workcraft.exceptions.InvalidConnectionException; import org.workcraft.gui.tools.Trace; import org.workcraft.plugins.dtd.*; import org.workcraft.plugins.dtd.VisualDtd.SignalEvent; +import org.workcraft.plugins.dtd.utils.DtdUtils; import org.workcraft.plugins.stg.SignalTransition; import org.workcraft.plugins.stg.Stg; import org.workcraft.types.Pair; @@ -16,6 +17,7 @@ import java.awt.geom.Point2D; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; +import java.util.Set; public class StgToDtdConverter { private static final double SIGNAL_OFFSET = 1.0; @@ -34,6 +36,7 @@ public class StgToDtdConverter { this.stg = stg; this.dtd = (dtd == null) ? new VisualDtd(new Dtd()) : dtd; signalMap = createSignals(signals); + setInitialState(trace); eventMap = ctreateEvents(trace); } @@ -84,12 +87,30 @@ public class StgToDtdConverter { return visualSignal; } + private void setInitialState(Trace trace) { + Set<String> visitedSignals = new HashSet<>(); + for (String transitionRef: trace) { + MathNode node = stg.getNodeByReference(transitionRef); + if (node instanceof SignalTransition) { + SignalTransition transition = (SignalTransition) node; + String signalRef = stg.getSignalReference(transition); + if (visitedSignals.contains(signalRef)) continue; + visitedSignals.add(signalRef); + if (signalMap.containsKey(signalRef)) { + VisualSignal signal = signalMap.get(signalRef); + TransitionEvent.Direction direction = getDirection(transition.getDirection()); + signal.setInitialState(DtdUtils.getPreviousState(direction)); + } + } + } + } + private HashMap<SignalEvent, SignalTransition> ctreateEvents(Trace trace) { HashMap<SignalEvent, SignalTransition> result = new HashMap<>(); HashMap<Node, HashSet<SignalEvent>> causeMap = new HashMap<>(); double x = EVENT_OFFSET; for (String transitionRef: trace) { - MathNode node = (MathNode) stg.getNodeByReference(transitionRef); + MathNode node = stg.getNodeByReference(transitionRef); if (node == null) continue; boolean skip = true; if (node instanceof SignalTransition) {
['DtdPlugin/src/org/workcraft/plugins/dtd/VisualDtd.java', 'StgPlugin/src/org/workcraft/plugins/stg/converters/StgToDtdConverter.java', 'GraphPlugin/src/org/workcraft/plugins/graph/Graph.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java']
{'.java': 4}
4
4
0
0
4
5,665,871
1,150,764
156,229
1,559
1,739
303
31
4
123
21
26
1
0
0
"1970-01-01T00:26:00"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
759
workcraft/workcraft/896/884
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/884
https://github.com/workcraft/workcraft/pull/896
https://github.com/workcraft/workcraft/pull/896
1
fixes
Signal type consistency across waveforms
When creating a new signal in a waveform that coincides with an existing signal in another waveform, the type might be inconsistent. This also happens when renaming a signal into a previously existing signal. Additionally, renaming a signal should rename any guards that reference it.
4ad049ebbe9f28686c5b9f1dca5eddad510cd3ce
f4aea0f5d58b1737e442c4ae11b322c4c752f269
https://github.com/workcraft/workcraft/compare/4ad049ebbe9f28686c5b9f1dca5eddad510cd3ce...f4aea0f5d58b1737e442c4ae11b322c4c752f269
diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgInputPropernessVerificationCommand.java b/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgInputPropernessVerificationCommand.java index 80ec9f4c4..cac82011b 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgInputPropernessVerificationCommand.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgInputPropernessVerificationCommand.java @@ -24,11 +24,11 @@ public class WtgInputPropernessVerificationCommand extends AbstractVerificationC @Override public Boolean execute(WorkspaceEntry we) { final Wtg wtg = WorkspaceUtils.getAs(we, Wtg.class); - if (VerificationUtils.checkInputProperness(wtg)) { + boolean result = VerificationUtils.checkInputProperness(wtg); + if (result) { DialogUtils.showInfo("The model is input proper.", TITLE); - return true; } - return false; + return result; } } \\ No newline at end of file diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgReachabilityVerificationCommand.java b/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgReachabilityVerificationCommand.java index 477f30c8d..70b2a393b 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgReachabilityVerificationCommand.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgReachabilityVerificationCommand.java @@ -23,11 +23,10 @@ public class WtgReachabilityVerificationCommand extends AbstractVerificationComm @Override public Boolean execute(WorkspaceEntry we) { final Wtg wtg = WorkspaceUtils.getAs(we, Wtg.class); - if (!VerificationUtils.checkReachability(wtg)) { - DialogUtils.showInfo("The model has unreachable nodes/transitions.", TITLE); - return false; + boolean result = VerificationUtils.checkReachability(wtg); + if (result) { + DialogUtils.showInfo("All nodes and transitions are reachable.", TITLE); } - DialogUtils.showInfo("All nodes and transitions are reachable.", TITLE); - return true; + return result; } } diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/properties/SignalNamePropertyDescriptor.java b/WtgPlugin/src/org/workcraft/plugins/wtg/properties/SignalNamePropertyDescriptor.java index 966e3fd30..86c017caf 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/properties/SignalNamePropertyDescriptor.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/properties/SignalNamePropertyDescriptor.java @@ -3,11 +3,14 @@ package org.workcraft.plugins.wtg.properties; import org.workcraft.gui.propertyeditor.PropertyDescriptor; import org.workcraft.observation.PropertyChangedEvent; import org.workcraft.plugins.dtd.Signal; +import org.workcraft.plugins.wtg.Guard; +import org.workcraft.plugins.wtg.Waveform; import org.workcraft.plugins.wtg.Wtg; import java.util.Map; public class SignalNamePropertyDescriptor implements PropertyDescriptor { + private final Wtg wtg; private final String signalName; @@ -49,7 +52,16 @@ public class SignalNamePropertyDescriptor implements PropertyDescriptor { wtg.setName(signal, (String) value); signal.sendNotification(new PropertyChangedEvent(signal, Signal.PROPERTY_NAME)); } - + for (Waveform waveform : wtg.getWaveforms()) { + Guard guard = waveform.getGuard(); + if (!guard.containsKey(signalName)) continue; + Guard newGuard = new Guard(); + for (Map.Entry<String, Boolean> entry : guard.entrySet()) { + String key = signalName.equals(entry.getKey()) ? (String) value : entry.getKey(); + newGuard.put(key, entry.getValue()); + } + waveform.setGuard(newGuard); + } } } diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/supervisors/SignalTypeConsistencySupervisor.java b/WtgPlugin/src/org/workcraft/plugins/wtg/supervisors/SignalTypeConsistencySupervisor.java index 814d3beca..40b9f9127 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/supervisors/SignalTypeConsistencySupervisor.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/supervisors/SignalTypeConsistencySupervisor.java @@ -7,6 +7,7 @@ import org.workcraft.plugins.dtd.Signal; import org.workcraft.plugins.wtg.Wtg; public class SignalTypeConsistencySupervisor extends StateSupervisor { + private final Wtg wtg; public SignalTypeConsistencySupervisor(Wtg wtg) { @@ -18,13 +19,30 @@ public class SignalTypeConsistencySupervisor extends StateSupervisor { if (e instanceof PropertyChangedEvent) { PropertyChangedEvent pce = (PropertyChangedEvent) e; String propertyName = pce.getPropertyName(); + if (propertyName.equals(Signal.PROPERTY_NAME)) { + updateThisSignalType((Signal) e.getSender()); + } if (propertyName.equals(Signal.PROPERTY_TYPE)) { - updateSignalType((Signal) e.getSender()); + updateOtherSignalType((Signal) e.getSender()); + } + } + } + + private void updateThisSignalType(Signal signal) { + String signalName = wtg.getName(signal); + if (signalName == null) { + return; + } + for (Signal otherSignal : wtg.getSignals()) { + if (signal == otherSignal) continue; + if (signalName.equals(wtg.getName(otherSignal))) { + signal.setType(otherSignal.getType()); + break; } } } - private void updateSignalType(Signal signal) { + private void updateOtherSignalType(Signal signal) { String signalName = wtg.getName(signal); if (signalName == null) { return; diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/utils/VerificationUtils.java b/WtgPlugin/src/org/workcraft/plugins/wtg/utils/VerificationUtils.java index 8485119dc..c94862149 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/utils/VerificationUtils.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/utils/VerificationUtils.java @@ -8,11 +8,12 @@ import org.workcraft.plugins.wtg.State; import org.workcraft.plugins.wtg.Waveform; import org.workcraft.plugins.wtg.Wtg; import org.workcraft.util.DialogUtils; +import org.workcraft.util.LogUtils; import java.util.*; -import static org.workcraft.plugins.wtg.utils.WtgUtils.*; import static org.workcraft.plugins.wtg.converter.WtgToStgConverter.*; +import static org.workcraft.plugins.wtg.utils.WtgUtils.*; public class VerificationUtils { @@ -526,7 +527,6 @@ public class VerificationUtils { public static boolean checkNodeReachability(Wtg wtg) { Set<Node> reachableNodes = new HashSet<>(); State initialState = wtg.getInitialState(); - int nonReachableNodes = wtg.getWaveforms().size() + wtg.getStates().size() - 1; Queue<Node> nodesToVisit = new LinkedList<>(); nodesToVisit.add(initialState); reachableNodes.add(initialState); @@ -537,25 +537,21 @@ public class VerificationUtils { if (!reachableNodes.contains(n)) { reachableNodes.add(n); nodesToVisit.add(n); - nonReachableNodes = nonReachableNodes - 1; } } } - - if (nonReachableNodes > 0) { - //Error handling - String msg = "The following nodes are unreachable:\\n"; - for (Waveform waveform : wtg.getWaveforms()) { - if (!reachableNodes.contains(waveform)) { - msg = msg.concat(" " + wtg.getName(waveform) + "\\n"); - } - } - for (State state : wtg.getStates()) { - if (!reachableNodes.contains(state)) { - msg = msg.concat(" " + wtg.getName(state) + "\\n"); - } - } - DialogUtils.showError(msg); + //Error handling + List<String> unreachableNodeNames = new ArrayList<>(); + for (Waveform waveform : wtg.getWaveforms()) { + if (reachableNodes.contains(waveform)) continue; + unreachableNodeNames.add(wtg.getName(waveform)); + } + for (State state : wtg.getStates()) { + if (reachableNodes.contains(state)) continue; + unreachableNodeNames.add(wtg.getName(state)); + } + if (!unreachableNodeNames.isEmpty()) { + DialogUtils.showError(LogUtils.getTextWithRefs("Unreachable node", unreachableNodeNames)); return false; } return true; diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/utils/WtgUtils.java b/WtgPlugin/src/org/workcraft/plugins/wtg/utils/WtgUtils.java index f077ac119..0fffe1171 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/utils/WtgUtils.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/utils/WtgUtils.java @@ -138,4 +138,5 @@ public class WtgUtils { } return null; } + }
['WtgPlugin/src/org/workcraft/plugins/wtg/supervisors/SignalTypeConsistencySupervisor.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/utils/VerificationUtils.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/properties/SignalNamePropertyDescriptor.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgReachabilityVerificationCommand.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/utils/WtgUtils.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/commands/WtgInputPropernessVerificationCommand.java']
{'.java': 6}
6
6
0
0
6
5,524,721
1,124,663
153,922
1,554
3,706
733
84
6
287
45
51
3
0
0
"1970-01-01T00:25:37"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
761
workcraft/workcraft/681/215
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/215
https://github.com/workcraft/workcraft/pull/681
https://github.com/workcraft/workcraft/pull/681
1
fixes
Name of a transformed STG work remains the same
To reproduce: 1. Create an STG work with a basic non-dedalock specification, e.g. p0->out- -> out+ ->p0 and p0 marked. 2. Save it as a.work 3. Do Tools->Convert->Net synthesis [Petrify] Observed behaviour: The produced STG is named "a" (without ".work", but still confusing) Expected behaviour: Add a numerical suffix to distinguish this new work, e.g. "a 1" Note, if the new work "a" is transformed again, then the result is called "a 1" as expected. So, the problem only appears when transforming the original "a.work". --- This issue was imported from Launchpad bug. - date created: 2015-02-28T23:07:06Z - owner: danilovesky - assignee: danilovesky - the launchpad url was https://bugs.launchpad.net/bugs/1426786
5a936c12f136883fb963d04b2c123717c618bbc6
54c787f028441a1e73b062c224c3139e887eec32
https://github.com/workcraft/workcraft/compare/5a936c12f136883fb963d04b2c123717c618bbc6...54c787f028441a1e73b062c224c3139e887eec32
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java index 5190aa60d..854908f72 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java @@ -515,20 +515,22 @@ public class CircuitToStgConverter { Hierarchy.getChildrenOfType(stg.getRoot(), VisualComponent.class)); movedComponents.removeAll(unmovedPlaces); movedComponents.removeAll(unmovedTransition); - Rectangle2D bb = BoundingBoxHelper.mergeBoundingBoxes((Collection) movedComponents); - double xPlace = bb.getCenterX() - SCALE_X * 0.5 * unmovedPlaces.size(); - double yPlace = bb.getMinY() - 2.0 * SCALE_Y; - for (VisualComponent component: unmovedPlaces) { - Point2D pos = new Point2D.Double(xPlace, yPlace); - component.setPosition(pos); - xPlace += SCALE_X; - } - double xTransition = bb.getCenterX() - SCALE_X * 0.5 * unmovedTransition.size(); - double yTransition = bb.getMinY() - SCALE_Y; - for (VisualComponent component: unmovedTransition) { - Point2D pos = new Point2D.Double(xTransition, yTransition); - component.setPosition(pos); - xTransition += SCALE_X; + if (!movedComponents.isEmpty()) { + Rectangle2D bb = BoundingBoxHelper.mergeBoundingBoxes((Collection) movedComponents); + double xPlace = bb.getCenterX() - SCALE_X * 0.5 * unmovedPlaces.size(); + double yPlace = bb.getMinY() - 2.0 * SCALE_Y; + for (VisualComponent component: unmovedPlaces) { + Point2D pos = new Point2D.Double(xPlace, yPlace); + component.setPosition(pos); + xPlace += SCALE_X; + } + double xTransition = bb.getCenterX() - SCALE_X * 0.5 * unmovedTransition.size(); + double yTransition = bb.getMinY() - SCALE_Y; + for (VisualComponent component: unmovedTransition) { + Point2D pos = new Point2D.Double(xTransition, yTransition); + component.setPosition(pos); + xTransition += SCALE_X; + } } } diff --git a/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java b/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java index 4980c4eb6..d9b0a6d77 100644 --- a/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java +++ b/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java @@ -1,6 +1,5 @@ package org.workcraft.plugins.cpog.tasks; -import java.io.File; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; @@ -21,7 +20,6 @@ import org.workcraft.plugins.shared.tasks.ExternalProcessResult; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -32,21 +30,21 @@ public class PGMinerResultHandler extends DummyProgressMonitor<ExternalProcessRe private final boolean createNewWindow; private WorkspaceEntry weResult; - public PGMinerResultHandler(VisualCpog visualCpog, WorkspaceEntry we, boolean createNewWindow) { + public PGMinerResultHandler(final VisualCpog visualCpog, final WorkspaceEntry we, final boolean createNewWindow) { this.visualCpog = visualCpog; this.we = we; this.createNewWindow = createNewWindow; this.weResult = null; } - public void finished(final Result<? extends ExternalProcessResult> result, String description) { + public void finished(final Result<? extends ExternalProcessResult> result, final String description) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { final Framework framework = Framework.getInstance(); - MainWindow mainWindow = framework.getMainWindow(); + final MainWindow mainWindow = framework.getMainWindow(); final GraphEditorPanel editor = framework.getMainWindow().getCurrentEditor(); final ToolboxPanel toolbox = editor.getToolBox(); final CpogSelectionTool tool = toolbox.getToolInstance(CpogSelectionTool.class); @@ -55,35 +53,33 @@ public class PGMinerResultHandler extends DummyProgressMonitor<ExternalProcessRe "Concurrency extraction failed", JOptionPane.ERROR_MESSAGE); } else { if (createNewWindow) { - CpogDescriptor cpogModel = new CpogDescriptor(); - MathModel mathModel = cpogModel.createMathModel(); - Path<String> path = we.getWorkspacePath(); - VisualModelDescriptor v = cpogModel.getVisualModelDescriptor(); + final CpogDescriptor cpogModel = new CpogDescriptor(); + final MathModel mathModel = cpogModel.createMathModel(); + final VisualModelDescriptor v = cpogModel.getVisualModelDescriptor(); try { if (v == null) { throw new VisualModelInstantiationException( "visual model is not defined for '" + cpogModel.getDisplayName() + "'."); } visualCpog = (VisualCpog) v.create(mathModel); - final Path<String> directory = we.getWorkspacePath().getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); final ModelEntry me = new ModelEntry(cpogModel, visualCpog); - weResult = framework.createWork(me, directory, name); - } catch (VisualModelInstantiationException e) { + final Path<String> path = we.getWorkspacePath(); + weResult = framework.createWork(me, path); + } catch (final VisualModelInstantiationException e) { e.printStackTrace(); } } - String[] output = new String(result.getReturnValue().getOutput()).split("\\n"); + final String[] output = new String(result.getReturnValue().getOutput()).split("\\n"); we.captureMemento(); try { for (int i = 0; i < output.length; i++) { - String exp = output[i]; + final String exp = output[i]; tool.insertExpression(exp, visualCpog, false, false, true, false); } we.saveMemento(); - } catch (Exception e) { + } catch (final Exception e) { we.cancelMemento(); } } diff --git a/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoResultHandler.java b/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoResultHandler.java index 59eebd865..f8e7bc327 100644 --- a/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoResultHandler.java +++ b/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoResultHandler.java @@ -43,25 +43,22 @@ public class ScencoResultHandler extends DummyProgressMonitor<ScencoResult> { String resultDirectory = result.getReturnValue().getResultDirectory(); solver.handleResult(stdoutLines, resultDirectory); - // import verilog file into circuit + // Import Verilog file into circuit if (solver.isVerilog()) { try { byte[] verilogBytes = solver.getVerilog(); - ByteArrayInputStream in = new ByteArrayInputStream(verilogBytes); - VerilogImporter verilogImporter = new VerilogImporter(false); + final ByteArrayInputStream in = new ByteArrayInputStream(verilogBytes); + final VerilogImporter verilogImporter = new VerilogImporter(false); final Circuit circuit = verilogImporter.importCircuit(in); - Path<String> path = we.getWorkspacePath(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); final ModelEntry me = new ModelEntry(new CircuitDescriptor(), circuit); - + final Path<String> path = we.getWorkspacePath(); final Framework framework = Framework.getInstance(); final MainWindow mainWindow = framework.getMainWindow(); - WorkspaceEntry weCircuit = framework.createWork(me, directory, name); - VisualModel visualModel = weCircuit.getModelEntry().getVisualModel(); + final WorkspaceEntry weCircuit = framework.createWork(me, path); + final VisualModel visualModel = weCircuit.getModelEntry().getVisualModel(); if (visualModel instanceof VisualCircuit) { - VisualCircuit visualCircuit = (VisualCircuit) visualModel; - String title = we.getModelEntry().getModel().getTitle(); + final VisualCircuit visualCircuit = (VisualCircuit) visualModel; + final String title = we.getModelEntry().getModel().getTitle(); visualCircuit.setTitle(title); SwingUtilities.invokeLater(new Runnable() { @Override @@ -75,19 +72,19 @@ public class ScencoResultHandler extends DummyProgressMonitor<ScencoResult> { } } } else if (result.getOutcome() == Outcome.FAILED) { - String errorMessage = getErrorMessage(result.getReturnValue()); + final String errorMessage = getErrorMessage(result.getReturnValue()); final Framework framework = Framework.getInstance(); // In case of an internal error, activate automatically verbose mode if (errorMessage.equals(INTERNAL_ERROR_MSG)) { - String[] sentence = result.getReturnValue().getStdout().split("\\n"); + final String[] sentence = result.getReturnValue().getStdout().split("\\n"); for (int i = 0; i < sentence.length; i++) { System.out.println(sentence[i]); } } //Removing temporary files - File dir = solver.getDirectory(); + final File dir = solver.getDirectory(); FileUtils.deleteOnExitRecursively(dir); //Display the error diff --git a/FstPlugin/src/org/workcraft/plugins/fst/tasks/PetriToFsmConversionResultHandler.java b/FstPlugin/src/org/workcraft/plugins/fst/tasks/PetriToFsmConversionResultHandler.java index c4fa16e80..d44f2eb42 100644 --- a/FstPlugin/src/org/workcraft/plugins/fst/tasks/PetriToFsmConversionResultHandler.java +++ b/FstPlugin/src/org/workcraft/plugins/fst/tasks/PetriToFsmConversionResultHandler.java @@ -1,7 +1,5 @@ package org.workcraft.plugins.fst.tasks; -import java.io.File; - import javax.swing.JOptionPane; import org.workcraft.Framework; @@ -18,7 +16,6 @@ import org.workcraft.plugins.shared.tasks.ExternalProcessResult; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -26,30 +23,26 @@ public class PetriToFsmConversionResultHandler extends DummyProgressMonitor<Writ private final WriteSgConversionTask task; private WorkspaceEntry result; - public PetriToFsmConversionResultHandler(WriteSgConversionTask task) { + public PetriToFsmConversionResultHandler(final WriteSgConversionTask task) { this.task = task; this.result = null; } @Override - public void finished(final Result<? extends WriteSgConversionResult> result, String description) { + public void finished(final Result<? extends WriteSgConversionResult> result, final String description) { final Framework framework = Framework.getInstance(); - WorkspaceEntry we = task.getWorkspaceEntry(); - Path<String> path = we.getWorkspacePath(); if (result.getOutcome() == Outcome.FINISHED) { final VisualFst fst = new VisualFst(result.getReturnValue().getConversionResult()); final VisualFsm fsm = new VisualFsm(new Fsm()); final FstToFsmConverter converter = new FstToFsmConverter(fst, fsm); - - MathModel model = converter.getDstModel().getMathModel(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); + final MathModel model = converter.getDstModel().getMathModel(); final ModelEntry me = new ModelEntry(new FsmDescriptor(), model); - this.result = framework.createWork(me, directory, name); + final Path<String> path = task.getWorkspaceEntry().getWorkspacePath(); + this.result = framework.createWork(me, path); } else if (result.getOutcome() != Outcome.CANCELLED) { - MainWindow mainWindow = framework.getMainWindow(); + final MainWindow mainWindow = framework.getMainWindow(); if (result.getCause() == null) { - Result<? extends ExternalProcessResult> writeSgResult = result.getReturnValue().getResult(); + final Result<? extends ExternalProcessResult> writeSgResult = result.getReturnValue().getResult(); JOptionPane.showMessageDialog(mainWindow, "Petrify output:\\n" + writeSgResult.getReturnValue().getErrorsHeadAndTail(), "Conversion failed", JOptionPane.WARNING_MESSAGE); diff --git a/FstPlugin/src/org/workcraft/plugins/fst/tasks/StgToFstConversionResultHandler.java b/FstPlugin/src/org/workcraft/plugins/fst/tasks/StgToFstConversionResultHandler.java index 1d243831f..e252a1129 100644 --- a/FstPlugin/src/org/workcraft/plugins/fst/tasks/StgToFstConversionResultHandler.java +++ b/FstPlugin/src/org/workcraft/plugins/fst/tasks/StgToFstConversionResultHandler.java @@ -1,7 +1,6 @@ package org.workcraft.plugins.fst.tasks; import java.awt.Color; -import java.io.File; import java.util.HashMap; import javax.swing.JOptionPane; @@ -21,7 +20,6 @@ import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; import org.workcraft.util.ColorGenerator; import org.workcraft.util.ColorUtils; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -34,30 +32,27 @@ public class StgToFstConversionResultHandler extends DummyProgressMonitor<WriteS private final WriteSgConversionTask task; private WorkspaceEntry result; - public StgToFstConversionResultHandler(WriteSgConversionTask task) { + public StgToFstConversionResultHandler(final WriteSgConversionTask task) { this.task = task; this.result = null; } @Override - public void finished(final Result<? extends WriteSgConversionResult> result, String description) { + public void finished(final Result<? extends WriteSgConversionResult> result, final String description) { final Framework framework = Framework.getInstance(); - WorkspaceEntry we = task.getWorkspaceEntry(); - Path<String> path = we.getWorkspacePath(); if (result.getOutcome() == Outcome.FINISHED) { - Fst model = result.getReturnValue().getConversionResult(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); + final Fst model = result.getReturnValue().getConversionResult(); final ModelEntry me = new ModelEntry(new FstDescriptor(), model); - this.result = framework.createWork(me, directory, name); - VisualModel visualModel = me.getVisualModel(); + final Path<String> path = task.getWorkspaceEntry().getWorkspacePath(); + this.result = framework.createWork(me, path); + final VisualModel visualModel = me.getVisualModel(); if (visualModel instanceof VisualFst) { highlightCscConflicts((VisualFst) visualModel); } } else if (result.getOutcome() != Outcome.CANCELLED) { - MainWindow mainWindow = framework.getMainWindow(); + final MainWindow mainWindow = framework.getMainWindow(); if (result.getCause() == null) { - Result<? extends ExternalProcessResult> petrifyResult = result.getReturnValue().getResult(); + final Result<? extends ExternalProcessResult> petrifyResult = result.getReturnValue().getResult(); JOptionPane.showMessageDialog(mainWindow, "Petrify output:\\n" + petrifyResult.getReturnValue().getErrorsHeadAndTail(), "Conversion failed", JOptionPane.WARNING_MESSAGE); @@ -67,13 +62,13 @@ public class StgToFstConversionResultHandler extends DummyProgressMonitor<WriteS } } - protected void highlightCscConflicts(VisualFst visualFst) { - HashMap<String, Color> codeToColorMap = new HashMap<>(); - for (VisualState state: visualFst.getVisualStates()) { - String name = visualFst.getMathName(state); + protected void highlightCscConflicts(final VisualFst visualFst) { + final HashMap<String, Color> codeToColorMap = new HashMap<>(); + for (final VisualState state: visualFst.getVisualStates()) { + final String name = visualFst.getMathName(state); if (name.endsWith("_csc")) { String code = null; - String[] nameParts = name.split("_"); + final String[] nameParts = name.split("_"); if (nameParts.length == 3) { code = name.split("_")[1]; } diff --git a/MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisResultHandler.java b/MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisResultHandler.java index e968ef568..85edde81f 100644 --- a/MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisResultHandler.java +++ b/MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisResultHandler.java @@ -1,7 +1,6 @@ package org.workcraft.plugins.mpsat.tasks; import java.io.ByteArrayInputStream; -import java.io.File; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; @@ -24,7 +23,6 @@ import org.workcraft.plugins.shared.tasks.ExternalProcessResult; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; -import org.workcraft.util.FileUtils; import org.workcraft.util.LogUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -35,13 +33,13 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth private final MpsatSynthesisChainTask task; private WorkspaceEntry result; - public MpsatSynthesisResultHandler(MpsatSynthesisChainTask task) { + public MpsatSynthesisResultHandler(final MpsatSynthesisChainTask task) { this.task = task; this.result = null; } @Override - public void finished(final Result<? extends MpsatSynthesisChainResult> result, String description) { + public void finished(final Result<? extends MpsatSynthesisChainResult> result, final String description) { switch (result.getOutcome()) { case FINISHED: handleSuccess(result); @@ -55,9 +53,9 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth } private void handleSuccess(final Result<? extends MpsatSynthesisChainResult> result) { - MpsatSynthesisChainResult returnValue = result.getReturnValue(); + final MpsatSynthesisChainResult returnValue = result.getReturnValue(); final MpsatSynthesisMode mpsatMode = returnValue.getMpsatSettings().getMode(); - ExternalProcessResult mpsatReturnValue = returnValue.getMpsatResult().getReturnValue(); + final ExternalProcessResult mpsatReturnValue = returnValue.getMpsatResult().getReturnValue(); switch (mpsatMode) { case COMPLEX_GATE_IMPLEMENTATION: handleSynthesisResult(mpsatReturnValue, false, RenderType.GATE); @@ -72,7 +70,7 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth handleSynthesisResult(mpsatReturnValue, false, RenderType.GATE); break; default: - MainWindow mainWindow = Framework.getInstance().getMainWindow(); + final MainWindow mainWindow = Framework.getInstance().getMainWindow(); JOptionPane.showMessageDialog(mainWindow, "Warning: MPSat synthesis mode \\'" + mpsatMode.getArgument() + "\\' is not (yet) supported.", TITLE, JOptionPane.WARNING_MESSAGE); @@ -80,19 +78,19 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth } } - private void handleSynthesisResult(ExternalProcessResult mpsatResult, boolean sequentialAssign, RenderType renderType) { + private void handleSynthesisResult(final ExternalProcessResult mpsatResult, final boolean sequentialAssign, final RenderType renderType) { final String log = new String(mpsatResult.getOutput()); if ((log != null) && !log.isEmpty()) { System.out.println(log); System.out.println(); } - byte[] eqnOutput = mpsatResult.getFileData(MpsatSynthesisTask.EQN_FILE_NAME); + final byte[] eqnOutput = mpsatResult.getFileData(MpsatSynthesisTask.EQN_FILE_NAME); if (eqnOutput != null) { LogUtils.logInfoLine("MPSat synthesis result in EQN format:"); System.out.println(new String(eqnOutput)); System.out.println(); } - byte[] verilogOutput = mpsatResult.getFileData(MpsatSynthesisTask.VERILOG_FILE_NAME); + final byte[] verilogOutput = mpsatResult.getFileData(MpsatSynthesisTask.VERILOG_FILE_NAME); if (verilogOutput != null) { LogUtils.logInfoLine("MPSat synthesis result in Verilog format:"); System.out.println(new String(verilogOutput)); @@ -100,24 +98,21 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth } if (MpsatSynthesisSettings.getOpenSynthesisResult() && (verilogOutput != null)) { try { - ByteArrayInputStream in = new ByteArrayInputStream(verilogOutput); - VerilogImporter verilogImporter = new VerilogImporter(sequentialAssign); + final Framework framework = Framework.getInstance(); + final ByteArrayInputStream in = new ByteArrayInputStream(verilogOutput); + final VerilogImporter verilogImporter = new VerilogImporter(sequentialAssign); final Circuit circuit = verilogImporter.importCircuit(in); - final WorkspaceEntry we = task.getWorkspaceEntry(); - Path<String> path = we.getWorkspacePath(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); final ModelEntry me = new ModelEntry(new CircuitDescriptor(), circuit); - - final Framework framework = Framework.getInstance(); - result = framework.createWork(me, directory, name); - VisualModel visualModel = result.getModelEntry().getVisualModel(); + final WorkspaceEntry we = task.getWorkspaceEntry(); + final Path<String> path = we.getWorkspacePath(); + result = framework.createWork(me, path); + final VisualModel visualModel = result.getModelEntry().getVisualModel(); if (visualModel instanceof VisualCircuit) { - VisualCircuit visualCircuit = (VisualCircuit) visualModel; - for (VisualFunctionComponent component: visualCircuit.getVisualFunctionComponents()) { + final VisualCircuit visualCircuit = (VisualCircuit) visualModel; + for (final VisualFunctionComponent component: visualCircuit.getVisualFunctionComponents()) { component.setRenderType(renderType); } - String title = we.getModelEntry().getModel().getTitle(); + final String title = we.getModelEntry().getModel().getTitle(); visualCircuit.setTitle(title); if (!we.getFile().exists()) { JOptionPane.showMessageDialog(null, @@ -142,7 +137,7 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth } }); } - } catch (DeserialisationException e) { + } catch (final DeserialisationException e) { throw new RuntimeException(e); } } @@ -150,42 +145,42 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth private void handleFailure(final Result<? extends MpsatSynthesisChainResult> result) { String errorMessage = "Error: MPSat synthesis failed."; - Throwable genericCause = result.getCause(); + final Throwable genericCause = result.getCause(); if (genericCause != null) { // Exception was thrown somewhere in the chain task run() method (not in any of the subtasks) errorMessage += ERROR_CAUSE_PREFIX + genericCause.toString(); } else { - MpsatSynthesisChainResult returnValue = result.getReturnValue(); - Result<? extends Object> exportResult = (returnValue == null) ? null : returnValue.getExportResult(); - Result<? extends ExternalProcessResult> punfResult = (returnValue == null) ? null : returnValue.getPunfResult(); - Result<? extends ExternalProcessResult> mpsatResult = (returnValue == null) ? null : returnValue.getMpsatResult(); + final MpsatSynthesisChainResult returnValue = result.getReturnValue(); + final Result<? extends Object> exportResult = (returnValue == null) ? null : returnValue.getExportResult(); + final Result<? extends ExternalProcessResult> punfResult = (returnValue == null) ? null : returnValue.getPunfResult(); + final Result<? extends ExternalProcessResult> mpsatResult = (returnValue == null) ? null : returnValue.getMpsatResult(); if ((exportResult != null) && (exportResult.getOutcome() == Outcome.FAILED)) { errorMessage += "\\n\\nCould not export the model as a .g file."; - Throwable exportCause = exportResult.getCause(); + final Throwable exportCause = exportResult.getCause(); if (exportCause != null) { errorMessage += ERROR_CAUSE_PREFIX + exportCause.toString(); } } else if ((punfResult != null) && (punfResult.getOutcome() == Outcome.FAILED)) { errorMessage += "\\n\\nPunf could not build the unfolding prefix."; - Throwable punfCause = punfResult.getCause(); + final Throwable punfCause = punfResult.getCause(); if (punfCause != null) { errorMessage += ERROR_CAUSE_PREFIX + punfCause.toString(); } else { - ExternalProcessResult punfReturnValue = punfResult.getReturnValue(); + final ExternalProcessResult punfReturnValue = punfResult.getReturnValue(); if (punfReturnValue != null) { - String punfError = punfReturnValue.getErrorsHeadAndTail(); + final String punfError = punfReturnValue.getErrorsHeadAndTail(); errorMessage += ERROR_CAUSE_PREFIX + punfError; } } } else if ((mpsatResult != null) && (mpsatResult.getOutcome() == Outcome.FAILED)) { errorMessage += "\\n\\nMPSat did not execute as expected."; - Throwable mpsatCause = mpsatResult.getCause(); + final Throwable mpsatCause = mpsatResult.getCause(); if (mpsatCause != null) { errorMessage += ERROR_CAUSE_PREFIX + mpsatCause.toString(); } else { - ExternalProcessResult mpsatReturnValue = mpsatResult.getReturnValue(); + final ExternalProcessResult mpsatReturnValue = mpsatResult.getReturnValue(); if (mpsatReturnValue != null) { - String mpsatError = mpsatReturnValue.getErrorsHeadAndTail(); + final String mpsatError = mpsatReturnValue.getErrorsHeadAndTail(); errorMessage += ERROR_CAUSE_PREFIX + mpsatError; } } @@ -193,7 +188,7 @@ public class MpsatSynthesisResultHandler extends DummyProgressMonitor<MpsatSynth errorMessage += "\\n\\nMPSat chain task returned failure status without further explanation."; } } - MainWindow mainWindow = Framework.getInstance().getMainWindow(); + final MainWindow mainWindow = Framework.getInstance().getMainWindow(); JOptionPane.showMessageDialog(mainWindow, errorMessage, TITLE, JOptionPane.ERROR_MESSAGE); } diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/MpsatCscConflictResolutionResultHandler.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/MpsatCscConflictResolutionResultHandler.java index 226ba1aab..6638e4a29 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/MpsatCscConflictResolutionResultHandler.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/MpsatCscConflictResolutionResultHandler.java @@ -1,7 +1,6 @@ package org.workcraft.plugins.mpsat; import java.io.ByteArrayInputStream; -import java.io.File; import javax.swing.JOptionPane; @@ -14,7 +13,6 @@ import org.workcraft.plugins.stg.StgDescriptor; import org.workcraft.plugins.stg.StgModel; import org.workcraft.plugins.stg.interop.DotGImporter; import org.workcraft.tasks.Result; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -24,7 +22,7 @@ public class MpsatCscConflictResolutionResultHandler implements Runnable { private final Result<? extends ExternalProcessResult> result; private WorkspaceEntry weResult; - public MpsatCscConflictResolutionResultHandler(WorkspaceEntry we, Result<? extends ExternalProcessResult> result) { + public MpsatCscConflictResolutionResultHandler(final WorkspaceEntry we, final Result<? extends ExternalProcessResult> result) { this.we = we; this.result = result; this.weResult = null; @@ -37,7 +35,7 @@ public class MpsatCscConflictResolutionResultHandler implements Runnable { } try { return new DotGImporter().importSTG(new ByteArrayInputStream(content)); - } catch (DeserialisationException e) { + } catch (final DeserialisationException e) { throw new RuntimeException(e); } } @@ -45,20 +43,16 @@ public class MpsatCscConflictResolutionResultHandler implements Runnable { @Override public void run() { final Framework framework = Framework.getInstance(); - Path<String> path = we.getWorkspacePath(); - String fileName = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); - - StgModel model = getResolvedStg(); + final StgModel model = getResolvedStg(); if (model == null) { - String errorMessage = result.getReturnValue().getErrorsHeadAndTail(); + final String errorMessage = result.getReturnValue().getErrorsHeadAndTail(); JOptionPane.showMessageDialog(framework.getMainWindow(), "MPSat output: \\n" + errorMessage, "Conflict resolution failed", JOptionPane.WARNING_MESSAGE); } else { - Path<String> directory = path.getParent(); - String name = fileName + "_resolved"; - ModelEntry me = new ModelEntry(new StgDescriptor(), model); - weResult = framework.createWork(me, directory, name); + final ModelEntry me = new ModelEntry(new StgDescriptor(), model); + final Path<String> path = we.getWorkspacePath(); + weResult = framework.createWork(me, path); } } diff --git a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifySynthesisResultHandler.java b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifySynthesisResultHandler.java index dac70d8ea..b5d3618ae 100644 --- a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifySynthesisResultHandler.java +++ b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifySynthesisResultHandler.java @@ -1,7 +1,6 @@ package org.workcraft.plugins.petrify.tasks; import java.io.ByteArrayInputStream; -import java.io.File; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; @@ -20,7 +19,6 @@ import org.workcraft.plugins.circuit.renderers.ComponentRenderingResult.RenderTy import org.workcraft.plugins.petrify.PetrifySettings; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; -import org.workcraft.util.FileUtils; import org.workcraft.util.LogUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -34,8 +32,8 @@ public class PetrifySynthesisResultHandler extends DummyProgressMonitor<PetrifyS private final boolean sequentialAssign; private WorkspaceEntry result; - public PetrifySynthesisResultHandler(WorkspaceEntry we, boolean boxSequentialComponents, - boolean boxCombinationalComponents, boolean sequentialAssign) { + public PetrifySynthesisResultHandler(final WorkspaceEntry we, final boolean boxSequentialComponents, + final boolean boxCombinationalComponents, final boolean sequentialAssign) { this.we = we; this.boxSequentialComponents = boxSequentialComponents; this.boxCombinationalComponents = boxCombinationalComponents; @@ -44,7 +42,7 @@ public class PetrifySynthesisResultHandler extends DummyProgressMonitor<PetrifyS } @Override - public void finished(final Result<? extends PetrifySynthesisResult> result, String description) { + public void finished(final Result<? extends PetrifySynthesisResult> result, final String description) { switch (result.getOutcome()) { case FINISHED: handleSuccess(result); @@ -58,39 +56,36 @@ public class PetrifySynthesisResultHandler extends DummyProgressMonitor<PetrifyS } private void handleSuccess(final Result<? extends PetrifySynthesisResult> result) { - String log = result.getReturnValue().getLog(); + final String log = result.getReturnValue().getLog(); if ((log != null) && !log.isEmpty()) { LogUtils.logInfoLine("Petrify synthesis log:"); System.out.println(log); } - String equations = result.getReturnValue().getEquation(); + final String equations = result.getReturnValue().getEquation(); if ((equations != null) && !equations.isEmpty()) { LogUtils.logInfoLine("Petrify synthesis result in EQN format:"); System.out.println(equations); } - String verilog = result.getReturnValue().getVerilog(); + final String verilog = result.getReturnValue().getVerilog(); if (PetrifySettings.getOpenSynthesisResult() && (verilog != null) && !verilog.isEmpty()) { LogUtils.logInfoLine("Petrify synthesis result in Verilog format:"); System.out.println(verilog); try { - ByteArrayInputStream in = new ByteArrayInputStream(verilog.getBytes()); - VerilogImporter verilogImporter = new VerilogImporter(sequentialAssign); + final ByteArrayInputStream in = new ByteArrayInputStream(verilog.getBytes()); + final VerilogImporter verilogImporter = new VerilogImporter(sequentialAssign); final Circuit circuit = verilogImporter.importCircuit(in); - Path<String> path = we.getWorkspacePath(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); + final Path<String> path = we.getWorkspacePath(); final ModelEntry me = new ModelEntry(new CircuitDescriptor(), circuit); - final Framework framework = Framework.getInstance(); final MainWindow mainWindow = framework.getMainWindow(); - this.result = framework.createWork(me, directory, name); - VisualModel visualModel = this.result.getModelEntry().getVisualModel(); + this.result = framework.createWork(me, path); + final VisualModel visualModel = this.result.getModelEntry().getVisualModel(); if (visualModel instanceof VisualCircuit) { - VisualCircuit visualCircuit = (VisualCircuit) visualModel; + final VisualCircuit visualCircuit = (VisualCircuit) visualModel; setComponentsRenderStyle(visualCircuit); - String title = we.getModelEntry().getModel().getTitle(); + final String title = we.getModelEntry().getModel().getTitle(); visualCircuit.setTitle(title); if (!we.getFile().exists()) { JOptionPane.showMessageDialog(mainWindow, @@ -113,14 +108,14 @@ public class PetrifySynthesisResultHandler extends DummyProgressMonitor<PetrifyS } }); } - } catch (DeserialisationException e) { + } catch (final DeserialisationException e) { throw new RuntimeException(e); } } } - private void setComponentsRenderStyle(VisualCircuit visualCircuit) { - for (VisualFunctionComponent component: visualCircuit.getVisualFunctionComponents()) { + private void setComponentsRenderStyle(final VisualCircuit visualCircuit) { + for (final VisualFunctionComponent component: visualCircuit.getVisualFunctionComponents()) { if (component.isSequentialGate()) { if (boxSequentialComponents) { component.setRenderType(RenderType.BOX); @@ -135,11 +130,11 @@ public class PetrifySynthesisResultHandler extends DummyProgressMonitor<PetrifyS private void handleFailure(final Result<? extends PetrifySynthesisResult> result) { String errorMessage = "Error: Petrify synthesis failed."; - PetrifySynthesisResult returnValue = result.getReturnValue(); + final PetrifySynthesisResult returnValue = result.getReturnValue(); if (returnValue != null) { errorMessage += ERROR_CAUSE_PREFIX + returnValue.getStderr(); } - MainWindow mainWindow = Framework.getInstance().getMainWindow(); + final MainWindow mainWindow = Framework.getInstance().getMainWindow(); JOptionPane.showMessageDialog(mainWindow, errorMessage, TITLE, JOptionPane.ERROR_MESSAGE); } diff --git a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifyTransformationResultHandler.java b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifyTransformationResultHandler.java index 312e287d1..114c3da13 100644 --- a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifyTransformationResultHandler.java +++ b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifyTransformationResultHandler.java @@ -1,6 +1,5 @@ package org.workcraft.plugins.petrify.tasks; -import java.io.File; import java.util.HashMap; import javax.swing.JOptionPane; @@ -28,7 +27,6 @@ import org.workcraft.plugins.stg.StgModel; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -50,15 +48,13 @@ public class PetrifyTransformationResultHandler extends DummyProgressMonitor<Pet @Override public void finished(final Result<? extends PetrifyTransformationResult> result, String description) { final Framework framework = Framework.getInstance(); - Path<String> path = we.getWorkspacePath(); if (result.getOutcome() == Outcome.FINISHED) { StgModel stgModel = result.getReturnValue().getResult(); PetriNetModel model = convertResultStgToPetriNet ? stgModel : convertStgToPetriNet(stgModel); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); final ModelDescriptor modelDescriptor = convertResultStgToPetriNet ? new StgDescriptor() : new PetriNetDescriptor(); final ModelEntry me = new ModelEntry(modelDescriptor, model); - this.result = framework.createWork(me, directory, name); + final Path<String> path = we.getWorkspacePath(); + this.result = framework.createWork(me, path); } else if (result.getOutcome() == Outcome.FAILED) { MainWindow mainWindow = framework.getMainWindow(); if (result.getCause() == null) { diff --git a/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java b/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java index 76a189f41..7e4e8c507 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java @@ -60,7 +60,6 @@ import org.workcraft.plugins.stg.converters.StgToDtdConverter; import org.workcraft.util.ColorGenerator; import org.workcraft.util.Pair; import org.workcraft.workspace.ModelEntry; -import org.workcraft.workspace.WorkspaceEntry; public class StgSimulationTool extends PetriSimulationTool { private static final int COLUMN_SIGNAL = 0; @@ -83,7 +82,7 @@ public class StgSimulationTool extends PetriSimulationTool { private final String name; - SignalState(String name) { + SignalState(final String name) { this.name = name; } @@ -110,12 +109,12 @@ public class StgSimulationTool extends PetriSimulationTool { public Boolean visible = true; public Color color = Color.BLACK; - public SignalData(String name, SignalTransition.Type type) { + public SignalData(final String name, final SignalTransition.Type type) { this.name = name; this.type = type; } - public void copy(SignalData signalData) { + public void copy(final SignalData signalData) { if (signalData != null) { value = signalData.value; excited = signalData.excited; @@ -127,7 +126,7 @@ public class StgSimulationTool extends PetriSimulationTool { @SuppressWarnings("serial") private final class StateTable extends JTable { - StateTable(StateTableModel model) { + StateTable(final StateTableModel model) { super(model); getTableHeader().setReorderingAllowed(false); setDragEnabled(true); @@ -143,12 +142,12 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public void editingStopped(ChangeEvent e) { - TableCellEditor cellEditor = getCellEditor(); - String signalName = signals.get(editingRow); + public void editingStopped(final ChangeEvent e) { + final TableCellEditor cellEditor = getCellEditor(); + final String signalName = signals.get(editingRow); if ((cellEditor != null) && (signalName != null)) { - SignalData signalData = signalDataMap.get(signalName); - Object value = cellEditor.getCellEditorValue(); + final SignalData signalData = signalDataMap.get(signalName); + final Object value = cellEditor.getCellEditorValue(); if ((signalData != null) && (value != null)) { switch (editingColumn) { case COLUMN_VISIBILE: @@ -173,7 +172,7 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public String getColumnName(int column) { + public String getColumnName(final int column) { switch (column) { case COLUMN_SIGNAL: return "Signal"; case COLUMN_STATE: return "State"; @@ -184,7 +183,7 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public Class<?> getColumnClass(int col) { + public Class<?> getColumnClass(final int col) { switch (col) { case COLUMN_SIGNAL: return SignalData.class; case COLUMN_STATE: return SignalData.class; @@ -200,10 +199,10 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public Object getValueAt(int row, int col) { + public Object getValueAt(final int row, final int col) { if (row < signalDataMap.size()) { - String signalName = signals.get(row); - SignalData signalData = signalDataMap.get(signalName); + final String signalName = signals.get(row); + final SignalData signalData = signalDataMap.get(signalName); if (signalData != null) { switch (col) { case COLUMN_SIGNAL: return signalData; @@ -218,7 +217,7 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public boolean isCellEditable(int row, int col) { + public boolean isCellEditable(final int row, final int col) { switch (col) { case COLUMN_SIGNAL: return false; case COLUMN_STATE: return false; @@ -228,9 +227,9 @@ public class StgSimulationTool extends PetriSimulationTool { } } - public void reorder(int from, int to) { + public void reorder(final int from, final int to) { if ((from >= 0) && (from < signals.size()) && (to >= 0) && (to < signals.size()) && (from != to)) { - String name = signals.remove(from); + final String name = signals.remove(from); signals.add(to, name); fireTableDataChanged(); } @@ -241,7 +240,7 @@ public class StgSimulationTool extends PetriSimulationTool { @SuppressWarnings("serial") final JLabel label = new JLabel() { @Override - public void paint(Graphics g) { + public void paint(final Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth() - 1, getHeight() - 1); super.paint(g); @@ -249,15 +248,15 @@ public class StgSimulationTool extends PetriSimulationTool { }; @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { + public Component getTableCellRendererComponent(final JTable table, final Object value, + final boolean isSelected, final boolean hasFocus, final int row, final int column) { label.setText(""); label.setBorder(PropertyEditorTable.BORDER_RENDER); label.setForeground(table.getForeground()); label.setBackground(table.getBackground()); label.setFont(table.getFont().deriveFont(Font.PLAIN)); if (isActivated() && (value instanceof SignalData)) { - SignalData st = (SignalData) value; + final SignalData st = (SignalData) value; switch (column) { case COLUMN_SIGNAL: label.setText(st.name); @@ -282,57 +281,57 @@ public class StgSimulationTool extends PetriSimulationTool { private final DataFlavor localObjectFlavor = new ActivationDataFlavor(Integer.class, "Integer Row Index"); private final JTable table; - public StateTableRowTransferHandler(JTable table) { + public StateTableRowTransferHandler(final JTable table) { this.table = table; } @Override - protected Transferable createTransferable(JComponent c) { + protected Transferable createTransferable(final JComponent c) { assert c == table; return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType()); } @Override - public boolean canImport(TransferHandler.TransferSupport info) { - boolean b = (info.getComponent() == table) && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor); + public boolean canImport(final TransferHandler.TransferSupport info) { + final boolean b = (info.getComponent() == table) && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor); table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop); return b; } @Override - public int getSourceActions(JComponent c) { + public int getSourceActions(final JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override - public boolean importData(TransferHandler.TransferSupport info) { - JTable target = (JTable) info.getComponent(); - JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation(); + public boolean importData(final TransferHandler.TransferSupport info) { + final JTable target = (JTable) info.getComponent(); + final JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation(); int rowTo = dl.getRow(); - int max = table.getModel().getRowCount(); + final int max = table.getModel().getRowCount(); if ((rowTo < 0) || (rowTo > max)) { rowTo = max; } target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); try { - Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor); + final Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor); if (rowTo > rowFrom) { rowTo--; } if ((rowFrom != -1) && (rowFrom != rowTo)) { - StateTableModel stateTableModel = (StateTableModel) table.getModel(); + final StateTableModel stateTableModel = (StateTableModel) table.getModel(); stateTableModel.reorder(rowFrom, rowTo); target.getSelectionModel().addSelectionInterval(rowTo, rowTo); return true; } - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); } return false; } @Override - protected void exportDone(JComponent c, Transferable t, int act) { + protected void exportDone(final JComponent c, final Transferable t, final int act) { if ((act == TransferHandler.MOVE) || (act == TransferHandler.NONE)) { table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @@ -344,21 +343,21 @@ public class StgSimulationTool extends PetriSimulationTool { @SuppressWarnings("serial") private final JLabel label = new JLabel() { @Override - public void paint(Graphics g) { + public void paint(final Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth() - 1, getHeight() - 1); super.paint(g); } }; - boolean isActive(int row, int column) { + boolean isActive(final int row, final int column) { if (column == 0) { if (!mainTrace.isEmpty() && branchTrace.isEmpty()) { return row == mainTrace.getPosition(); } } else { - int absoluteBranchSize = mainTrace.getPosition() + branchTrace.size(); - int absoluteBranchPosition = mainTrace.getPosition() + branchTrace.getPosition(); + final int absoluteBranchSize = mainTrace.getPosition() + branchTrace.size(); + final int absoluteBranchPosition = mainTrace.getPosition() + branchTrace.getPosition(); if (!branchTrace.isEmpty() && (row >= mainTrace.getPosition()) && (row < absoluteBranchSize)) { return row == absoluteBranchPosition; } @@ -367,14 +366,14 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { + public Component getTableCellRendererComponent(final JTable table, final Object value, + final boolean isSelected, final boolean hasFocus, final int row, final int column) { JLabel result = null; label.setBorder(PropertyEditorTable.BORDER_RENDER); if (isActivated() && (value instanceof String)) { label.setText(value.toString()); - Node node = getUnderlyingStg().getNodeByReference(value.toString()); - Color color = getNodeColor(node); + final Node node = getUnderlyingStg().getNodeByReference(value.toString()); + final Color color = getNodeColor(node); label.setForeground(color); if (isActive(row, column)) { label.setBackground(table.getSelectionBackground()); @@ -408,7 +407,7 @@ public class StgSimulationTool extends PetriSimulationTool { public void updateSignalState() { initialiseSignalState(); - ArrayList<String> combinedTrace = new ArrayList<>(); + final ArrayList<String> combinedTrace = new ArrayList<>(); if (!mainTrace.isEmpty()) { combinedTrace.addAll(mainTrace.subList(0, mainTrace.getPosition())); } @@ -416,12 +415,12 @@ public class StgSimulationTool extends PetriSimulationTool { combinedTrace.addAll(branchTrace.subList(0, branchTrace.getPosition())); } - for (String ref : combinedTrace) { - Node node = getUnderlyingStg().getNodeByReference(ref); + for (final String ref : combinedTrace) { + final Node node = getUnderlyingStg().getNodeByReference(ref); if (node instanceof SignalTransition) { - SignalTransition transition = (SignalTransition) node; - String signalReference = getUnderlyingStg().getSignalReference(transition); - SignalData signalState = signalDataMap.get(signalReference); + final SignalTransition transition = (SignalTransition) node; + final String signalReference = getUnderlyingStg().getSignalReference(transition); + final SignalData signalState = signalDataMap.get(signalReference); if (signalState != null) { switch (transition.getDirection()) { case MINUS: @@ -440,11 +439,11 @@ public class StgSimulationTool extends PetriSimulationTool { } } - for (Node node: getUnderlyingStg().getTransitions()) { + for (final Node node: getUnderlyingStg().getTransitions()) { if (node instanceof SignalTransition) { - SignalTransition transition = (SignalTransition) node; - String signalReference = getUnderlyingStg().getSignalReference(transition); - SignalData signalData = signalDataMap.get(signalReference); + final SignalTransition transition = (SignalTransition) node; + final String signalReference = getUnderlyingStg().getSignalReference(transition); + final SignalData signalData = signalDataMap.get(signalReference); if (signalData != null) { signalData.excited |= isEnabledNode(transition); } @@ -453,8 +452,8 @@ public class StgSimulationTool extends PetriSimulationTool { } public void initialiseSignalState() { - for (String signalName: signalDataMap.keySet()) { - SignalData signalData = signalDataMap.get(signalName); + for (final String signalName: signalDataMap.keySet()) { + final SignalData signalData = signalDataMap.get(signalName); signalData.value = SignalState.UNDEFINED; signalData.excited = false; } @@ -469,30 +468,27 @@ public class StgSimulationTool extends PetriSimulationTool { @Override public void generateTraceGraph(final GraphEditor editor) { - Framework framework = Framework.getInstance(); - Stg stg = getUnderlyingStg(); - Trace trace = getCombinedTrace(); + final Framework framework = Framework.getInstance(); + final Trace trace = getCombinedTrace(); if (trace.isEmpty()) { JOptionPane.showMessageDialog(framework.getMainWindow(), "Cannot generate a timing diagram for an empty trace.", "Generation of Timing Diagram", JOptionPane.WARNING_MESSAGE); } else { - LinkedList<Pair<String, Color>> visibleSignals = getVisibleSignals(stg); - StgToDtdConverter converter = new StgToDtdConverter(stg, trace, visibleSignals); - VisualDtd dtd = converter.getVisualDtd(); - - WorkspaceEntry we = editor.getWorkspaceEntry(); - final Path<String> directory = we.getWorkspacePath().getParent(); - final String desiredName = we.getWorkspacePath().getNode(); + final Stg stg = getUnderlyingStg(); + final LinkedList<Pair<String, Color>> visibleSignals = getVisibleSignals(stg); + final StgToDtdConverter converter = new StgToDtdConverter(stg, trace, visibleSignals); + final VisualDtd dtd = converter.getVisualDtd(); + final Path<String> path = editor.getWorkspaceEntry().getWorkspacePath(); final ModelEntry me = new ModelEntry(new DtdDescriptor(), dtd); - framework.createWork(me, directory, desiredName); + framework.createWork(me, path); } } - private LinkedList<Pair<String, Color>> getVisibleSignals(Stg stg) { - LinkedList<Pair<String, Color>> result = new LinkedList<>(); - for (String signalRef: signals) { - SignalData signalData = signalDataMap.get(signalRef); + private LinkedList<Pair<String, Color>> getVisibleSignals(final Stg stg) { + final LinkedList<Pair<String, Color>> result = new LinkedList<>(); + for (final String signalRef: signals) { + final SignalData signalData = signalDataMap.get(signalRef); if ((signalData != null) && signalData.visible) { result.add(new Pair<String, Color>(signalData.name, signalData.color)); } @@ -501,13 +497,13 @@ public class StgSimulationTool extends PetriSimulationTool { } @Override - public String getTraceLabelByReference(String ref) { + public String getTraceLabelByReference(final String ref) { String result = null; if (ref != null) { - String name = NamespaceHelper.getReferenceName(ref); - String nameWithoutInstance = LabelParser.getTransitionName(name); + final String name = NamespaceHelper.getReferenceName(ref); + final String nameWithoutInstance = LabelParser.getTransitionName(name); if (nameWithoutInstance != null) { - String path = NamespaceHelper.getReferencePath(ref); + final String path = NamespaceHelper.getReferencePath(ref); result = path + nameWithoutInstance; } } @@ -515,14 +511,14 @@ public class StgSimulationTool extends PetriSimulationTool { } protected void initialiseStateMap() { - Stg stg = getUnderlyingStg(); - HashMap<String, SignalData> newStateMap = new HashMap<>(); - LinkedList<String> allSignals = new LinkedList<>(); - for (Type type: Type.values()) { - Set<String> typedSignals = stg.getSignalReferences(type); + final Stg stg = getUnderlyingStg(); + final HashMap<String, SignalData> newStateMap = new HashMap<>(); + final LinkedList<String> allSignals = new LinkedList<>(); + for (final Type type: Type.values()) { + final Set<String> typedSignals = stg.getSignalReferences(type); allSignals.addAll(typedSignals); - for (String signal: typedSignals) { - SignalData signalData = new SignalData(signal, type); + for (final String signal: typedSignals) { + final SignalData signalData = new SignalData(signal, type); signalData.copy(signalDataMap.get(signal)); signalData.visible = type != Type.INTERNAL; newStateMap.put(signal, signalData); @@ -536,15 +532,15 @@ public class StgSimulationTool extends PetriSimulationTool { updateSignalState(); } - private Color getNodeColor(Node node) { + private Color getNodeColor(final Node node) { if (node instanceof SignalTransition) { - SignalTransition transition = (SignalTransition) node; + final SignalTransition transition = (SignalTransition) node; return getTypeColor(transition.getSignalType()); } return Color.BLACK; } - private Color getTypeColor(SignalTransition.Type type) { + private Color getTypeColor(final SignalTransition.Type type) { switch (type) { case INPUT: return CommonSignalSettings.getInputColor(); case OUTPUT: return CommonSignalSettings.getOutputColor(); @@ -553,26 +549,26 @@ public class StgSimulationTool extends PetriSimulationTool { } } - public void coloriseTokens(Transition t) { - VisualStg visualStg = (VisualStg) getUnderlyingModel(); - VisualTransition vt = visualStg.getVisualTransition(t); + public void coloriseTokens(final Transition t) { + final VisualStg visualStg = (VisualStg) getUnderlyingModel(); + final VisualTransition vt = visualStg.getVisualTransition(t); if (vt == null) return; Color tokenColor = Color.black; - ColorGenerator tokenColorGenerator = vt.getTokenColorGenerator(); + final ColorGenerator tokenColorGenerator = vt.getTokenColorGenerator(); if (tokenColorGenerator != null) { // generate token colour tokenColor = tokenColorGenerator.updateColor(); } else { // combine preset token colours - for (Connection c: visualStg.getConnections(vt)) { + for (final Connection c: visualStg.getConnections(vt)) { if ((c.getSecond() == vt) && (c instanceof VisualConnection)) { - VisualConnection vc = (VisualConnection) c; + final VisualConnection vc = (VisualConnection) c; if (vc.isTokenColorPropagator()) { if (vc.getFirst() instanceof VisualPlace) { - VisualPlace vp = (VisualPlace) c.getFirst(); + final VisualPlace vp = (VisualPlace) c.getFirst(); tokenColor = Coloriser.colorise(tokenColor, vp.getTokenColor()); } else if (vc instanceof VisualImplicitPlaceArc) { - VisualImplicitPlaceArc vipa = (VisualImplicitPlaceArc) vc; + final VisualImplicitPlaceArc vipa = (VisualImplicitPlaceArc) vc; tokenColor = Coloriser.colorise(tokenColor, vipa.getTokenColor()); } } @@ -580,15 +576,15 @@ public class StgSimulationTool extends PetriSimulationTool { } } // propagate the colour to postset tokens - for (Connection c: visualStg.getConnections(vt)) { + for (final Connection c: visualStg.getConnections(vt)) { if ((c.getFirst() == vt) && (c instanceof VisualConnection)) { - VisualConnection vc = (VisualConnection) c; + final VisualConnection vc = (VisualConnection) c; if (vc.isTokenColorPropagator()) { if (vc.getSecond() instanceof VisualPlace) { - VisualPlace vp = (VisualPlace) c.getSecond(); + final VisualPlace vp = (VisualPlace) c.getSecond(); vp.setTokenColor(tokenColor); } else if (vc instanceof VisualImplicitPlaceArc) { - VisualImplicitPlaceArc vipa = (VisualImplicitPlaceArc) vc; + final VisualImplicitPlaceArc vipa = (VisualImplicitPlaceArc) vc; vipa.setTokenColor(tokenColor); } } diff --git a/WorkcraftCore/src/org/workcraft/Framework.java b/WorkcraftCore/src/org/workcraft/Framework.java index d5c745d41..f3a3b33f9 100644 --- a/WorkcraftCore/src/org/workcraft/Framework.java +++ b/WorkcraftCore/src/org/workcraft/Framework.java @@ -591,6 +591,12 @@ public final class Framework { return null; } + public WorkspaceEntry createWork(ModelEntry me, Path<String> desiredPath) { + final Path<String> directory = desiredPath.getParent(); + final String desiredName = desiredPath.getNode(); + return createWork(me, directory, desiredName); + } + public WorkspaceEntry createWork(ModelEntry me, Path<String> directory, String desiredName) { final Path<String> path = getWorkspace().createWorkPath(directory, desiredName); boolean open = me.isVisual() || CommonEditorSettings.getOpenNonvisual(); diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/commands/AbstractConversionCommand.java b/WorkcraftCore/src/org/workcraft/gui/graph/commands/AbstractConversionCommand.java index c6171a22b..2b2e6616c 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/commands/AbstractConversionCommand.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/commands/AbstractConversionCommand.java @@ -30,9 +30,8 @@ public abstract class AbstractConversionCommand implements ScriptableCommand, Me return null; } else { final Framework framework = Framework.getInstance(); - final Path<String> directory = we.getWorkspacePath().getParent(); - final String name = we.getWorkspacePath().getNode(); - return framework.createWork(meDst, directory, name); + final Path<String> desiredPath = we.getWorkspacePath(); + return framework.createWork(meDst, desiredPath); } } diff --git a/WtgPlugin/src/org/workcraft/plugins/wtg/tasks/WtgToStgConversionResultHandler.java b/WtgPlugin/src/org/workcraft/plugins/wtg/tasks/WtgToStgConversionResultHandler.java index 36c0571a4..59640d986 100644 --- a/WtgPlugin/src/org/workcraft/plugins/wtg/tasks/WtgToStgConversionResultHandler.java +++ b/WtgPlugin/src/org/workcraft/plugins/wtg/tasks/WtgToStgConversionResultHandler.java @@ -1,7 +1,5 @@ package org.workcraft.plugins.wtg.tasks; -import java.io.File; - import javax.swing.JOptionPane; import org.workcraft.Framework; @@ -14,7 +12,6 @@ import org.workcraft.plugins.stg.StgDescriptor; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; -import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -23,30 +20,27 @@ public class WtgToStgConversionResultHandler extends DummyProgressMonitor<WaverC private final WaverConversionTask task; private WorkspaceEntry result; - public WtgToStgConversionResultHandler(WaverConversionTask task) { + public WtgToStgConversionResultHandler(final WaverConversionTask task) { this.task = task; this.result = null; } @Override - public void finished(final Result<? extends WaverConversionResult> result, String description) { + public void finished(final Result<? extends WaverConversionResult> result, final String description) { final Framework framework = Framework.getInstance(); - WorkspaceEntry we = task.getWorkspaceEntry(); - Path<String> path = we.getWorkspacePath(); if (result.getOutcome() == Outcome.FINISHED) { - Stg model = result.getReturnValue().getConversionResult(); - final Path<String> directory = path.getParent(); - final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); + final Stg model = result.getReturnValue().getConversionResult(); final ModelEntry me = new ModelEntry(new StgDescriptor(), model); - this.result = framework.createWork(me, directory, name); + final Path<String> path = task.getWorkspaceEntry().getWorkspacePath(); + this.result = framework.createWork(me, path); } else if (result.getOutcome() != Outcome.CANCELLED) { - MainWindow mainWindow = framework.getMainWindow(); + final MainWindow mainWindow = framework.getMainWindow(); if (result.getCause() != null) { ExceptionDialog.show(mainWindow, result.getCause()); } else { String message = "Unexpected Waver error"; if (result.getReturnValue() != null) { - Result<? extends ExternalProcessResult> waverResult = result.getReturnValue().getResult(); + final Result<? extends ExternalProcessResult> waverResult = result.getReturnValue().getResult(); message = "Waver output:\\n" + waverResult.getReturnValue().getErrorsHeadAndTail(); } JOptionPane.showMessageDialog(mainWindow, message, "Conversion failed", JOptionPane.WARNING_MESSAGE);
['WorkcraftCore/src/org/workcraft/Framework.java', 'MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisResultHandler.java', 'PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifySynthesisResultHandler.java', 'WorkcraftCore/src/org/workcraft/gui/graph/commands/AbstractConversionCommand.java', 'FstPlugin/src/org/workcraft/plugins/fst/tasks/StgToFstConversionResultHandler.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/MpsatCscConflictResolutionResultHandler.java', 'StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java', 'PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/PetrifyTransformationResultHandler.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java', 'WtgPlugin/src/org/workcraft/plugins/wtg/tasks/WtgToStgConversionResultHandler.java', 'CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java', 'FstPlugin/src/org/workcraft/plugins/fst/tasks/PetriToFsmConversionResultHandler.java', 'CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoResultHandler.java']
{'.java': 13}
13
13
0
0
13
4,839,482
971,864
135,255
1,381
35,060
6,501
492
13
724
109
210
20
1
0
"1970-01-01T00:24:53"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
762
workcraft/workcraft/676/113
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/113
https://github.com/workcraft/workcraft/pull/676
https://github.com/workcraft/workcraft/pull/676
1
fixes
Problem creating a new work while another work is maximised
- Work with an existing document - Maximize it's editor window - Create a new document Now it is not possible to exit the maximized editor mode properly.... The error message is: Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Can't maximize while different dockable is maximized at org.flexdock.docking.DockingManager.toggleMaximized(DockingManager.java:2732) at org.workcraft.gui.MainWindow.toggleDockableWindowMaximized(MainWindow.java:448) at org.workcraft.gui.DockableWindowContentPanel$ViewAction.run(DockableWindowContentPanel.java:71) at org.workcraft.gui.MainWindow$1.actionPerformed(MainWindow.java:109) at org.workcraft.gui.tabs.TabButton.mouseClicked(TabButton.java:62) at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) --- This issue was imported from Launchpad bug. - date created: 2010-10-21T16:37:09Z - owner: sgaflv - assignee: danilovesky - the launchpad url was https://bugs.launchpad.net/bugs/664600
2702122bbed73b0ec111cbc2107a97dc4614af7f
b3f511fe8dbc3f14df1a723550f3fcb3d3616a7b
https://github.com/workcraft/workcraft/compare/2702122bbed73b0ec111cbc2107a97dc4614af7f...b3f511fe8dbc3f14df1a723550f3fcb3d3616a7b
diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/gui/MpsatSolutionPanel.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/gui/MpsatSolutionPanel.java index 5186264cb..1e56a028f 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/gui/MpsatSolutionPanel.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/gui/MpsatSolutionPanel.java @@ -2,7 +2,6 @@ package org.workcraft.plugins.mpsat.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.util.List; import javax.swing.BorderFactory; import javax.swing.BoxLayout; @@ -75,20 +74,11 @@ public class MpsatSolutionPanel extends JPanel { public void actionPerformed(ActionEvent e) { final Framework framework = Framework.getInstance(); final MainWindow mainWindow = framework.getMainWindow(); - GraphEditorPanel currentEditor = mainWindow.getCurrentEditor(); - if (currentEditor == null || currentEditor.getWorkspaceEntry() != we) { - final List<GraphEditorPanel> editors = mainWindow.getEditors(we); - if (editors.size() > 0) { - currentEditor = editors.get(0); - mainWindow.requestFocus(currentEditor); - } else { - currentEditor = mainWindow.createEditorWindow(we); - } - } - final ToolboxPanel toolbox = currentEditor.getToolBox(); + GraphEditorPanel editor = mainWindow.getEditor(we); + final ToolboxPanel toolbox = editor.getToolBox(); final SimulationTool tool = toolbox.getToolInstance(SimulationTool.class); toolbox.selectTool(tool); - tool.setTrace(solution.getMainTrace(), solution.getBranchTrace(), currentEditor); + tool.setTrace(solution.getMainTrace(), solution.getBranchTrace(), editor); String comment = solution.getComment(); if ((comment != null) && !comment.isEmpty()) { comment = comment.replaceAll("\\\\<.*?>", ""); diff --git a/SonPlugin/src/org/workcraft/plugins/son/commands/ToolManager.java b/SonPlugin/src/org/workcraft/plugins/son/commands/ToolManager.java index 6ed0d01a2..d73c7a702 100644 --- a/SonPlugin/src/org/workcraft/plugins/son/commands/ToolManager.java +++ b/SonPlugin/src/org/workcraft/plugins/son/commands/ToolManager.java @@ -1,7 +1,5 @@ package org.workcraft.plugins.son.commands; -import java.util.List; - import org.workcraft.Framework; import org.workcraft.gui.MainWindow; import org.workcraft.gui.ToolboxPanel; @@ -13,17 +11,8 @@ public class ToolManager { public static ToolboxPanel getToolboxPanel(WorkspaceEntry we) { final Framework framework = Framework.getInstance(); final MainWindow mainWindow = framework.getMainWindow(); - GraphEditorPanel currentEditor = mainWindow.getCurrentEditor(); - if (currentEditor == null || currentEditor.getWorkspaceEntry() != we) { - final List<GraphEditorPanel> editors = mainWindow.getEditors(we); - if (editors.size() > 0) { - currentEditor = editors.get(0); - mainWindow.requestFocus(currentEditor); - } else { - currentEditor = mainWindow.createEditorWindow(we); - } - } - return currentEditor.getToolBox(); + GraphEditorPanel editor = mainWindow.getEditor(we); + return editor.getToolBox(); } } diff --git a/WorkcraftCore/src/org/workcraft/gui/DockableWindow.java b/WorkcraftCore/src/org/workcraft/gui/DockableWindow.java index ed64882c6..33333bdaa 100644 --- a/WorkcraftCore/src/org/workcraft/gui/DockableWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/DockableWindow.java @@ -1,6 +1,7 @@ package org.workcraft.gui; import java.awt.Component; +import java.awt.Container; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; @@ -82,6 +83,15 @@ public class DockableWindow extends AbstractDockable { public void setMaximized(boolean maximized) { panel.setMaximized(maximized); updateHeaders(this.getDockingPort(), mainWindow.getDefaultActionListener()); + if (maximized) { + for (DockableWindowTabListener l: tabListeners) { + l.windowMaximised(); + } + } else { + for (DockableWindowTabListener l: tabListeners) { + l.windowRestored(); + } + } } public boolean isClosed() { @@ -121,7 +131,8 @@ public class DockableWindow extends AbstractDockable { JTabbedPane tabbedPane = (JTabbedPane) dockable.getComponent().getParent(); for (int i = 0; i < tabbedPane.getComponentCount(); i++) { if (dockable.getComponent() == tabbedPane.getComponentAt(i)) { - tabbedPane.setTabComponentAt(i, new DockableTab(dockable, actionListener)); + DockableTab dockableTab = new DockableTab(dockable, actionListener); + tabbedPane.setTabComponentAt(i, dockableTab); break; } } @@ -154,23 +165,23 @@ public class DockableWindow extends AbstractDockable { } public void processTabEvents() { - if (getComponent().getParent() instanceof JTabbedPane) { - JTabbedPane tabbedPane = (JTabbedPane) getComponent().getParent(); + Container parent = getComponent().getParent(); + if (parent instanceof JTabbedPane) { + JTabbedPane tabbedPane = (JTabbedPane) parent; if (!inTab) { inTab = true; for (DockableWindowTabListener l: tabListeners) { l.dockedInTab(tabbedPane, getTabIndex(tabbedPane, this)); } } - if (!Arrays.asList(tabbedPane.getChangeListeners()).contains(tabChangeListener)) { + List<ChangeListener> tabbedPaneListeners = Arrays.asList(tabbedPane.getChangeListeners()); + if (!tabbedPaneListeners.contains(tabChangeListener)) { tabbedPane.addChangeListener(tabChangeListener); } - } else { - if (inTab) { - inTab = false; - for (DockableWindowTabListener l: tabListeners) { - l.dockedStandalone(); - } + } else if (inTab) { + inTab = false; + for (DockableWindowTabListener l: tabListeners) { + l.dockedStandalone(); } } } diff --git a/WorkcraftCore/src/org/workcraft/gui/DockableWindowContentPanel.java b/WorkcraftCore/src/org/workcraft/gui/DockableWindowContentPanel.java index a95ba06f8..a44b390d4 100644 --- a/WorkcraftCore/src/org/workcraft/gui/DockableWindowContentPanel.java +++ b/WorkcraftCore/src/org/workcraft/gui/DockableWindowContentPanel.java @@ -43,18 +43,17 @@ public class DockableWindowContentPanel extends JPanel { @Override public void run() { + final Framework framework = Framework.getInstance(); + MainWindow mainWindow = framework.getMainWindow(); switch (actionType) { case CLOSE_ACTION: try { - final Framework framework = Framework.getInstance(); - framework.getMainWindow().closeDockableWindow(windowID); + mainWindow.closeDockableWindow(windowID); } catch (OperationCancelledException e) { - } break; case MAXIMIZE_ACTION: - final Framework framework = Framework.getInstance(); - framework.getMainWindow().toggleDockableWindowMaximized(windowID); + mainWindow.toggleDockableWindowMaximized(windowID); break; case MINIMIZE_ACTION: throw new NotSupportedException(); @@ -103,7 +102,8 @@ public class DockableWindowContentPanel extends JPanel { int iconCount = 0; if ((options & MINIMIZE_BUTTON) != 0) { Icon minIcon = UIManager.getIcon("InternalFrame.minimizeIcon"); - btnMin = createHeaderButton(minIcon, new ViewAction(id, ViewAction.MINIMIZE_ACTION), mainWindow.getDefaultActionListener()); + ViewAction minAction = new ViewAction(id, ViewAction.MINIMIZE_ACTION); + btnMin = createHeaderButton(minIcon, minAction, mainWindow.getDefaultActionListener()); btnMin.setToolTipText("Toggle minimized"); buttonPanel.add(btnMin); iconCount++; @@ -111,21 +111,24 @@ public class DockableWindowContentPanel extends JPanel { if ((options & MAXIMIZE_BUTTON) != 0) { Icon maxIcon = UIManager.getIcon("InternalFrame.maximizeIcon"); - btnMax = createHeaderButton(maxIcon, new ViewAction(id, ViewAction.MAXIMIZE_ACTION), mainWindow.getDefaultActionListener()); + ViewAction maxAction = new ViewAction(id, ViewAction.MAXIMIZE_ACTION); + btnMax = createHeaderButton(maxIcon, maxAction, mainWindow.getDefaultActionListener()); buttonPanel.add(btnMax); iconCount++; } Icon closeIcon = UIManager.getIcon("InternalFrame.closeIcon"); if ((options & CLOSE_BUTTON) != 0) { - btnClose = createHeaderButton(closeIcon, new ViewAction(id, ViewAction.CLOSE_ACTION), mainWindow.getDefaultActionListener()); + ViewAction closeAction = new ViewAction(id, ViewAction.CLOSE_ACTION); + btnClose = createHeaderButton(closeIcon, closeAction, mainWindow.getDefaultActionListener()); btnClose.setToolTipText("Close window"); buttonPanel.add(btnClose); iconCount++; } if (iconCount != 0) { - buttonPanel.setPreferredSize(new Dimension((closeIcon.getIconWidth() + 4) * iconCount, closeIcon.getIconHeight() + 4)); + Dimension size = new Dimension((closeIcon.getIconWidth() + 4) * iconCount, closeIcon.getIconHeight() + 4); + buttonPanel.setPreferredSize(size); } titleLabel = new JLabel(title); diff --git a/WorkcraftCore/src/org/workcraft/gui/DockableWindowTabListener.java b/WorkcraftCore/src/org/workcraft/gui/DockableWindowTabListener.java index 6f3cad387..9e25d858f 100644 --- a/WorkcraftCore/src/org/workcraft/gui/DockableWindowTabListener.java +++ b/WorkcraftCore/src/org/workcraft/gui/DockableWindowTabListener.java @@ -8,4 +8,6 @@ public interface DockableWindowTabListener { void tabSelected(JTabbedPane pane, int index); void tabDeselected(JTabbedPane pane, int index); void headerClicked(); + void windowMaximised(); + void windowRestored(); } diff --git a/WorkcraftCore/src/org/workcraft/gui/EditorWindowTabListener.java b/WorkcraftCore/src/org/workcraft/gui/EditorWindowTabListener.java index 7d5d15292..ccd7ec288 100644 --- a/WorkcraftCore/src/org/workcraft/gui/EditorWindowTabListener.java +++ b/WorkcraftCore/src/org/workcraft/gui/EditorWindowTabListener.java @@ -15,9 +15,8 @@ public class EditorWindowTabListener implements DockableWindowTabListener { @Override public void tabSelected(JTabbedPane tabbedPane, int tabIndex) { - final Framework framework = Framework.getInstance(); - MainWindow mainWindow = framework.getMainWindow(); - mainWindow.requestFocus(editor); + setNonFocusable(tabbedPane); + requestEditorFocus(); } @Override @@ -26,14 +25,36 @@ public class EditorWindowTabListener implements DockableWindowTabListener { @Override public void dockedStandalone() { + requestEditorFocus(); } @Override public void dockedInTab(JTabbedPane tabbedPane, int tabIndex) { + setNonFocusable(tabbedPane); + requestEditorFocus(); } @Override public void headerClicked() { + requestEditorFocus(); + } + + @Override + public void windowMaximised() { + requestEditorFocus(); + } + + @Override + public void windowRestored() { + requestEditorFocus(); + } + + private void setNonFocusable(JTabbedPane tabbedPane) { + // Set non-focusable, so that tab activation does not steal the focus form the included component. + tabbedPane.setFocusable(false); + } + + private void requestEditorFocus() { final Framework framework = Framework.getInstance(); MainWindow mainWindow = framework.getMainWindow(); mainWindow.requestFocus(editor); diff --git a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java index 7b85e3c8e..1d908c3df 100644 --- a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java @@ -225,10 +225,7 @@ public class MainWindow extends JFrame { final GraphEditorPanel editor = new GraphEditorPanel(we); String title = getTitle(we); final DockableWindow editorWindow; - int options = DockableWindowContentPanel.CLOSE_BUTTON; - // FIXME: Maximised tabs confuse EditorWindowTabListener that sets editorInFocus, - // therefore the maximise button is temporary removed from the dockable windows. - // options |= DockableWindowContentPanel.MAXIMIZE_BUTTON; + int options = DockableWindowContentPanel.CLOSE_BUTTON | DockableWindowContentPanel.MAXIMIZE_BUTTON; if (editorWindows.isEmpty()) { editorWindow = createDockableWindow(editor, title, documentPlaceholder, options, DockingConstants.CENTER_REGION, "Document" + we.getWorkspacePath()); @@ -236,11 +233,13 @@ public class MainWindow extends JFrame { DockingManager.unregisterDockable(documentPlaceholder); utilityWindows.remove(documentPlaceholder); } else { + unmaximiseAllDockableWindows(); DockableWindow firstEditorWindow = editorWindows.values().iterator().next().iterator().next(); editorWindow = createDockableWindow(editor, title, firstEditorWindow, options, DockingConstants.CENTER_REGION, "Document" + we.getWorkspacePath()); } - editorWindow.addTabListener(new EditorWindowTabListener(editor)); + EditorWindowTabListener tabListener = new EditorWindowTabListener(editor); + editorWindow.addTabListener(tabListener); editorWindows.put(we, editorWindow); requestFocus(editor); setWorkActionsEnableness(true); @@ -248,6 +247,17 @@ public class MainWindow extends JFrame { return editor; } + private void unmaximiseAllDockableWindows() { + for (LinkedList<DockableWindow> dockableWindows: editorWindows.values()) { + for (DockableWindow dockableWindow: dockableWindows) { + if (dockableWindow.isMaximized()) { + DockingManager.toggleMaximized(dockableWindow); + dockableWindow.setMaximized(false); + } + } + } + } + private void registerUtilityWindow(DockableWindow dockableWindow) { if (!rootDockingPort.getDockables().contains(dockableWindow)) { dockableWindow.setClosed(true); @@ -696,25 +706,24 @@ public class MainWindow extends JFrame { } } - public void requestFocus(GraphEditorPanel sender) { - sender.requestFocusInWindow(); - if (editorInFocus != sender) { - editorInFocus = sender; + public void requestFocus(GraphEditorPanel editor) { + editor.requestFocusInWindow(); + if (editorInFocus != editor) { + editorInFocus = editor; WorkspaceEntry we = editorInFocus.getWorkspaceEntry(); mainMenu.setMenuForWorkspaceEntry(we); - ToolboxPanel toolBox = sender.getToolBox(); + ToolboxPanel toolBox = editorInFocus.getToolBox(); toolControlsWindow.setContent(toolBox); editorToolsWindow.setContent(toolBox.getControlPanel()); GraphEditorTool selectedTool = toolBox.getSelectedTool(); selectedTool.setup(editorInFocus); - sender.updatePropertyView(); + editorInFocus.updatePropertyView(); Framework.getInstance().updateJavaScript(we); } - editorInFocus.requestFocus(); } private void printCause(Throwable e) { diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanel.java b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanel.java index 68e0ed17d..6d6e84609 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanel.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanel.java @@ -72,37 +72,46 @@ public class GraphEditorPanel extends JPanel implements StateObserver, GraphEdit public static final String TITLE_SUFFIX_SELECTED_ELEMENTS = " selected elements"; private static final int VIEWPORT_MARGIN = 25; - class Resizer implements ComponentListener { + public class GraphEditorFocusListener implements FocusListener { + private final GraphEditorPanel editor; - @Override - public void componentHidden(ComponentEvent e) { + public GraphEditorFocusListener(GraphEditorPanel editor) { + this.editor = editor; } @Override - public void componentMoved(ComponentEvent e) { + public void focusGained(FocusEvent e) { + final Framework framework = Framework.getInstance(); + MainWindow mainWindow = framework.getMainWindow(); + mainWindow.requestFocus(editor); + repaint(); } @Override - public void componentResized(ComponentEvent e) { - reshape(); + public void focusLost(FocusEvent e) { repaint(); } + } + + class Resizer implements ComponentListener { @Override - public void componentShown(ComponentEvent e) { + public void componentHidden(ComponentEvent e) { } - } - public class GraphEditorFocusListener implements FocusListener { @Override - public void focusGained(FocusEvent e) { - repaint(); + public void componentMoved(ComponentEvent e) { } @Override - public void focusLost(FocusEvent e) { + public void componentResized(ComponentEvent e) { + reshape(); repaint(); } + + @Override + public void componentShown(ComponentEvent e) { + } } private static final long serialVersionUID = 1L; @@ -201,14 +210,14 @@ public class GraphEditorPanel extends JPanel implements StateObserver, GraphEdit GraphEditorPanelMouseListener mouseListener = new GraphEditorPanelMouseListener(this, toolboxPanel); GraphEditorPanelKeyListener keyListener = new GraphEditorPanelKeyListener(this, toolboxPanel); + GraphEditorFocusListener focusListener = new GraphEditorFocusListener(this); addMouseMotionListener(mouseListener); addMouseListener(mouseListener); addMouseWheelListener(mouseListener); - addFocusListener(new GraphEditorFocusListener()); - addComponentListener(new Resizer()); - addKeyListener(keyListener); + addFocusListener(focusListener); + addComponentListener(new Resizer()); add(overlay, BorderLayout.CENTER); diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelKeyListener.java b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelKeyListener.java index e2cae2928..633c858e1 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelKeyListener.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelKeyListener.java @@ -8,8 +8,8 @@ import org.workcraft.gui.events.GraphEditorKeyEvent; import org.workcraft.gui.graph.tools.GraphEditorKeyListener; class GraphEditorPanelKeyListener implements KeyListener { - GraphEditorPanel editor; - GraphEditorKeyListener forwardListener; + private final GraphEditorPanel editor; + private final GraphEditorKeyListener forwardListener; GraphEditorPanelKeyListener(GraphEditorPanel editor, GraphEditorKeyListener forwardListener) { this.editor = editor; diff --git a/WorkcraftCore/src/org/workcraft/gui/tabs/DockableTab.java b/WorkcraftCore/src/org/workcraft/gui/tabs/DockableTab.java index 95fe0bf55..3fe556f8d 100644 --- a/WorkcraftCore/src/org/workcraft/gui/tabs/DockableTab.java +++ b/WorkcraftCore/src/org/workcraft/gui/tabs/DockableTab.java @@ -41,20 +41,22 @@ public class DockableTab extends JPanel { label.setFocusable(false); label.setOpaque(false); - TabButton close = null; + TabButton closeButton = null; if ((dockableWindow.getOptions() & DockableWindowContentPanel.MAXIMIZE_BUTTON) != 0) { - TabButton max = new TabButton("\\u2191", "Maximize window", new ViewAction(dockableWindow.getID(), ViewAction.MAXIMIZE_ACTION), actionListener); - buttonsPanel.add(max); + ViewAction viewAction = new ViewAction(dockableWindow.getID(), ViewAction.MAXIMIZE_ACTION); + TabButton maxButton = new TabButton("\\u2191", "Maximize window", viewAction, actionListener); + buttonsPanel.add(maxButton); buttonsPanel.add(Box.createRigidArea(new Dimension(2, 0))); } if ((dockableWindow.getOptions() & DockableWindowContentPanel.CLOSE_BUTTON) != 0) { - close = new TabButton("\\u00d7", "Close window", new ViewAction(dockableWindow.getID(), ViewAction.CLOSE_ACTION), actionListener); - buttonsPanel.add(close); + ViewAction viewAction = new ViewAction(dockableWindow.getID(), ViewAction.CLOSE_ACTION); + closeButton = new TabButton("\\u00d7", "Close window", viewAction, actionListener); + buttonsPanel.add(closeButton); } Dimension x = label.getPreferredSize(); - Dimension y = (close != null) ? close.getPreferredSize() : x; + Dimension y = (closeButton != null) ? closeButton.getPreferredSize() : x; this.add(label, BorderLayout.CENTER); this.add(buttonsPanel, BorderLayout.EAST);
['WorkcraftCore/src/org/workcraft/gui/tabs/DockableTab.java', 'WorkcraftCore/src/org/workcraft/gui/MainWindow.java', 'WorkcraftCore/src/org/workcraft/gui/DockableWindowTabListener.java', 'WorkcraftCore/src/org/workcraft/gui/DockableWindowContentPanel.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/gui/MpsatSolutionPanel.java', 'WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelKeyListener.java', 'SonPlugin/src/org/workcraft/plugins/son/commands/ToolManager.java', 'WorkcraftCore/src/org/workcraft/gui/EditorWindowTabListener.java', 'WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanel.java', 'WorkcraftCore/src/org/workcraft/gui/DockableWindow.java']
{'.java': 10}
10
10
0
0
10
4,835,392
970,958
135,144
1,378
10,588
1,956
202
10
1,044
84
260
25
1
0
"1970-01-01T00:24:53"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
763
workcraft/workcraft/636/631
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/631
https://github.com/workcraft/workcraft/pull/636
https://github.com/workcraft/workcraft/pull/636
1
fixes
Anchor points are not moved on DFS copying for wagging
If there is an anchor point on the ark where wagging is applied, then the result may be confusing, as in all copies the anchor points will have the same coordinate -- it looks like an intersection of arcs. The relative position of anchor points to the arc should be preserved relative to the arc, not their global position.
5239dcd60bc4e7180ce10040140a760595e0007b
16c1c0cbc1516056dabe93d3a52915fca57fb8f7
https://github.com/workcraft/workcraft/compare/5239dcd60bc4e7180ce10040140a760595e0007b...16c1c0cbc1516056dabe93d3a52915fca57fb8f7
diff --git a/DfsPlugin/src/org/workcraft/plugins/dfs/commands/WaggingGenerator.java b/DfsPlugin/src/org/workcraft/plugins/dfs/commands/WaggingGenerator.java index 54b60bc9a..0a89e25ec 100644 --- a/DfsPlugin/src/org/workcraft/plugins/dfs/commands/WaggingGenerator.java +++ b/DfsPlugin/src/org/workcraft/plugins/dfs/commands/WaggingGenerator.java @@ -11,6 +11,7 @@ import org.workcraft.dom.Node; import org.workcraft.dom.math.MathConnection; import org.workcraft.dom.math.MathNode; import org.workcraft.dom.visual.BoundingBoxHelper; +import org.workcraft.dom.visual.ConnectionHelper; import org.workcraft.dom.visual.VisualComponent; import org.workcraft.dom.visual.VisualTransformableNode; import org.workcraft.dom.visual.connections.ControlPoint; @@ -81,7 +82,8 @@ public class WaggingGenerator { if (hasInterface.getSecond()) { insertPopControl(); } - createGroups(); + cleanup(); + group(); } private void replicateSelection() { @@ -151,6 +153,9 @@ public class WaggingGenerator { } replica.copyStyle(connection); replica.copyShape(connection); + Point2D p = connection.getFirstCenter(); + Point2D offset = new Point2D.Double(first.getX() - p.getX(), first.getY() - p.getY()); + ConnectionHelper.moveControlPoints(replica, offset); } return replica; } @@ -281,12 +286,15 @@ public class WaggingGenerator { } } - private void createGroups() { + private void cleanup() { dfs.selectNone(); for (VisualComponent component: selectedComponents) { dfs.addToSelection(component); } dfs.deleteSelection(); + } + + private void group() { // data components ArrayList<Node> dataNodes = new ArrayList<>(); for (WaggingData waggingData: wagging) { diff --git a/WorkcraftCore/src/org/workcraft/dom/visual/ConnectionHelper.java b/WorkcraftCore/src/org/workcraft/dom/visual/ConnectionHelper.java index 01d02b8c8..0803c5c47 100644 --- a/WorkcraftCore/src/org/workcraft/dom/visual/ConnectionHelper.java +++ b/WorkcraftCore/src/org/workcraft/dom/visual/ConnectionHelper.java @@ -199,6 +199,17 @@ public class ConnectionHelper { } } + public static void moveControlPoints(VisualConnection connection, Point2D offset) { + if ((connection != null) && (offset != null)) { + ConnectionGraphic graphic = connection.getGraphic(); + for (ControlPoint cp: graphic.getControlPoints()) { + Point2D p1 = cp.getPosition(); + Point2D p2 = new Point2D.Double(p1.getX() + offset.getX(), p1.getY() + offset.getY()); + cp.setPosition(p2); + } + } + } + public static void removeControlPointsByDistance(Polyline polyline, Point2D pos, double threshold) { List<ControlPoint> controlPoints = new LinkedList<>(polyline.getControlPoints()); for (ControlPoint cp: controlPoints) { diff --git a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java index 0803f8656..59010fcbe 100644 --- a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java @@ -139,8 +139,8 @@ public class MainWindow extends JFrame { private static final String DIALOG_RESET_LAYOUT = "Reset layout"; private final ScriptedActionListener defaultActionListener = new ScriptedActionListener() { - public void actionPerformed(Action e) { - e.run(); + public void actionPerformed(Action action) { + action.run(); } }; @@ -784,8 +784,9 @@ public class MainWindow extends JFrame { } // Set file filters fc.setAcceptAllFileFilterUsed(false); - fc.setFileFilter(FileFilters.DOCUMENT_FILES); - if (importers != null) { + if ((importers == null) || (importers.length == 0)) { + fc.setFileFilter(FileFilters.DOCUMENT_FILES); + } else { for (Importer importer : importers) { fc.addChoosableFileFilter(new ImporterFileFilter(importer)); } @@ -1034,8 +1035,8 @@ public class MainWindow extends JFrame { JFileChooser fc = createOpenDialog("Import model(s)", true, importers); if (fc.showDialog(this, "Open") == JFileChooser.APPROVE_OPTION) { - for (File f : fc.getSelectedFiles()) { - importFrom(f, importers); + for (File file : fc.getSelectedFiles()) { + importFrom(file, importers); } } } diff --git a/WorkcraftCore/src/org/workcraft/workspace/WorkspaceEntry.java b/WorkcraftCore/src/org/workcraft/workspace/WorkspaceEntry.java index d2ff7d380..7391acdd7 100644 --- a/WorkcraftCore/src/org/workcraft/workspace/WorkspaceEntry.java +++ b/WorkcraftCore/src/org/workcraft/workspace/WorkspaceEntry.java @@ -332,7 +332,7 @@ public class WorkspaceEntry implements ObservableState { if (model.getSelection().size() > 0) { captureMemento(); try { - // copy selected nodes inside a group as if it was the root + // Copy selected nodes inside a group as if it was the root. while (model.getCurrentLevel() != model.getRoot()) { Collection<Node> nodes = new HashSet<>(model.getSelection()); Container level = model.getCurrentLevel(); @@ -349,8 +349,7 @@ public class WorkspaceEntry implements ObservableState { final Framework framework = Framework.getInstance(); framework.clipboard = framework.saveModel(modelEntry); if (CommonDebugSettings.getCopyModelOnChange()) { - // copy the memento clipboard into the system-wide clipboard - // as a string + // Copy the memento clipboard into the system-wide clipboard as a string. Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(getClipboardAsString()), null); }
['WorkcraftCore/src/org/workcraft/workspace/WorkspaceEntry.java', 'DfsPlugin/src/org/workcraft/plugins/dfs/commands/WaggingGenerator.java', 'WorkcraftCore/src/org/workcraft/dom/visual/ConnectionHelper.java', 'WorkcraftCore/src/org/workcraft/gui/MainWindow.java']
{'.java': 4}
4
4
0
0
4
4,968,154
1,008,598
139,234
1,304
1,879
371
41
4
326
59
65
3
0
0
"1970-01-01T00:24:42"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
764
workcraft/workcraft/635/634
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/634
https://github.com/workcraft/workcraft/pull/635
https://github.com/workcraft/workcraft/pull/635
1
fixes
Error on Verilog export
When exporting verilog from a circuit with standard C-gates, the resulting file does not import correctly. The reason is that the assignments representing C-gates are wrong. The C-gate output has been concatenated to onto the previous variable instead of being ORed. From the example: ``` assign gn = assign_gn_SET__o & assign_gn_nRESET__ogn& (~~(assign_gn_SET__o | assign_gn_nRESET__o)); ``` should be ``` assign gn = assign_gn_SET__o & assign_gn_nRESET__o | gn & (~~(assign_gn_SET__o | assign_gn_nRESET__o)); ``` Clearly importing the incorrect verilog will give the wrong answer as there is no signal called `assign_gn_nRESET__ogn`. Having corrected the verilog the import works in that the circuit is conformant with the original STG, but the C-gate isn't recognised as a C-gate and is represented by a complex gate with loop-back. Note that I have included .work files created from the imported verilog. However they won't open again. I've also noticed that saving the .work and opening it again works. Closing the circuit window then opening the .work fails. So there are three problems where 1. Output verilog for a C-gate is incorrect. 2. C-gate isn't recognised when importing assignment based verilog. 3. Saving the imported verilog results in a corrupt .work file. Files: * [all_zc.work.zip](https://github.com/tuura/workcraft/files/668935/all_zc.work.zip) - original STG. * [all_zc_circuit.work.zip](https://github.com/tuura/workcraft/files/668934/all_zc_circuit.work.zip) - result of synthesis with "Standard C-element [MpSat]" * [all_zc_circuit.v.txt](https://github.com/tuura/workcraft/files/668944/all_zc_circuit.v.txt) - result of exporting verilog from all_zc_cicuit.work * [all_zc_circuit.v.work.zip](https://github.com/tuura/workcraft/files/668936/all_zc_circuit.v.work.zip) result of importing all_zc_circuit.v, will not read in. * [all_zc_circuit_fixed.v.txt](https://github.com/tuura/workcraft/files/668945/all_zc_circuit_fixed.v.txt) - fixed version of all_zc_circuit.v * [all_zc_circuit_fixed.v.work.zip](https://github.com/tuura/workcraft/files/668937/all_zc_circuit_fixed.v.work.zip) - result of importing all_zc_circuit_fixed.v, will not read in.
31d821d3c1a8a6669c06169f434c2b99382c4ae7
dcfb3880b24e1cb64e20b3e82d76301f83b873b1
https://github.com/workcraft/workcraft/compare/31d821d3c1a8a6669c06169f434c2b99382c4ae7...dcfb3880b24e1cb64e20b3e82d76301f83b873b1
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java index 29d4d8b30..0be3e1293 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java @@ -183,19 +183,6 @@ public class CircuitUtils { return circuit.getVisualComponent(mathSignal, VisualContact.class); } - public static String getWireName(Circuit circuit, Contact contact) { - String result = null; - if (!circuit.getPreset(contact).isEmpty() || !circuit.getPostset(contact).isEmpty()) { - Contact signal = findSignal(circuit, contact, false); - result = getContactName(circuit, signal); - } - return result; - } - - public static String getWireName(VisualCircuit circuit, VisualContact contact) { - return getWireName((Circuit) circuit.getMathModel(), contact.getReferencedContact()); - } - public static String getSignalName(Circuit circuit, Contact contact) { String result = null; if (contact.isPort() || contact.isInput()) { diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java index 565e47129..5f4ab6e1d 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java @@ -39,7 +39,10 @@ import java.util.Set; import org.workcraft.Framework; import org.workcraft.dom.Connection; import org.workcraft.dom.Node; +import org.workcraft.dom.hierarchy.NamespaceProvider; import org.workcraft.dom.math.MathNode; +import org.workcraft.dom.references.HierarchicalUniqueNameReferenceManager; +import org.workcraft.dom.references.NameManager; import org.workcraft.exceptions.ArgumentException; import org.workcraft.exceptions.DeserialisationException; import org.workcraft.exceptions.FormatException; @@ -93,7 +96,6 @@ public class VerilogImporter implements Importer { private static final String PRIMITIVE_GATE_INPUT_PREFIX = "i"; private static final String PRIMITIVE_GATE_OUTPUT_NAME = "o"; - private static final String ASSIGN_GATE_PREFIX = "assign_"; private final boolean sequentialAssign; @@ -252,12 +254,7 @@ public class VerilogImporter implements Importer { private FunctionComponent createAssignGate(Circuit circuit, Assign assign, HashMap<String, Wire> wires) { final FunctionComponent component = new FunctionComponent(); circuit.add(component); - String componentName = getAssignComponentName(assign.name); - try { - circuit.setName(component, componentName); - } catch (ArgumentException e) { - LogUtils.logWarningLine("Cannot set name '" + componentName + "' for component '" + circuit.getName(component) + "'."); - } + setAssignComponentName(circuit, component, assign.name); AssignGate assignGate = null; if (sequentialAssign && isSequentialAssign(assign)) { @@ -300,8 +297,19 @@ public class VerilogImporter implements Importer { return component; } - private String getAssignComponentName(String name) { - return ASSIGN_GATE_PREFIX + removeLeadingAndTrailingSymbol(name, '_'); + private void setAssignComponentName(Circuit circuit, FunctionComponent component, String name) { + HierarchicalUniqueNameReferenceManager refManager + = (HierarchicalUniqueNameReferenceManager) circuit.getReferenceManager(); + + NamespaceProvider namespaceProvider = refManager.getNamespaceProvider(circuit.getRoot()); + NameManager nameManagerer = refManager.getNameManager(namespaceProvider); + String candidateName = removeLeadingAndTrailingSymbol(name, '_'); + String componentName = nameManagerer.getDerivedName(component, candidateName); + try { + circuit.setName(component, componentName); + } catch (ArgumentException e) { + LogUtils.logWarningLine("Cannot set name '" + componentName + "' for component '" + circuit.getName(component) + "'."); + } } private String removeLeadingAndTrailingSymbol(String s, char c) { diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/VerilogSerialiser.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/VerilogSerialiser.java index 7f9aed23e..216f1a040 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/VerilogSerialiser.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/VerilogSerialiser.java @@ -29,6 +29,7 @@ import java.util.LinkedList; import java.util.UUID; import org.workcraft.dom.Model; +import org.workcraft.dom.Node; import org.workcraft.dom.hierarchy.NamespaceHelper; import org.workcraft.exceptions.ArgumentException; import org.workcraft.formula.BooleanFormula; @@ -58,6 +59,7 @@ public class VerilogSerialiser implements ModelSerialiser { private static final String KEYWORD_INPUT = "input"; private static final String KEYWORD_MODULE = "module"; private static final String KEYWORD_ENDMODULE = "endmodule"; + private static final String KEYWORD_ASSIGN = "assign"; class ReferenceResolver implements ReferenceProducer { HashMap<Object, String> refMap = new HashMap<>(); @@ -101,7 +103,34 @@ public class VerilogSerialiser implements ModelSerialiser { return Format.VERILOG; } + private final HashMap<Contact, String> contactWires = new HashMap<>(); + + private String getWireName(Circuit circuit, Contact contact) { + String result = contactWires.get(contact); + if (result == null) { + if (!circuit.getPreset(contact).isEmpty() || !circuit.getPostset(contact).isEmpty()) { + Contact signal = CircuitUtils.findSignal(circuit, contact, false); + Node parent = signal.getParent(); + boolean isAssignOutput = false; + if (parent instanceof FunctionComponent) { + FunctionComponent component = (FunctionComponent) parent; + isAssignOutput = signal.isOutput() && !component.isMapped(); + } + if (isAssignOutput) { + result = CircuitUtils.getSignalName(circuit, signal); + } else { + result = CircuitUtils.getContactName(circuit, signal); + } + } + if (result != null) { + contactWires.put(contact, result); + } + } + return result; + } + private void writeCircuit(PrintWriter out, Circuit circuit) { + contactWires.clear(); writeHeader(out, circuit); writeInstances(out, circuit); writeInitialState(out, circuit); @@ -184,7 +213,7 @@ public class VerilogSerialiser implements ModelSerialiser { LinkedList<BooleanFormula> values = new LinkedList<>(); for (FunctionContact contact: component.getFunctionContacts()) { if (contact.isOutput()) continue; - String wireName = CircuitUtils.getWireName(circuit, contact); + String wireName = getWireName(circuit, contact); BooleanFormula wire = signals.get(wireName); if (wire != null) { variables.add(contact); @@ -194,7 +223,12 @@ public class VerilogSerialiser implements ModelSerialiser { for (FunctionContact contact: component.getFunctionContacts()) { if (contact.isInput()) continue; String formula = null; - String wireName = CircuitUtils.getWireName(circuit, contact); + String wireName = getWireName(circuit, contact); + if ((wireName == null) || wireName.isEmpty()) { + String contactName = contact.getName(); + LogUtils.logWarningLine("In component '" + instanceFlatName + "' contact '" + contactName + "' is disconnected."); + continue; + } BooleanFormula setFunction = BooleanUtils.cleverReplace(contact.getSetFunction(), variables, values); String setFormula = FormulaToString.toString(setFunction, Style.VERILOG); BooleanFormula resetFunction = BooleanUtils.cleverReplace(contact.getResetFunction(), variables, values); @@ -203,14 +237,14 @@ public class VerilogSerialiser implements ModelSerialiser { } String resetFormula = FormulaToString.toString(resetFunction, Style.VERILOG); if (!setFormula.isEmpty() && !resetFormula.isEmpty()) { - formula = setFormula + wireName + "& (" + resetFormula + ")"; + formula = setFormula + " | " + wireName + " & (" + resetFormula + ")"; } else if (!setFormula.isEmpty()) { formula = setFormula; } else if (!resetFormula.isEmpty()) { formula = resetFormula; } if ((formula != null) && !formula.isEmpty()) { - out.println(" assign " + wireName + " = " + formula + ";"); + out.println(" " + KEYWORD_ASSIGN + " " + wireName + " = " + formula + ";"); result = true; } } @@ -223,7 +257,7 @@ public class VerilogSerialiser implements ModelSerialiser { String signalName = null; BooleanFormula signal = null; if (contact.isDriver()) { - signalName = CircuitUtils.getWireName(circuit, contact); + signalName = getWireName(circuit, contact); if (contact.isPort()) { signal = contact; } else { @@ -261,7 +295,7 @@ public class VerilogSerialiser implements ModelSerialiser { } else { out.print(", "); } - String wireName = CircuitUtils.getWireName(circuit, contact); + String wireName = getWireName(circuit, contact); if ((wireName == null) || wireName.isEmpty()) { String contactName = contact.getName(); LogUtils.logWarningLine("In component '" + instanceFlatName + "' contact '" + contactName + "' is disconnected."); @@ -287,7 +321,7 @@ public class VerilogSerialiser implements ModelSerialiser { out.println(" // signal values at the initial state:"); out.print(" //"); for (Contact contact: contacts) { - String wireName = CircuitUtils.getWireName(circuit, contact); + String wireName = getWireName(circuit, contact); if ((wireName != null) && !wireName.isEmpty()) { out.print(" "); if (!contact.getInitToOne()) { diff --git a/WorkcraftCore/src/org/workcraft/Framework.java b/WorkcraftCore/src/org/workcraft/Framework.java index e69ea8e70..f17470a30 100644 --- a/WorkcraftCore/src/org/workcraft/Framework.java +++ b/WorkcraftCore/src/org/workcraft/Framework.java @@ -579,27 +579,29 @@ public final class Framework { return null; } - public WorkspaceEntry createWork(ModelEntry me, Path<String> path) { + public WorkspaceEntry createWork(ModelEntry me, Path<String> directory, String desiredName) { + final Path<String> path = getWorkspace().createWorkPath(directory, desiredName); + boolean open = me.isVisual() || CommonEditorSettings.getOpenNonvisual(); + return createWork(me, path, open, true); + } + + private WorkspaceEntry createWork(ModelEntry me, Path<String> path, boolean open, boolean changed) { WorkspaceEntry we = new WorkspaceEntry(getWorkspace()); - we.setChanged(true); + we.setChanged(changed); we.setModelEntry(createVisual(me)); getWorkspace().addWork(path, we); - boolean openInEditor = me.isVisual() || CommonEditorSettings.getOpenNonvisual(); - if (openInEditor && isInGuiMode()) { + if (open && isInGuiMode()) { getMainWindow().createEditorWindow(we); } return we; } - public WorkspaceEntry createWork(ModelEntry me, Path<String> directory, String desiredName) { - final Path<String> path = getWorkspace().createWorkPath(directory, desiredName); - return createWork(me, path); - } - private ModelEntry createVisual(ModelEntry me) { ModelEntry result = me; VisualModel visualModel = me.getVisualModel(); - if (visualModel == null) { + if (visualModel != null) { + visualModel.selectNone(); + } else { ModelDescriptor descriptor = me.getDescriptor(); VisualModelDescriptor vmd = descriptor.getVisualModelDescriptor(); if (vmd == null) { @@ -642,33 +644,35 @@ public final class Framework { public WorkspaceEntry loadWork(File file) throws DeserialisationException { // Check if work is already loaded - Path<String> workspacePath = getWorkspace().getPath(file); + Path<String> path = getWorkspace().getPath(file); for (WorkspaceEntry we : getWorkspace().getWorks()) { - if (we.getWorkspacePath().equals(workspacePath)) { + if (we.getWorkspacePath().equals(path)) { return we; } } // Load (from *.work) or import (other extensions) work - WorkspaceEntry we = new WorkspaceEntry(getWorkspace()); - we.setChanged(false); + ModelEntry me = null; if (file.getName().endsWith(FileFilters.DOCUMENT_EXTENSION)) { - we.setModelEntry(loadModel(file)); - if (workspacePath == null) { - workspacePath = getWorkspace().tempMountExternalFile(file); + if (path == null) { + path = getWorkspace().tempMountExternalFile(file); } + me = loadModel(file); } else { - we.setModelEntry(importModel(file)); Path<String> parent; - if (workspacePath == null) { + if (path == null) { parent = Path.empty(); } else { - parent = workspacePath.getParent(); + parent = path.getParent(); } String desiredName = FileUtils.getFileNameWithoutExtension(file); - workspacePath = getWorkspace().createWorkPath(parent, desiredName); + path = getWorkspace().createWorkPath(parent, desiredName); + me = importModel(file); + } + WorkspaceEntry we = null; + if (me != null) { + we = createWork(me, path, false, false); } - getWorkspace().addWork(workspacePath, we); return we; }
['WorkcraftCore/src/org/workcraft/Framework.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/VerilogSerialiser.java']
{'.java': 4}
4
4
0
0
4
4,966,636
1,008,315
139,201
1,304
7,153
1,396
135
4
2,253
247
600
37
6
2
"1970-01-01T00:24:42"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
765
workcraft/workcraft/613/609
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/609
https://github.com/workcraft/workcraft/pull/613
https://github.com/workcraft/workcraft/pull/613
1
fixes
Connection from output port to input pin
To reproduce 1. Create a digital circuit with a output port and an inverter. 2. Connect output port to the inverter input. 3. Generate the circuit STG. Observed: An isolated elementary cycle is crested for inverter input pin. Expected behaviour: The STG for inverter input is redundant. Possible solutions: Option A: Forbid connections from output ports. Option B: Improve the STG conversion code.
d2b13a24b7254c7f5c94c4938b9f0b14048eb2a4
5be83c88a1db445bf71d12ced312227569a9bcd4
https://github.com/workcraft/workcraft/compare/d2b13a24b7254c7f5c94c4938b9f0b14048eb2a4...5be83c88a1db445bf71d12ced312227569a9bcd4
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java index dad9b787d..29d4d8b30 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java @@ -78,7 +78,8 @@ public class CircuitUtils { queue.addAll(circuit.getPreset(zeroDelayInput)); } else if (contact.isDriver()) { result = contact; - } else if (node == curNode) { + } else { + // Is it necessary to check that (node == curNode) before adding preset to queue? queue.addAll(circuit.getPreset(contact)); } } else { @@ -121,25 +122,27 @@ public class CircuitUtils { } while (!queue.isEmpty()) { Node node = queue.remove(); - if (!visited.contains(node)) { - visited.add(node); - if (node instanceof Joint) { - queue.addAll(circuit.getPostset(node)); - } else if (node instanceof Contact) { - Contact contact = (Contact) node; - // Support for zero-delay buffers and inverters. - Contact zeroDelayOutput = transparentZeroDelayComponents ? findZeroDelayOutput(contact) : null; - if (zeroDelayOutput != null) { - queue.addAll(circuit.getPostset(zeroDelayOutput)); - } else if (contact.isDriven()) { - result.add(contact); - } else if (node == curNode) { - queue.addAll(circuit.getPostset(contact)); - } + if (visited.contains(node)) { + continue; + } + visited.add(node); + if (node instanceof Joint) { + queue.addAll(circuit.getPostset(node)); + } else if (node instanceof Contact) { + Contact contact = (Contact) node; + // Support for zero-delay buffers and inverters. + Contact zeroDelayOutput = transparentZeroDelayComponents ? findZeroDelayOutput(contact) : null; + if (zeroDelayOutput != null) { + queue.addAll(circuit.getPostset(zeroDelayOutput)); + } else if (contact.isDriven()) { + result.add(contact); } else { - throw new RuntimeException("Unexpected node '" + circuit.getNodeReference(node) - + "' in the driven trace for node '" + circuit.getNodeReference(curNode) + "'!"); + // Is it necessary to check that (node == curNode) before adding postset to queue? + queue.addAll(circuit.getPostset(contact)); } + } else { + throw new RuntimeException("Unexpected node '" + circuit.getNodeReference(node) + + "' in the driven trace for node '" + circuit.getNodeReference(curNode) + "'!"); } } return result; diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java index d96b1a9ce..5bf14a320 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java @@ -41,12 +41,12 @@ import org.workcraft.plugins.petri.VisualPlace; import org.workcraft.plugins.stg.SignalTransition; import org.workcraft.plugins.stg.SignalTransition.Direction; import org.workcraft.plugins.stg.Stg; +import org.workcraft.plugins.stg.StgSettings; import org.workcraft.plugins.stg.VisualImplicitPlaceArc; import org.workcraft.plugins.stg.VisualSignalTransition; import org.workcraft.plugins.stg.VisualStg; import org.workcraft.plugins.stg.generator.SignalStg; import org.workcraft.util.Geometry; -import org.workcraft.util.Hierarchy; import org.workcraft.util.Pair; import org.workcraft.util.TwoWayMap; @@ -79,10 +79,11 @@ public class CircuitToStgConverter { this.driverToStgMap = convertDriversToStgs(drivers); connectDriverStgs(drivers); if (CircuitSettings.getSimplifyStg()) { - simplifyDriverStgs(drivers); // remove dead transitions + // Remove dead transitions + simplifyDriverStgs(drivers); } positionDriverStgs(drivers); - //groupDriverStgs(drivers); + groupDriverStgs(drivers); } public CircuitToStgConverter(VisualCircuit circuit, VisualStg stg) { @@ -91,12 +92,14 @@ public class CircuitToStgConverter { this.refToPageMap = convertPages(); HashSet<VisualContact> drivers = identifyDrivers(); this.nodeToDriverMap = associateNodesToDrivers(drivers); - this.driverToStgMap = associateDriversToStgs(drivers); // STGs already exist, just associate them with the drivers + // STGs already exist, just associate them with the drivers + this.driverToStgMap = associateDriversToStgs(drivers); if (CircuitSettings.getSimplifyStg()) { - simplifyDriverStgs(drivers); // remove dead transitions + // Remove dead transitions + simplifyDriverStgs(drivers); } positionDriverStgs(drivers); - //groupDriverStgs(drivers); + groupDriverStgs(drivers); } public VisualStg getStg() { @@ -152,7 +155,7 @@ public class CircuitToStgConverter { private HashSet<VisualContact> identifyDrivers() { HashSet<VisualContact> result = new HashSet<>(); - for (VisualContact contact : Hierarchy.getDescendantsOfType(circuit.getRoot(), VisualContact.class)) { + for (VisualContact contact : circuit.getVisualFunctionContacts()) { VisualContact driver = CircuitUtils.findDriver(circuit, contact); if (driver == null) { driver = contact; @@ -507,27 +510,32 @@ public class CircuitToStgConverter { } private void groupDriverStgs(HashSet<VisualContact> drivers) { - for (VisualContact driver: drivers) { - SignalStg signalStg = driverToStgMap.getValue(driver); - if (signalStg != null) { - Collection<Node> nodesToGroup = new LinkedList<>(); - nodesToGroup.addAll(signalStg.getAllNodes()); - - Container currentLevel = null; - Container oldLevel = stg.getCurrentLevel(); - for (Node node: nodesToGroup) { - if (currentLevel == null) { - currentLevel = (Container) node.getParent(); - } - if (currentLevel != node.getParent()) { - throw new RuntimeException("Current level is not the same among the processed nodes"); - } + if (StgSettings.getGroupSignalConversion()) { + for (VisualContact driver: drivers) { + SignalStg signalStg = driverToStgMap.getValue(driver); + groupSignalStg(signalStg); + } + } + } + + private void groupSignalStg(SignalStg signalStg) { + if ((signalStg != null) && StgSettings.getGroupSignalConversion()) { + Collection<Node> nodesToGroup = new LinkedList<>(); + nodesToGroup.addAll(signalStg.getAllNodes()); + Container currentLevel = null; + Container oldLevel = stg.getCurrentLevel(); + for (Node node: nodesToGroup) { + if (currentLevel == null) { + currentLevel = (Container) node.getParent(); + } + if (currentLevel != node.getParent()) { + throw new RuntimeException("Current level is not the same among the processed nodes"); } - stg.setCurrentLevel(currentLevel); - stg.select(nodesToGroup); - stg.groupSelection(); - stg.setCurrentLevel(oldLevel); } + stg.setCurrentLevel(currentLevel); + stg.select(nodesToGroup); + stg.groupSelection(); + stg.setCurrentLevel(oldLevel); } } diff --git a/StgPlugin/src/org/workcraft/plugins/stg/StgSettings.java b/StgPlugin/src/org/workcraft/plugins/stg/StgSettings.java index 2b4480ce8..3738aede4 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/StgSettings.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/StgSettings.java @@ -39,16 +39,19 @@ public class StgSettings implements Settings { private static final String keyDensityMapLevelLimit = prefix + ".densityMapLevelLimit"; private static final String keyLowLevelSuffix = prefix + ".lowLevelSuffix"; private static final String keyHighLevelSuffix = prefix + ".highLevelSuffix"; + private static final String keyGroupSignalConversion = prefix + ".groupSignalConversion"; private static final String keyConceptsFolderLocation = prefix + ".conceptsFolderLocation"; private static final Integer defaultDensityMapLevelLimit = 5; private static final String defaultLowLevelSuffix = "_LOW"; private static final String defaultHighLevelSuffix = "_HIGH"; + private static final Boolean defaultGroupSignalConversion = false; private static final String defaultConceptsFolderLocation = DesktopApi.getOs().isWindows() ? "tools\\\\concepts\\\\" : "tools/concepts/"; private static Integer densityMapLevelLimit = defaultDensityMapLevelLimit; private static String lowLevelSuffix = defaultLowLevelSuffix; private static String highLevelSuffix = defaultHighLevelSuffix; + private static Boolean groupSignalConversion = defaultGroupSignalConversion; private static String conceptsFolderLocation = defaultConceptsFolderLocation; public StgSettings() { @@ -96,6 +99,16 @@ public class StgSettings implements Settings { } }); + properties.add(new PropertyDeclaration<StgSettings, Boolean>( + this, "Group signals on conversion", Boolean.class, true, false, false) { + protected void setter(StgSettings object, Boolean value) { + setGroupSignalConversion(value); + } + protected Boolean getter(StgSettings object) { + return getGroupSignalConversion(); + } + }); + properties.add(new PropertyDeclaration<StgSettings, String>( this, "Concepts folder location", String.class, true, false, false) { protected void setter(StgSettings object, String value) { @@ -142,6 +155,7 @@ public class StgSettings implements Settings { setDensityMapLevelLimit(config.getInt(keyDensityMapLevelLimit, defaultDensityMapLevelLimit)); setLowLevelSuffix(config.getString(keyLowLevelSuffix, defaultLowLevelSuffix)); setHighLevelSuffix(config.getString(keyHighLevelSuffix, defaultHighLevelSuffix)); + setGroupSignalConversion(config.getBoolean(keyGroupSignalConversion, defaultGroupSignalConversion)); setConceptsFolderLocation(config.getString(keyConceptsFolderLocation, defaultConceptsFolderLocation)); } @@ -150,6 +164,7 @@ public class StgSettings implements Settings { config.setInt(keyDensityMapLevelLimit, getDensityMapLevelLimit()); config.set(keyLowLevelSuffix, getLowLevelSuffix()); config.set(keyHighLevelSuffix, getHighLevelSuffix()); + config.setBoolean(keyGroupSignalConversion, getGroupSignalConversion()); config.set(keyConceptsFolderLocation, getConceptsFolderLocation()); } @@ -191,6 +206,14 @@ public class StgSettings implements Settings { } } + public static Boolean getGroupSignalConversion() { + return groupSignalConversion; + } + + public static void setGroupSignalConversion(Boolean value) { + groupSignalConversion = value; + } + public static String getConceptsFolderLocation() { return conceptsFolderLocation; } diff --git a/StgPlugin/src/org/workcraft/plugins/stg/generator/StgGenerator.java b/StgPlugin/src/org/workcraft/plugins/stg/generator/StgGenerator.java index 3ba234751..50ccb44af 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/generator/StgGenerator.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/generator/StgGenerator.java @@ -20,6 +20,7 @@ import org.workcraft.exceptions.InvalidConnectionException; import org.workcraft.plugins.petri.VisualPlace; import org.workcraft.plugins.petri.VisualReplicaPlace; import org.workcraft.plugins.stg.Stg; +import org.workcraft.plugins.stg.StgSettings; import org.workcraft.plugins.stg.SignalTransition; import org.workcraft.plugins.stg.VisualStg; import org.workcraft.plugins.stg.VisualSignalTransition; @@ -281,8 +282,10 @@ public abstract class StgGenerator { } public void groupComponentStg(NodeStg nodeStg) { - stg.select(nodeStg.getAllNodes()); - stg.groupSelection(); + if (StgSettings.getGroupSignalConversion()) { + stg.select(nodeStg.getAllNodes()); + stg.groupSelection(); + } } }
['CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitUtils.java', 'StgPlugin/src/org/workcraft/plugins/stg/StgSettings.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/stg/CircuitToStgConverter.java', 'StgPlugin/src/org/workcraft/plugins/stg/generator/StgGenerator.java']
{'.java': 4}
4
4
0
0
4
4,957,689
1,008,188
139,157
1,302
6,770
1,235
129
4
414
63
90
14
0
0
"1970-01-01T00:24:40"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
766
workcraft/workcraft/612/602
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/602
https://github.com/workcraft/workcraft/pull/612
https://github.com/workcraft/workcraft/pull/612
1
fixes
Inconsistent state of global settings
To reproduce, run Workcraft with the following script: ``` workcraft -nogui -exec:<(echo "setConfigVar(\\"CircuitSettings.gateLibrary\\", \\"libraries/test.lib\\");; exit();") ``` Examine the saved `~/.config/workcraft/config.xml` file. The `gateLibrary` variable in `CircuitSettings` group is still set to 'libraries/workcraft.lib' instead of the expected 'libraries/test.lib'. The reason for this inconsistency is that plugins often cache the original config settings into local variables, and then only track the changes of settings via GUI. On exit plugins write these variables back into config dictionary, thus overwriting all the changes performed via `setConfigVar` interface. Option 1 (did not work): Use config dictionary as the only storage for global settings, without caching them in plugins. This did not work because other config dictionaries are also used for resetting to default settings. Option 2: Update plugin settings on every use of `setConfigVar` and re-read plugin settings on every `getConfigVar`.
7d9d08b09793382ac6bea8ad629fdaa153e34e3e
0a19fb635a25a6f0c760e12cf615d056168abf5c
https://github.com/workcraft/workcraft/compare/7d9d08b09793382ac6bea8ad629fdaa153e34e3e...0a19fb635a25a6f0c760e12cf615d056168abf5c
diff --git a/WorkcraftCore/src/org/workcraft/Framework.java b/WorkcraftCore/src/org/workcraft/Framework.java index c326e21b0..b986bfbf2 100644 --- a/WorkcraftCore/src/org/workcraft/Framework.java +++ b/WorkcraftCore/src/org/workcraft/Framework.java @@ -239,65 +239,57 @@ public final class Framework { return instance; } - public void resetConfig() { - config = new Config(); + private void loadConfigPlugins() { for (PluginInfo<? extends Settings> info : pluginManager.getPlugins(Settings.class)) { info.getSingleton().load(config); } } + private void saveConfigPlugins() { + for (PluginInfo<? extends Settings> info : pluginManager.getPlugins(Settings.class)) { + info.getSingleton().save(config); + } + } + + public void resetConfig() { + config = new Config(); + loadConfigPlugins(); + } + public void loadConfig() { File file = new File(CONFIG_FILE_PATH); LogUtils.logMessageLine("Loading global preferences from " + file.getAbsolutePath()); config.load(file); - for (PluginInfo<? extends Settings> info : pluginManager.getPlugins(Settings.class)) { - info.getSingleton().load(config); - } + loadConfigPlugins(); } public void saveConfig() { - for (PluginInfo<? extends Settings> info : pluginManager.getPlugins(Settings.class)) { - info.getSingleton().save(config); - } + saveConfigPlugins(); File file = new File(CONFIG_FILE_PATH); LogUtils.logMessageLine("Saving global preferences to " + file.getAbsolutePath()); config.save(file); } - public void setConfigVar(String key, String value) { + public void setConfigCoreVar(String key, String value) { + // Set a core variable, that does not require updating plugin settings. config.set(key, value); } - public void setConfigVar(String key, int value) { - config.set(key, Integer.toString(value)); - } - - public void setConfigVar(String key, boolean value) { - config.set(key, Boolean.toString(value)); + public void setConfigVar(String key, String value) { + setConfigCoreVar(key, value); + // For consistency, update plugin settings. + loadConfigPlugins(); } - public String getConfigVar(String key) { + public String getConfigCoreVar(String key) { + // Get a core variable, that does not require flushing plugin settings. return config.get(key); } - public int getConfigVarAsInt(String key, int defaultValue) { - String s = config.get(key); - - try { - return Integer.parseInt(s); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - public boolean getConfigVarAsBool(String key, boolean defaultValue) { - String s = config.get(key); - - if (s == null) { - return defaultValue; - } else { - return Boolean.parseBoolean(s); - } + public String getConfigVar(String key) { + // For consistency, flush plugin settings. + saveConfigPlugins(); + return getConfigCoreVar(key); } public String[] getModelNames() { @@ -341,11 +333,9 @@ public final class Framework { public Object run(Context arg0) { Object scriptable = Context.javaToJS(object, scope); ScriptableObject.putProperty(scope, name, scriptable); - if (readOnly) { scope.setAttributes(name, ScriptableObject.READONLY); } - return scriptable; } }); @@ -357,7 +347,6 @@ public final class Framework { return ScriptableObject.deleteProperty(scope, name); } }); - } public Object execJavaScript(File file) throws FileNotFoundException { @@ -380,7 +369,8 @@ public final class Framework { @Override public String getMessage() { - return String.format("Java %s was unhandled in javascript. \\nJavascript stack trace: %s", getCause().getClass().getSimpleName(), getScriptTrace()); + return String.format("Java %s was unhandled in javascript. \\nJavascript stack trace: %s", + getCause().getClass().getSimpleName(), getScriptTrace()); } public String getScriptTrace() { diff --git a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java index 1ce606746..bc0960b84 100644 --- a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java @@ -654,9 +654,9 @@ public class MainWindow extends JFrame { public void loadWindowGeometryFromConfig() { final Framework framework = Framework.getInstance(); - String maximisedStr = framework.getConfigVar(CONFIG_GUI_MAIN_MAXIMISED); - String widthStr = framework.getConfigVar(CONFIG_GUI_MAIN_WIDTH); - String heightStr = framework.getConfigVar(CONFIG_GUI_MAIN_HEIGHT); + String maximisedStr = framework.getConfigCoreVar(CONFIG_GUI_MAIN_MAXIMISED); + String widthStr = framework.getConfigCoreVar(CONFIG_GUI_MAIN_WIDTH); + String heightStr = framework.getConfigCoreVar(CONFIG_GUI_MAIN_HEIGHT); boolean maximised = (maximisedStr == null) ? true : Boolean.parseBoolean(maximisedStr); this.setExtendedState(maximised ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL); @@ -685,17 +685,17 @@ public class MainWindow extends JFrame { public void saveWindowGeometryToConfig() { final Framework framework = Framework.getInstance(); boolean maximised = (getExtendedState() & JFrame.MAXIMIZED_BOTH) != 0; - framework.setConfigVar(CONFIG_GUI_MAIN_MAXIMISED, Boolean.toString(maximised)); - framework.setConfigVar(CONFIG_GUI_MAIN_WIDTH, Integer.toString(getWidth())); - framework.setConfigVar(CONFIG_GUI_MAIN_HEIGHT, Integer.toString(getHeight())); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_MAXIMISED, Boolean.toString(maximised)); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_WIDTH, Integer.toString(getWidth())); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_HEIGHT, Integer.toString(getHeight())); } public void loadRecentFilesFromConfig() { final Framework framework = Framework.getInstance(); - lastSavePath = framework.getConfigVar(CONFIG_GUI_MAIN_LAST_SAVE_PATH); - lastOpenPath = framework.getConfigVar(CONFIG_GUI_MAIN_LAST_OPEN_PATH); + lastSavePath = framework.getConfigCoreVar(CONFIG_GUI_MAIN_LAST_SAVE_PATH); + lastOpenPath = framework.getConfigCoreVar(CONFIG_GUI_MAIN_LAST_OPEN_PATH); for (int i = 0; i < CommonEditorSettings.getRecentCount(); i++) { - String entry = framework.getConfigVar(CONFIG_GUI_MAIN_RECENT_FILE + i); + String entry = framework.getConfigCoreVar(CONFIG_GUI_MAIN_RECENT_FILE + i); pushRecentFile(entry, false); } updateRecentFilesMenu(); @@ -704,15 +704,15 @@ public class MainWindow extends JFrame { public void saveRecentFilesToConfig() { final Framework framework = Framework.getInstance(); if (lastSavePath != null) { - framework.setConfigVar(CONFIG_GUI_MAIN_LAST_SAVE_PATH, lastSavePath); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_LAST_SAVE_PATH, lastSavePath); } if (lastOpenPath != null) { - framework.setConfigVar(CONFIG_GUI_MAIN_LAST_OPEN_PATH, lastOpenPath); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_LAST_OPEN_PATH, lastOpenPath); } int recentCount = CommonEditorSettings.getRecentCount(); String[] tmp = recentFiles.toArray(new String[recentCount]); for (int i = 0; i < recentCount; i++) { - framework.setConfigVar(CONFIG_GUI_MAIN_RECENT_FILE + i, tmp[i]); + framework.setConfigCoreVar(CONFIG_GUI_MAIN_RECENT_FILE + i, tmp[i]); } } diff --git a/WorkcraftCore/src/org/workcraft/gui/workspace/WorkspaceWindow.java b/WorkcraftCore/src/org/workcraft/gui/workspace/WorkspaceWindow.java index 6257140a4..b43673234 100644 --- a/WorkcraftCore/src/org/workcraft/gui/workspace/WorkspaceWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/workspace/WorkspaceWindow.java @@ -141,17 +141,17 @@ public class WorkspaceWindow extends JPanel { setLayout(new BorderLayout(0, 0)); this.add(scrollPane, BorderLayout.CENTER); - lastSavePath = framework.getConfigVar("gui.workspace.lastSavePath"); - lastOpenPath = framework.getConfigVar("gui.workspace.lastOpenPath"); + lastSavePath = framework.getConfigCoreVar("gui.workspace.lastSavePath"); + lastOpenPath = framework.getConfigCoreVar("gui.workspace.lastOpenPath"); } public void shutdown() { final Framework framework = Framework.getInstance(); if (lastSavePath != null) { - framework.setConfigVar("gui.workspace.lastSavePath", lastSavePath); + framework.setConfigCoreVar("gui.workspace.lastSavePath", lastSavePath); } if (lastOpenPath != null) { - framework.setConfigVar("gui.workspace.lastOpenPath", lastOpenPath); + framework.setConfigCoreVar("gui.workspace.lastOpenPath", lastOpenPath); } }
['WorkcraftCore/src/org/workcraft/Framework.java', 'WorkcraftCore/src/org/workcraft/gui/workspace/WorkspaceWindow.java', 'WorkcraftCore/src/org/workcraft/gui/MainWindow.java']
{'.java': 3}
3
3
0
0
3
4,957,782
1,008,207
139,167
1,302
5,252
1,010
98
3
1,032
136
219
11
0
1
"1970-01-01T00:24:39"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
767
workcraft/workcraft/606/605
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/605
https://github.com/workcraft/workcraft/pull/606
https://github.com/workcraft/workcraft/pull/606
1
fixed
Right-click (two-finger click) doesn't work on Mac trackpad.
Please answer these questions before submitting your issue. Thanks! 1. What version of Workcraft are you using? 3.1.2 master from tuura/workcraft 2. What operating system are you using? macOS 12 Sierra I am unsure whether this is because I updated my mac. I have looked into how right-click works on macs, and it appears that right-click works in the same way for all macs using the trackpad. 3. What did you do? If possible, provide a list of steps to reproduce the error. Tried to right-click a gate in the Digital Circuit plugin in order to add a new input. 4. What did you expect to see? A popup menu 5. What did you see instead? Nothing
6e659bb47caa8c6c855e309122b65b6c5a271bc9
34a928e2c292292ef7a84ba97043486ef9bbc047
https://github.com/workcraft/workcraft/compare/6e659bb47caa8c6c855e309122b65b6c5a271bc9...34a928e2c292292ef7a84ba97043486ef9bbc047
diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelMouseListener.java b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelMouseListener.java index 5b7943238..1dd28ce2e 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelMouseListener.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelMouseListener.java @@ -92,9 +92,7 @@ class GraphEditorPanelMouseListener implements MouseMotionListener, MouseListene final MainWindow mainWindow = framework.getMainWindow(); mainWindow.requestFocus(editor); } - if (!isPanCombo(e)) { - toolProvider.getSelectedTool().mouseClicked(adaptEvent(e)); - } + toolProvider.getSelectedTool().mouseClicked(adaptEvent(e)); } @Override
['WorkcraftCore/src/org/workcraft/gui/graph/GraphEditorPanelMouseListener.java']
{'.java': 1}
1
1
0
0
1
4,936,525
1,003,685
138,578
1,300
183
37
4
1
668
117
159
20
0
0
"1970-01-01T00:24:38"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
768
workcraft/workcraft/598/597
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/597
https://github.com/workcraft/workcraft/pull/598
https://github.com/workcraft/workcraft/pull/598
1
fixes
Petrify issue if installed in a non-user-writable directory
Using Workcraft V3.1.2 on Arch Linux. With a basic STG, selecting `Tools -> External visualizer -> State graph ({basic,binary-coded})` fails when the directory `workcraft/Tools/PetrifyTools` is not writable by the user who invoked `workcraft`. The error is: > Petrify tool chain execution failed. > > Errors running draw_astg: > **\\* FATAL ERROR: opening tmp file <draw_astg_xxxxxx> A zero-size pdf is produced by draw_astg in the tmp directory. Using `strace` it seems that Petrify's `write_sg` does not finish writing the .sg file before `draw_astg` is called under these conditions. I'm not sure if this is something to do with Petrify being unable to write its log file (which should reside in the unwritable directory I believe). I have not found this to happen for any other Petrify task such as from the `verification` or `conversion` menus under these conditions. The tasks stated above seem to be the only ones which perform two Petrify operations with the second depending on the first (at least when working with an STG). This came to my attention when packaging Workcraft where the files will normally reside in `/opt` or `/usr/share` which are owned root:root with 755 permissions (ie. not writable by a normal user who would invoke `workcraft`). In this situation, allowing write permissions for "other" would not be a permissible solution.
2705569e76b732d633777da68a38acbbe31f2226
47aa852e2101584917e256bbbf10a6323363e918
https://github.com/workcraft/workcraft/compare/2705569e76b732d633777da68a38acbbe31f2226...47aa852e2101584917e256bbbf10a6323363e918
diff --git a/FstPlugin/src/org/workcraft/plugins/fst/task/WriteSgConversionTask.java b/FstPlugin/src/org/workcraft/plugins/fst/task/WriteSgConversionTask.java index 08cf8b9e1..44251be2d 100644 --- a/FstPlugin/src/org/workcraft/plugins/fst/task/WriteSgConversionTask.java +++ b/FstPlugin/src/org/workcraft/plugins/fst/task/WriteSgConversionTask.java @@ -105,7 +105,7 @@ public class WriteSgConversionTask implements Task<WriteSgConversionResult> { } while (true) { - WriteSgTask writeSgTask = new WriteSgTask(petriFile.getAbsolutePath(), null, writeSgOptions); + WriteSgTask writeSgTask = new WriteSgTask(writeSgOptions, petriFile, null, null); Result<? extends ExternalProcessResult> writeSgResult = framework.getTaskManager().execute( writeSgTask, "Building state graph", subtaskMonitor); diff --git a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/AstgExporter.java b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/AstgExporter.java index 4606882c2..a65f63f86 100644 --- a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/AstgExporter.java +++ b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/AstgExporter.java @@ -82,7 +82,7 @@ public class AstgExporter implements Exporter { File resultFile = new File(directory, RESULT_FILE_NAME); - DrawAstgTask task = new DrawAstgTask(stgFile.getAbsolutePath(), resultFile.getAbsolutePath(), new ArrayList<String>()); + DrawAstgTask task = new DrawAstgTask(new ArrayList<String>(), stgFile, resultFile, directory); final Result<? extends ExternalProcessResult> drawAstgResult = framework.getTaskManager().execute(task, "Executing Petrify"); diff --git a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawAstgTask.java b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawAstgTask.java index 586739c50..12c3dce7e 100644 --- a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawAstgTask.java +++ b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawAstgTask.java @@ -1,5 +1,6 @@ package org.workcraft.plugins.petrify.tasks; +import java.io.File; import java.util.ArrayList; import java.util.List; @@ -13,13 +14,16 @@ import org.workcraft.tasks.Task; import org.workcraft.util.ToolUtils; public class DrawAstgTask implements Task<ExternalProcessResult> { - private final String inputPath, outputPath; private final List<String> options; + private final File inputFile; + private final File outputFile; + private final File workingDirectory; - public DrawAstgTask(String inputPath, String outputPath, List<String> options) { - this.inputPath = inputPath; - this.outputPath = outputPath; + public DrawAstgTask(List<String> options, File inputFile, File outputFile, File workingDirectory) { this.options = options; + this.inputFile = inputFile; + this.outputFile = outputFile; + this.workingDirectory = workingDirectory; } @Override @@ -36,13 +40,17 @@ public class DrawAstgTask implements Task<ExternalProcessResult> { } // Input file - command.add(inputPath); + if (inputFile != null) { + command.add(inputFile.getAbsolutePath()); + } // Output file - command.add("-o"); - command.add(outputPath); + if (outputFile != null) { + command.add("-o"); + command.add(outputFile.getAbsolutePath()); + } - ExternalProcessTask task = new ExternalProcessTask(command, null); + ExternalProcessTask task = new ExternalProcessTask(command, workingDirectory); Result<? extends ExternalProcessResult> res = task.run(monitor); if (res.getOutcome() != Outcome.FINISHED) { diff --git a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawSgTask.java b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawSgTask.java index a639f68d1..245ba2d0e 100644 --- a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawSgTask.java +++ b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawSgTask.java @@ -96,7 +96,7 @@ public class DrawSgTask implements Task<DrawSgResult> { writeSgOptions.add("-bin"); } while (true) { - WriteSgTask writeSgTask = new WriteSgTask(stgFile.getAbsolutePath(), sgFile.getAbsolutePath(), writeSgOptions); + WriteSgTask writeSgTask = new WriteSgTask(writeSgOptions, stgFile, sgFile, directory); Result<? extends ExternalProcessResult> writeSgResult = framework.getTaskManager().execute( writeSgTask, "Running Petrify"); @@ -133,7 +133,7 @@ public class DrawSgTask implements Task<DrawSgResult> { if (binary) { drawAstgOptions.add("-bin"); } - DrawAstgTask drawAstgTask = new DrawAstgTask(sgFile.getAbsolutePath(), resultFile.getAbsolutePath(), drawAstgOptions); + DrawAstgTask drawAstgTask = new DrawAstgTask(drawAstgOptions, sgFile, resultFile, directory); final Result<? extends ExternalProcessResult> drawAstgResult = framework.getTaskManager().execute(drawAstgTask, "Running Petrify"); if (drawAstgResult.getOutcome() != Outcome.FINISHED) { diff --git a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/WriteSgTask.java b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/WriteSgTask.java index d8401b526..a879434ee 100644 --- a/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/WriteSgTask.java +++ b/PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/WriteSgTask.java @@ -1,5 +1,6 @@ package org.workcraft.plugins.petrify.tasks; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -16,18 +17,21 @@ import org.workcraft.util.DataAccumulator; import org.workcraft.util.ToolUtils; public class WriteSgTask implements Task<ExternalProcessResult>, ExternalProcessListener { - private final String inputPath, outputPath; private final List<String> options; + private final File inputFile; + private final File outputFile; + private final File workingDirectory; private ProgressMonitor<? super ExternalProcessResult> monitor; private final DataAccumulator stdoutAccum = new DataAccumulator(); private final DataAccumulator stderrAccum = new DataAccumulator(); - public WriteSgTask(String inputPath, String outputPath, List<String> options) { - this.inputPath = inputPath; - this.outputPath = outputPath; + public WriteSgTask(List<String> options, File inputFile, File outputFile, File workingDirectory) { this.options = options; + this.inputFile = inputFile; + this.outputFile = outputFile; + this.workingDirectory = workingDirectory; } @Override @@ -47,17 +51,17 @@ public class WriteSgTask implements Task<ExternalProcessResult>, ExternalProcess } // Input file - if ((inputPath != null) && !inputPath.isEmpty()) { - command.add(inputPath); + if (inputFile != null) { + command.add(inputFile.getAbsolutePath()); } // Output file - if ((outputPath != null) && !outputPath.isEmpty()) { + if (outputFile != null) { command.add("-o"); - command.add(outputPath); + command.add(outputFile.getAbsolutePath()); } - ExternalProcessTask task = new ExternalProcessTask(command, null); + ExternalProcessTask task = new ExternalProcessTask(command, workingDirectory); Result<? extends ExternalProcessResult> res = task.run(monitor); if (res.getOutcome() != Outcome.FINISHED) { return res; diff --git a/WorkcraftCore/src/org/workcraft/Info.java b/WorkcraftCore/src/org/workcraft/Info.java index a63f2702d..cc733d205 100644 --- a/WorkcraftCore/src/org/workcraft/Info.java +++ b/WorkcraftCore/src/org/workcraft/Info.java @@ -12,8 +12,8 @@ public class Info { private static final int majorVersion = 3; private static final int minorVersion = 1; - private static final int revisionVersion = 2; - private static final String statusVersion = null; // "alpha", "beta", "rc1", null (for release) + private static final int revisionVersion = 3; + private static final String statusVersion = "alpha"; // "alpha", "beta", "rc1", null (for release) private static final int startYear = 2006; private static final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
['PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawAstgTask.java', 'PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/AstgExporter.java', 'FstPlugin/src/org/workcraft/plugins/fst/task/WriteSgConversionTask.java', 'PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/DrawSgTask.java', 'WorkcraftCore/src/org/workcraft/Info.java', 'PetrifyExtraPlugin/src/org/workcraft/plugins/petrify/tasks/WriteSgTask.java']
{'.java': 6}
6
6
0
0
6
4,936,044
1,003,590
138,566
1,300
3,404
711
58
6
1,361
216
314
15
0
0
"1970-01-01T00:24:36"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
778
workcraft/workcraft/377/355
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/355
https://github.com/workcraft/workcraft/pull/377
https://github.com/workcraft/workcraft/pull/377
1
fixes
Position implicit place token in the middle of the polyline segment
If the transitions connected by an arc (with implicit place) have significantly different name length, then a token on that arc would appear closer to the transition with the longer name. This happens because the connection start and end point are considered as the the centres of the adjacent nodes. Instead the intersection with their bounding boxes should be taken as the start and end points.
a90083fae09e8aaffcb819fdc1bd63cfdfc83ffd
417453033303ab63c913c91ed4d4fbf32f44b4f9
https://github.com/workcraft/workcraft/compare/a90083fae09e8aaffcb819fdc1bd63cfdfc83ffd...417453033303ab63c913c91ed4d4fbf32f44b4f9
diff --git a/STGPlugin/src/org/workcraft/plugins/stg/VisualImplicitPlaceArc.java b/STGPlugin/src/org/workcraft/plugins/stg/VisualImplicitPlaceArc.java index c8393fa56..3ed21ea4f 100644 --- a/STGPlugin/src/org/workcraft/plugins/stg/VisualImplicitPlaceArc.java +++ b/STGPlugin/src/org/workcraft/plugins/stg/VisualImplicitPlaceArc.java @@ -121,7 +121,7 @@ public class VisualImplicitPlaceArc extends VisualConnection { public void draw(DrawRequest r) { super.draw(r); int tokens = implicitPlace.getTokens(); - Point2D p = getPointOnConnection(0.5); + Point2D p = getMiddleSegmentCenterPoint(); Graphics2D g = r.getGraphics(); g.translate(p.getX(), p.getY()); VisualPlace.drawTokens(r, tokens, singleTokenSize, multipleTokenSeparation, tokenSpaceSize, 0, tokenColor); diff --git a/WorkcraftCore/src/org/workcraft/dom/visual/connections/Polyline.java b/WorkcraftCore/src/org/workcraft/dom/visual/connections/Polyline.java index 12567e18f..07d4bf767 100644 --- a/WorkcraftCore/src/org/workcraft/dom/visual/connections/Polyline.java +++ b/WorkcraftCore/src/org/workcraft/dom/visual/connections/Polyline.java @@ -106,13 +106,13 @@ public class Polyline implements ConnectionGraphic, Container, StateObserver, g.draw(connectionPath); if (connectionInfo.hasArrow()) { - DrawHelper.drawArrowHead(g, curveInfo.headPosition, curveInfo.headOrientation, + DrawHelper.drawArrowHead(g, curveInfo.headPosition, curveInfo.headOrientation, connectionInfo.getArrowLength(), connectionInfo.getArrowWidth(), color); } if (connectionInfo.hasBubble()) { DrawHelper.drawBubbleHead(g, curveInfo.headPosition, curveInfo.headOrientation, - connectionInfo.getBubbleSize(), color, connectionInfo.getStroke()); + connectionInfo.getBubbleSize(), color, connectionInfo.getStroke()); } } diff --git a/WorkcraftCore/src/org/workcraft/dom/visual/connections/VisualConnection.java b/WorkcraftCore/src/org/workcraft/dom/visual/connections/VisualConnection.java index 3417400d1..1d3714c3a 100644 --- a/WorkcraftCore/src/org/workcraft/dom/visual/connections/VisualConnection.java +++ b/WorkcraftCore/src/org/workcraft/dom/visual/connections/VisualConnection.java @@ -429,7 +429,19 @@ public class VisualConnection extends VisualNode implements Node, Drawable, Shap @NoAutoSerialisation public Point2D getSplitPoint() { - return (splitPoint == null) ? getPointOnConnection(0.5) : splitPoint; + return (splitPoint == null) ? getMiddleSegmentCenterPoint() : splitPoint; + } + + public Point2D getMiddleSegmentCenterPoint() { + double k = 0.5; + ConnectionGraphic graphic = getGraphic(); + boolean isSingleSegmentPolyline = (graphic instanceof Polyline) + && (((Polyline) graphic).getSegmentCount() == 1); + if ((graphic instanceof Bezier) || isSingleSegmentPolyline) { + PartialCurveInfo curveInfo = graphic.getCurveInfo(); + k = 0.5 * (curveInfo.tStart + curveInfo.tEnd); + } + return getPointOnConnection(k); } public Point2D getPointOnConnection(double t) {
['WorkcraftCore/src/org/workcraft/dom/visual/connections/Polyline.java', 'STGPlugin/src/org/workcraft/plugins/stg/VisualImplicitPlaceArc.java', 'WorkcraftCore/src/org/workcraft/dom/visual/connections/VisualConnection.java']
{'.java': 3}
3
3
0
0
3
5,257,466
1,103,980
151,842
1,301
1,153
252
20
3
398
66
73
2
0
0
"1970-01-01T00:24:16"
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
709
phac-nml/irida/245/222
phac-nml
irida
https://github.com/phac-nml/irida/issues/222
https://github.com/phac-nml/irida/pull/245
https://github.com/phac-nml/irida/pull/245
1
fixes
Synchronizing projects with metadata does not work
In our latest `development` branch, if I try to sync a project where samples have metadata assigned (e.g., derived from a pipeline) I will get the following exception: ``` 14 Dec 2018 13:40:06,639 DEBUG ca.corefacility.bioinformatics.irida.service.remote.ProjectSynchronizationService:151 - An error occurred while synchronizing project http://localhost:8080/api/projects/3 org.springframework.orm.ObjectRetrievalFailureException: Object [id=null] was not of the specified subclass [ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry] : class of the given object did not match class of persistent copy; nested exception is org. hibernate.WrongClassException: Object [id=null] was not of the specified subclass [ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry] : class of the given object did not match class of persistent copy at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:294) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:225) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) at com.sun.proxy.$Proxy161.save(Unknown Source) at ca.corefacility.bioinformatics.irida.service.impl.CRUDServiceImpl.update(CRUDServiceImpl.java:223) at ca.corefacility.bioinformatics.irida.service.impl.sample.SampleServiceImpl.update(SampleServiceImpl.java:172) at ca.corefacility.bioinformatics.irida.service.impl.sample.SampleServiceImpl.update(SampleServiceImpl.java:67) at ca.corefacility.bioinformatics.irida.service.impl.sample.SampleServiceImpl$$FastClassBySpringCGLIB$$9792ab2e.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:718) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:654) at ca.corefacility.bioinformatics.irida.service.impl.sample.SampleServiceImpl$$EnhancerBySpringCGLIB$$89119358.update(<generated>) at ca.corefacility.bioinformatics.irida.service.remote.ProjectSynchronizationService.syncSample(ProjectSynchronizationService.java:287) at ca.corefacility.bioinformatics.irida.service.remote.ProjectSynchronizationService.syncProject(ProjectSynchronizationService.java:243) at ca.corefacility.bioinformatics.irida.service.remote.ProjectSynchronizationService.findMarkedProjectsToSync(ProjectSynchronizationService.java:143) at ca.corefacility.bioinformatics.irida.config.services.scheduled.ProjectSyncScheduledTaskConfig.syncProject(ProjectSyncScheduledTaskConfig.java:27) ... ```
061febba909d0a203f8a5988d992799a58bdfe8d
4004923eff53d5309db0d6465ddd2774a05fef58
https://github.com/phac-nml/irida/compare/061febba909d0a203f8a5988d992799a58bdfe8d...4004923eff53d5309db0d6465ddd2774a05fef58
diff --git a/src/main/java/ca/corefacility/bioinformatics/irida/model/sample/metadata/MetadataEntry.java b/src/main/java/ca/corefacility/bioinformatics/irida/model/sample/metadata/MetadataEntry.java index 9878c7d751..5d602d9a53 100644 --- a/src/main/java/ca/corefacility/bioinformatics/irida/model/sample/metadata/MetadataEntry.java +++ b/src/main/java/ca/corefacility/bioinformatics/irida/model/sample/metadata/MetadataEntry.java @@ -54,7 +54,11 @@ public class MetadataEntry { public void setValue(String value) { this.value = value; } - + + public void setId(Long id) { + this.id = id; + } + public Long getId() { return id; } diff --git a/src/main/java/ca/corefacility/bioinformatics/irida/service/remote/ProjectSynchronizationService.java b/src/main/java/ca/corefacility/bioinformatics/irida/service/remote/ProjectSynchronizationService.java index d2dd424501..13e3c8d0af 100644 --- a/src/main/java/ca/corefacility/bioinformatics/irida/service/remote/ProjectSynchronizationService.java +++ b/src/main/java/ca/corefacility/bioinformatics/irida/service/remote/ProjectSynchronizationService.java @@ -361,6 +361,9 @@ public class ProjectSynchronizationService { */ public Sample syncSampleMetadata(Sample sample){ Map<String, MetadataEntry> sampleMetadata = sampleRemoteService.getSampleMetadata(sample); + + sampleMetadata.values().forEach(e -> e.setId(null)); + Map<MetadataTemplateField, MetadataEntry> metadata = metadataTemplateService.getMetadataMap(sampleMetadata); sample.setMetadata(metadata);
['src/main/java/ca/corefacility/bioinformatics/irida/model/sample/metadata/MetadataEntry.java', 'src/main/java/ca/corefacility/bioinformatics/irida/service/remote/ProjectSynchronizationService.java']
{'.java': 2}
2
2
0
0
2
2,172,644
470,184
63,685
552
122
33
9
2
4,703
156
919
38
1
1
"1970-01-01T00:25:46"
40
Java
{'Java': 5148223, 'JavaScript': 876296, 'TypeScript': 447025, 'HTML': 41041, 'CSS': 21537, 'Kotlin': 19654, 'Shell': 13267, 'Python': 11481, 'Perl': 6980, 'Dockerfile': 4941}
Apache License 2.0
1,190
ibi-group/datatools-server/307/306
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/306
https://github.com/ibi-group/datatools-server/pull/307
https://github.com/ibi-group/datatools-server/pull/307
1
fix
Bug report: MTC feed merge
From MTC: > Production TDM's Merge functionality is not following [rule number 5 defined in user docs](https://mtc-datatools.readthedocs.io/en/mtc-docs/user/merging-feeds/#merge-rules). Two feeds with same service_id and overlapping dates are merged but the start and end dates are not updated. Attached are sample feeds for reference. > > Please investigate the issue and help us provide a fix. Input datasets: [Livermore_Amador_Valley_Transit_Authority-current.zip](https://github.com/ibi-group/datatools-server/files/4583453/Livermore_Amador_Valley_Transit_Authority-current.zip) [Livermore_Amador_Valley_Transit_Authority-Future-2020May-01.zip](https://github.com/ibi-group/datatools-server/files/4583452/Livermore_Amador_Valley_Transit_Authority-Future-2020May-01.zip) The merged result calendar.txt should have records with prefixed service_ids `Livermore_Amador_Valley_Transit_Authority30` that have end_dates of May 3rd (but they are showing June 14th).
4d110f9077c92c5885e5a3cd9488f772241d31da
1c3c1caef92ea9f5643ddc2c2261f51838df9cb7
https://github.com/ibi-group/datatools-server/compare/4d110f9077c92c5885e5a3cd9488f772241d31da...1c3c1caef92ea9f5643ddc2c2261f51838df9cb7
diff --git a/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java b/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java index 1279464e..3770f435 100644 --- a/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java +++ b/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java @@ -508,7 +508,9 @@ public class MergeFeedsJob extends MonitorableJob { // Get index of field from GTFS spec as it appears in feed int index = fieldsFoundList.indexOf(field); String val = csvReader.get(index); - // Default value to write is unchanged from value found in csv. + // Default value to write is unchanged from value found in csv (i.e. val). Note: if looking to + // modify the value that is written in the merged file, you must update valueToWrite (e.g., + // updating the current feed's end_date or accounting for cases where IDs conflict). String valueToWrite = val; // Handle filling in agency_id if missing when merging regional feeds. if (newAgencyId != null && field.name.equals("agency_id") && mergeType @@ -615,10 +617,9 @@ public class MergeFeedsJob extends MonitorableJob { getFieldIndex(fieldsFoundInZip, "end_date"); if (index == endDateIndex) { LocalDate endDate = LocalDate - .parse(csvReader.get(endDateIndex), - GTFS_DATE_FORMATTER); + .parse(csvReader.get(endDateIndex), GTFS_DATE_FORMATTER); if (!endDate.isBefore(futureFeedFirstDate)) { - val = futureFeedFirstDate + val = valueToWrite = futureFeedFirstDate .minus(1, ChronoUnit.DAYS) .format(GTFS_DATE_FORMATTER); } diff --git a/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java b/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java index dd4a8226..26d97f1d 100644 --- a/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java +++ b/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java @@ -23,6 +23,7 @@ import java.util.UUID; import static com.conveyal.datatools.TestUtils.assertThatFeedHasNoErrorsOfType; import static com.conveyal.datatools.TestUtils.assertThatSqlCountQueryYieldsExpectedCount; +import static com.conveyal.datatools.TestUtils.assertThatSqlQueryYieldsRowCount; import static com.conveyal.datatools.TestUtils.createFeedVersion; import static com.conveyal.datatools.TestUtils.createFeedVersionFromGtfsZip; import static com.conveyal.datatools.TestUtils.zipFolderFiles; @@ -523,7 +524,6 @@ public class MergeFeedsJobTest extends UnitTest { * Tests whether a MTC feed merge of two feed versions correctly removes calendar records that have overlapping * service but keeps calendar_dates records that share service_id with the removed calendar and trips that reference * that service_id. - * */ @Test public void canMergeFeedsWithMTCForServiceIds3 () throws SQLException { @@ -563,6 +563,15 @@ public class MergeFeedsJobTest extends UnitTest { ), 1 ); + // Amended calendar record from earlier feed version should also have a modified end date (one day before the + // earliest start_date from the future feed). + assertThatSqlCountQueryYieldsExpectedCount( + String.format( + "SELECT count(*) FROM %s.calendar WHERE service_id='Fake_Agency4:common_id' AND end_date='20170914'", + mergedNamespace + ), + 1 + ); // Modified cal_to_remove should still exist in calendar_dates. It is modified even though it does not exist in // the future feed due to the MTC requirement to update all service_ids in the past feed. // See https://github.com/ibi-group/datatools-server/issues/244
['src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java', 'src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java']
{'.java': 2}
2
2
0
0
2
1,003,110
201,904
23,110
153
867
133
9
1
975
81
254
10
3
0
"1970-01-01T00:26:28"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
700
phac-nml/irida/606/605
phac-nml
irida
https://github.com/phac-nml/irida/issues/605
https://github.com/phac-nml/irida/pull/606
https://github.com/phac-nml/irida/pull/606
1
fixes
ClientsControllerTest failing after hotfix
## Describe the bug `ClientsControllerTest.testGetAjaxClientList` is failing due to the hotfix lower casing the search terms coming in to the new ant tables. ## Steps to reproduce the problem What were you doing when you encountered the problem? 1. ran `mvn test` 2. `ClientsControllerTest.testGetAjaxClientList` failed 3. ## Expected behaviour `ClientsControllerTest.testGetAjaxClientList` pass ## Additional context It's a null pointer due to the change to ant design on the clients table. It looks like no search term is being sent to the tablerequest.
7472c7472b2b8f415181c7685172341ff5ba9397
abd800f8d88d173d6750d5b9f311f0f5d73c7599
https://github.com/phac-nml/irida/compare/7472c7472b2b8f415181c7685172341ff5ba9397...abd800f8d88d173d6750d5b9f311f0f5d73c7599
diff --git a/src/main/java/ca/corefacility/bioinformatics/irida/ria/web/models/tables/TableRequest.java b/src/main/java/ca/corefacility/bioinformatics/irida/ria/web/models/tables/TableRequest.java index 37382b124d..4e7aafa2d9 100644 --- a/src/main/java/ca/corefacility/bioinformatics/irida/ria/web/models/tables/TableRequest.java +++ b/src/main/java/ca/corefacility/bioinformatics/irida/ria/web/models/tables/TableRequest.java @@ -40,18 +40,25 @@ public class TableRequest { } public String getSearch() { - return search.trim(); + return search; } + /** + * Set the search term for the TableRequest. This method will trim any leading and trailing whitespace. + * + * @param search The search term for the request + */ public void setSearch(String search) { - this.search = search; + if (search != null) { + this.search = search.trim(); + } else { + search = null; + } } /** - * Since we he need an actual {@link Sort} object and cannot pass this from - * the client, we create one from the information fathered from the client - * Direction of sort - * Column (attribute) of sort + * Since we he need an actual {@link Sort} object and cannot pass this from the client, we create one from the + * information fathered from the client Direction of sort Column (attribute) of sort * * @return {@link Sort} */ diff --git a/src/test/java/ca/corefacility/bioinformatics/irida/ria/integration/pages/analysis/AnalysesUserPage.java b/src/test/java/ca/corefacility/bioinformatics/irida/ria/integration/pages/analysis/AnalysesUserPage.java index 45a50d379c..256a593fd5 100644 --- a/src/test/java/ca/corefacility/bioinformatics/irida/ria/integration/pages/analysis/AnalysesUserPage.java +++ b/src/test/java/ca/corefacility/bioinformatics/irida/ria/integration/pages/analysis/AnalysesUserPage.java @@ -58,6 +58,7 @@ public class AnalysesUserPage extends AbstractPage { waitForElementToBeClickable(nameFilterSubmit); nameFilterInput.sendKeys(name); nameFilterSubmit.click(); + waitForElementInvisible(By.className("t-name-filter")); } public void clearNameFilter() {
['src/test/java/ca/corefacility/bioinformatics/irida/ria/integration/pages/analysis/AnalysesUserPage.java', 'src/main/java/ca/corefacility/bioinformatics/irida/ria/web/models/tables/TableRequest.java']
{'.java': 2}
2
2
0
0
2
2,272,384
491,162
66,564
596
746
179
19
1
575
81
131
15
0
0
"1970-01-01T00:26:22"
40
Java
{'Java': 5148223, 'JavaScript': 876296, 'TypeScript': 447025, 'HTML': 41041, 'CSS': 21537, 'Kotlin': 19654, 'Shell': 13267, 'Python': 11481, 'Perl': 6980, 'Dockerfile': 4941}
Apache License 2.0
1,194
ibi-group/datatools-server/209/208
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/208
https://github.com/ibi-group/datatools-server/pull/209
https://github.com/ibi-group/datatools-server/pull/209
1
fixes
MTC sync fails (if not first sync)
## Observed behavior MTC sync fails if not attempting sync for the first time. This is because the code attempts to create a new feed source each time sync is initiated and hits a duplicate ID error in the MongoDB database when re-creating a feed that already exists. ## Steps to reproduce the problem Create project. Click MTC sync. Wait. Click MTC sync again => fail. ## Any special notes on configuration used MTC extension should be enabled. ## Version of datatools-server and datatools-ui if applicable (exact commit hash or branch name) Current dev branches.
a99a4f648030a3796d6311ce385dbcd6627c1352
289ed0e899e503f35902525f950b793ddc6921e6
https://github.com/ibi-group/datatools-server/compare/a99a4f648030a3796d6311ce385dbcd6627c1352...289ed0e899e503f35902525f950b793ddc6921e6
diff --git a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java index 822de30c..5b7eb075 100644 --- a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java +++ b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java @@ -22,10 +22,20 @@ import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import java.util.Collection; import static com.conveyal.datatools.manager.models.ExternalFeedSourceProperty.constructId; /** + * This class implements the {@link ExternalFeedResource} interface for the MTC RTD database list of carriers (transit + * operators) and allows the Data Tools application to read and sync the list of carriers to a set of feed sources for a + * given project. + * + * This is generally intended as an initialization step to importing feed sources into a project; however, it should + * support subsequent sync requests (e.g., if new agencies are expected in the external feed resource, syncing should + * import those OR if feed properties are expected to have changed in the external feed resource, they should be updated + * accordingly in Data Tools). + * * Created by demory on 3/30/16. */ public class MtcFeedResource implements ExternalFeedResource { @@ -48,11 +58,15 @@ public class MtcFeedResource implements ExternalFeedResource { return RESOURCE_TYPE; } + /** + * Fetch the list of feeds from the MTC endpoint, create any feed sources that do not match on agencyID, and update + * the external feed source properties. + */ @Override public void importFeedsForProject(Project project, String authHeader) throws IOException, IllegalAccessException { URL url; ObjectMapper mapper = new ObjectMapper(); - // single list from MTC + // A single list of feeds is returned from the MTC Carrier endpoint. try { url = new URL(rtdApi + "/Carrier"); } catch(MalformedURLException ex) { @@ -61,76 +75,54 @@ public class MtcFeedResource implements ExternalFeedResource { } try { - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - - // optional default is GET - con.setRequestMethod("GET"); - + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //add request header - con.setRequestProperty("User-Agent", "User-Agent"); - + conn.setRequestProperty("User-Agent", "User-Agent"); // add auth header - LOG.info("authHeader="+authHeader); - con.setRequestProperty("Authorization", authHeader); - - int responseCode = con.getResponseCode(); - LOG.info("Sending 'GET' request to URL : " + url); - LOG.info("Response Code : " + responseCode); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer response = new StringBuffer(); + conn.setRequestProperty("Authorization", authHeader); - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - in.close(); - - String json = response.toString(); - RtdCarrier[] results = mapper.readValue(json, RtdCarrier[].class); - for (int i = 0; i < results.length; i++) { - // String className = "RtdCarrier"; - // Object car = Class.forName(className).newInstance(); - RtdCarrier car = results[i]; - //LOG.info("car id=" + car.AgencyId + " name=" + car.AgencyName); + LOG.info("Sending 'GET' request to URL : {}", url); + LOG.info("Response Code : {}", conn.getResponseCode()); + RtdCarrier[] carriers = mapper.readValue(conn.getInputStream(), RtdCarrier[].class); + Collection<FeedSource> projectFeedSources = project.retrieveProjectFeedSources(); + // Iterate over carriers found in response and update properties. Also, create a feed source for any carriers + // found in the response that do not correspond to an agency ID found in the external feed source properties. + for (int i = 0; i < carriers.length; i++) { + RtdCarrier carrier = carriers[i]; FeedSource source = null; - // check if a FeedSource with this AgencyId already exists - for (FeedSource existingSource : project.retrieveProjectFeedSources()) { + // Check if a FeedSource with this AgencyId already exists. + for (FeedSource existingSource : projectFeedSources) { ExternalFeedSourceProperty agencyIdProp; - agencyIdProp = Persistence.externalFeedSourceProperties.getById(constructId(existingSource, this.getResourceType(), - AGENCY_ID_FIELDNAME)); - if (agencyIdProp != null && agencyIdProp.value != null && agencyIdProp.value.equals(car.AgencyId)) { - //LOG.info("already exists: " + car.AgencyId); + String propertyId = constructId(existingSource, this.getResourceType(), AGENCY_ID_FIELDNAME); + agencyIdProp = Persistence.externalFeedSourceProperties.getById(propertyId); + if (agencyIdProp != null && agencyIdProp.value != null && agencyIdProp.value.equals(carrier.AgencyId)) { source = existingSource; } } - - String feedName; - if (car.AgencyName != null) { - feedName = car.AgencyName; - } else if (car.AgencyShortName != null) { - feedName = car.AgencyShortName; - } else { - feedName = car.AgencyId; - } - + // Feed source does not exist. Create one using carrier properties. if (source == null) { + // Derive the name from carrier properties found in response. + String feedName = carrier.AgencyName != null + ? carrier.AgencyName + : carrier.AgencyShortName != null + ? carrier.AgencyShortName + : carrier.AgencyId; + // Create new feed source to store in application database. source = new FeedSource(feedName); + source.projectId = project.id; + LOG.info("Creating feed source {} from carrier response. (Did not previously exist.)", feedName); + // Store the feed source if it does not already exist. + Persistence.feedSources.create(source); } - else source.name = feedName; - - source.projectId = project.id; - // Store the feed source. - Persistence.feedSources.create(source); - - // create / update the properties + // TODO: Does any property on the feed source need to be updated from the carrier (e.g., name). - for(Field carrierField : car.getClass().getDeclaredFields()) { + // Create / update the properties + LOG.info("Updating props for {}", source.name); + for(Field carrierField : carrier.getClass().getDeclaredFields()) { String fieldName = carrierField.getName(); - String fieldValue = carrierField.get(car) != null ? carrierField.get(car).toString() : null; + String fieldValue = carrierField.get(carrier) != null ? carrierField.get(carrier).toString() : null; ExternalFeedSourceProperty prop = new ExternalFeedSourceProperty(source, this.getResourceType(), fieldName, fieldValue); if (Persistence.externalFeedSourceProperties.getById(prop.id) == null) { Persistence.externalFeedSourceProperties.create(prop);
['src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java']
{'.java': 1}
1
1
0
0
1
871,993
175,493
20,879
150
6,388
1,148
104
1
587
95
121
16
0
0
"1970-01-01T00:26:01"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
1,191
ibi-group/datatools-server/302/301
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/301
https://github.com/ibi-group/datatools-server/pull/302
https://github.com/ibi-group/datatools-server/pull/302
1
fixes
During OTP ELB deployment, a condition exists where no running EC2 servers remain, but the job succeeds
## Observed behavior If during deployment to ELB, a different graph build config is used than the final servers to run, there is a case where the graph build server succeeds (and shut downs as per its instructions), but the graph loading server(s) fail but the deploy job still succeeds. ## Expected behavior If the number of running servers at the end of deployment is zero, the job should fail (and the previous servers should not be terminated). ## Steps to reproduce the problem 1. Set up an ELB server to deploy to with different instance sizes for graph build (i.e., normal size for graph build, micro for the other). 2. Kick off deploy job to server with expected graph size that is too large for graph loading server. 3. Job completes successfully with zero servers running. ## Any special notes on configuration used N/A ## Version of datatools-server and datatools-ui if applicable (exact commit hash or branch name) latest dev
146d85f39d182bbc7f16a9dba78884b032c05c2b
becbee101a811748ed980254657d54a20aaedc5d
https://github.com/ibi-group/datatools-server/compare/146d85f39d182bbc7f16a9dba78884b032c05c2b...becbee101a811748ed980254657d54a20aaedc5d
diff --git a/src/main/java/com/conveyal/datatools/manager/jobs/DeployJob.java b/src/main/java/com/conveyal/datatools/manager/jobs/DeployJob.java index cc59b1de..4f87a150 100644 --- a/src/main/java/com/conveyal/datatools/manager/jobs/DeployJob.java +++ b/src/main/java/com/conveyal/datatools/manager/jobs/DeployJob.java @@ -496,8 +496,8 @@ public class DeployJob extends MonitorableJob { // Track any previous instances running for the server we're deploying to in order to de-register and // terminate them later. List<EC2InstanceSummary> previousInstances = otpServer.retrieveEC2InstanceSummaries(); - // Track new instances added. - List<Instance> instances = new ArrayList<>(); + // Track new instances that should be added to target group once the deploy job is completed. + List<Instance> newInstancesForTargetGroup = new ArrayList<>(); // First start graph-building instance and wait for graph to successfully build. if (!deployType.equals(DeployType.USE_PREBUILT_GRAPH)) { status.message = "Starting up graph building EC2 instance"; @@ -567,7 +567,7 @@ public class DeployJob extends MonitorableJob { status.numServersRemaining = Math.max(otpServer.ec2Info.instanceCount, 1); } else { // same configuration exists, so keep instance on and add to list of running instances - instances.addAll(graphBuildingInstances); + newInstancesForTargetGroup.addAll(graphBuildingInstances); status.numServersRemaining = otpServer.ec2Info.instanceCount <= 0 ? 0 : otpServer.ec2Info.instanceCount - 1; @@ -608,7 +608,13 @@ public class DeployJob extends MonitorableJob { } } // Add all servers that did not encounter issues to list for registration with ELB. - instances.addAll(remainingInstances); + newInstancesForTargetGroup.addAll(remainingInstances); + // Fail deploy job if no instances are running at this point (i.e., graph builder instance has shut down + // and the graph loading instance(s) failed to load graph successfully). + if (newInstancesForTargetGroup.size() == 0) { + status.fail("Job failed because no running instances remain."); + return; + } String finalMessage = "Server setup is complete!"; // Get EC2 servers running that are associated with this server. if (deployType.equals(DeployType.REPLACE)) {
['src/main/java/com/conveyal/datatools/manager/jobs/DeployJob.java']
{'.java': 1}
1
1
0
0
1
1,002,617
201,809
23,104
153
930
157
14
1
966
161
199
21
0
0
"1970-01-01T00:26:27"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
1,188
ibi-group/datatools-server/423/422
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/422
https://github.com/ibi-group/datatools-server/pull/423
https://github.com/ibi-group/datatools-server/pull/423
1
closes
Labels: 404 warning when assigning labels
## Observed behavior When adding labels to feeds, a 404 error would appear, even though the label would be assigned correctly. ## Expected behavior The label should be assigned without error ## Steps to reproduce the problem Assign a label to a feed, observe error modal appearing. ## Any special notes on configuration used n/a ## Version of datatools-server and datatools-ui if applicable (exact commit hash or branch name) latest dev
7513fec4bc98ee2d333d2f2a7e139361a8036e37
42c560a53bbc97648bf105fb85e31d091cafd6c0
https://github.com/ibi-group/datatools-server/compare/7513fec4bc98ee2d333d2f2a7e139361a8036e37...42c560a53bbc97648bf105fb85e31d091cafd6c0
diff --git a/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java b/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java index cdd7bc2a..612e4504 100644 --- a/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java +++ b/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java @@ -42,6 +42,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import static com.conveyal.datatools.manager.utils.StringUtils.getCleanName; @@ -339,18 +340,18 @@ public class FeedSource extends Model implements Cloneable { // Compare every property other than labels return this.name.equals(o.name) && this.preserveStopTimesSequence == o.preserveStopTimesSequence && - this.transformRules.equals(o.transformRules) && + Objects.equals(this.transformRules, o.transformRules) && this.isPublic == o.isPublic && this.deployable == o.deployable && - this.retrievalMethod.equals(o.retrievalMethod) && - this.fetchFrequency.equals(o.fetchFrequency) && + Objects.equals(this.retrievalMethod, o.retrievalMethod) && + Objects.equals(this.fetchFrequency, o.fetchFrequency) && this.fetchInterval == o.fetchInterval && - this.lastFetched.equals(o.lastFetched) && - this.url.equals(o.url) && - this.s3Url.equals(o.s3Url) && - this.snapshotVersion.equals(o.snapshotVersion) && - this.publishedVersionId.equals(o.publishedVersionId) && - this.editorNamespace.equals(o.editorNamespace); + Objects.equals(this.lastFetched, o.lastFetched) && + Objects.equals(this.url, o.url) && + Objects.equals(this.s3Url, o.s3Url) && + Objects.equals(this.snapshotVersion, o.snapshotVersion) && + Objects.equals(this.publishedVersionId, o.publishedVersionId) && + Objects.equals(this.editorNamespace, o.editorNamespace); } public String toString () {
['src/main/java/com/conveyal/datatools/manager/models/FeedSource.java']
{'.java': 1}
1
1
0
0
1
1,043,252
206,736
23,548
166
1,209
233
19
1
459
71
93
17
0
0
"1970-01-01T00:27:12"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
1,193
ibi-group/datatools-server/211/210
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/210
https://github.com/ibi-group/datatools-server/pull/211
https://github.com/ibi-group/datatools-server/pull/211
1
fixes
New MTC feed source does not contain nulled out MTC external feed source properties
## Observed behavior Creating a new feed source for MTC results in no external feed source properties being available in the UI (`Feed Source > Settings > MTC Properties`). The workflow for creating a new feed requires that these props be available because in order to register a new feed with MTC's external database, the `AgencyId` prop must be changed from null to a two letter string value. ## Expected behavior MTC properties with null values should be initialized. ## Steps to reproduce the problem Ensure MTC config is enabled. Create feed source. Go to `Feed Source > Settings > MTC Properties`. No properties are visible. ## Any special notes on configuration used MTC extension required
eedf4e7358a3ce352e9bc196e69c6ec4779d2002
f8d393dea5f4f447f78ca1a47c95bad2b6b680ce
https://github.com/ibi-group/datatools-server/compare/eedf4e7358a3ce352e9bc196e69c6ec4779d2002...f8d393dea5f4f447f78ca1a47c95bad2b6b680ce
diff --git a/src/main/java/com/conveyal/datatools/manager/extensions/ExternalFeedResource.java b/src/main/java/com/conveyal/datatools/manager/extensions/ExternalFeedResource.java index d3c0c61b..c761449d 100644 --- a/src/main/java/com/conveyal/datatools/manager/extensions/ExternalFeedResource.java +++ b/src/main/java/com/conveyal/datatools/manager/extensions/ExternalFeedResource.java @@ -16,7 +16,7 @@ public interface ExternalFeedResource { public void importFeedsForProject(Project project, String authHeader) throws Exception; - public void feedSourceCreated(FeedSource source, String authHeader); + public void feedSourceCreated(FeedSource source, String authHeader) throws Exception; public void propertyUpdated(ExternalFeedSourceProperty property, String previousValue, String authHeader) throws IOException; diff --git a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java index 5b7eb075..99e2125b 100644 --- a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java +++ b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java @@ -120,16 +120,7 @@ public class MtcFeedResource implements ExternalFeedResource { // Create / update the properties LOG.info("Updating props for {}", source.name); - for(Field carrierField : carrier.getClass().getDeclaredFields()) { - String fieldName = carrierField.getName(); - String fieldValue = carrierField.get(carrier) != null ? carrierField.get(carrier).toString() : null; - ExternalFeedSourceProperty prop = new ExternalFeedSourceProperty(source, this.getResourceType(), fieldName, fieldValue); - if (Persistence.externalFeedSourceProperties.getById(prop.id) == null) { - Persistence.externalFeedSourceProperties.create(prop); - } else { - Persistence.externalFeedSourceProperties.updateField(prop.id, fieldName, fieldValue); - } - } + carrier.updateFields(source); } } catch(Exception ex) { LOG.error("Could not read feeds from MTC RTD API"); @@ -138,12 +129,15 @@ public class MtcFeedResource implements ExternalFeedResource { } /** - * Do nothing for now. Creating a new agency for RTD requires adding the AgencyId property (when it was previously - * null. See {@link #propertyUpdated(ExternalFeedSourceProperty, String, String)}. + * Generate blank external feed resource properties when a new feed source is created. Creating a new agency for RTD + * requires adding the AgencyId property (when it was previously null. See {@link #propertyUpdated(ExternalFeedSourceProperty, String, String)}. */ @Override - public void feedSourceCreated(FeedSource source, String authHeader) { - LOG.info("Processing new FeedSource {} for RTD. (No action taken.)", source.name); + public void feedSourceCreated(FeedSource source, String authHeader) throws IllegalAccessException { + LOG.info("Processing new FeedSource {} for RTD. Empty external feed properties being generated.", source.name); + // Create a blank carrier and update fields (will initialize all fields to null). + RtdCarrier carrier = new RtdCarrier(); + carrier.updateFields(source); } /** diff --git a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/RtdCarrier.java b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/RtdCarrier.java index 768acdf9..920d7ee3 100644 --- a/src/main/java/com/conveyal/datatools/manager/extensions/mtc/RtdCarrier.java +++ b/src/main/java/com/conveyal/datatools/manager/extensions/mtc/RtdCarrier.java @@ -1,12 +1,17 @@ package com.conveyal.datatools.manager.extensions.mtc; +import com.conveyal.datatools.manager.models.ExternalFeedSourceProperty; import com.conveyal.datatools.manager.models.FeedSource; import com.conveyal.datatools.manager.persistence.Persistence; import com.fasterxml.jackson.annotation.JsonProperty; +import java.lang.reflect.Field; + import static com.conveyal.datatools.manager.models.ExternalFeedSourceProperty.constructId; /** + * Represents all of the properties persisted on a carrier record by the external MTC database known as RTD. + * * Created by demory on 3/30/16. */ @@ -63,11 +68,12 @@ public class RtdCarrier { @JsonProperty String EditedDate; + /** Empty constructor needed for serialization (also used to create empty carrier). */ public RtdCarrier() { } /** - * Construct an RtdCarrier given the provided feed source. + * Construct an RtdCarrier given the provided feed source and initialize all field values from MongoDB. * @param source */ public RtdCarrier(FeedSource source) { @@ -93,9 +99,38 @@ public class RtdCarrier { } /** - * FIXME: Are there cases where this might throw NPEs? + * Get the value stored in the database for a particular field. + * + * TODO: Are there cases where this might throw NPEs? */ private String getValueForField (FeedSource source, String fieldName) { return Persistence.externalFeedSourceProperties.getById(getPropId(source, fieldName)).value; } + + /** + * Use reflection to update (or create if field does not exist) all fields for a carrier instance and provided feed + * source. + * + * TODO: Perhaps we should not be using reflection, but it works pretty well here. + */ + public void updateFields(FeedSource feedSource) throws IllegalAccessException { + // Using reflection, iterate over every field in the class. + for(Field carrierField : this.getClass().getDeclaredFields()) { + String fieldName = carrierField.getName(); + String fieldValue = carrierField.get(this) != null ? carrierField.get(this).toString() : null; + // Construct external feed source property for field with value from carrier. + ExternalFeedSourceProperty prop = new ExternalFeedSourceProperty( + feedSource, + MtcFeedResource.RESOURCE_TYPE, + fieldName, + fieldValue + ); + // If field does not exist, create it. Otherwise, update value. + if (Persistence.externalFeedSourceProperties.getById(prop.id) == null) { + Persistence.externalFeedSourceProperties.create(prop); + } else { + Persistence.externalFeedSourceProperties.updateField(prop.id, fieldName, fieldValue); + } + } + } } \\ No newline at end of file diff --git a/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java b/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java index 3f428a0b..fa18e3aa 100644 --- a/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java +++ b/src/main/java/com/conveyal/datatools/manager/models/FeedSource.java @@ -30,6 +30,7 @@ import java.util.HashMap; import java.util.Map; import static com.conveyal.datatools.manager.utils.StringUtils.getCleanName; +import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.eq; /** @@ -391,10 +392,10 @@ public class FeedSource extends Model implements Cloneable { for(String resourceType : DataManager.feedResources.keySet()) { Map<String, String> propTable = new HashMap<>(); - // FIXME: use mongo filters instead - Persistence.externalFeedSourceProperties.getAll().stream() - .filter(prop -> prop.feedSourceId.equals(this.id)) - .forEach(prop -> propTable.put(prop.name, prop.value)); + // Get all external properties for the feed source/resource type and fill prop table. + Persistence.externalFeedSourceProperties + .getFiltered(and(eq("feedSourceId", this.id), eq("resourceType", resourceType))) + .forEach(prop -> propTable.put(prop.name, prop.value)); resourceTable.put(resourceType, propTable); }
['src/main/java/com/conveyal/datatools/manager/extensions/mtc/RtdCarrier.java', 'src/main/java/com/conveyal/datatools/manager/extensions/ExternalFeedResource.java', 'src/main/java/com/conveyal/datatools/manager/extensions/mtc/MtcFeedResource.java', 'src/main/java/com/conveyal/datatools/manager/models/FeedSource.java']
{'.java': 4}
4
4
0
0
4
872,814
175,668
20,871
150
4,715
866
72
4
717
116
142
15
0
0
"1970-01-01T00:26:01"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
1,192
ibi-group/datatools-server/268/267
ibi-group
datatools-server
https://github.com/ibi-group/datatools-server/issues/267
https://github.com/ibi-group/datatools-server/pull/268
https://github.com/ibi-group/datatools-server/pull/268
1
fixes
MTC feed merge shapes issue
## Observed behavior (please include a screenshot if possible) MTC has reported an issue with shapes.txt during an MTC feed merge (future + active). Essentially, identical shape_ids found in both feeds are causing the merged dataset to contain shape_id:shape_pt_sequence values from both datasets (e.g., if future dataset contains sequences 1,2,3,10 and active contains 1,2,7,9,10; the merged set will contain 1,2,3,7,9,10). So the output shape will be a frankenstein of both input shape point records. ## Expected behavior If a `shape_id` is found in both the future and active datasets, all shape points from the active dataset must be feed-scoped. ## Steps to reproduce the problem Run merge BART feeds test that now fails here: https://github.com/ibi-group/datatools-server/commit/17bf199705e7765ef9bb70766b03339fb5a1f32a ## Any special notes on configuration used n/a ## Version of datatools-ui and datatools-server if applicable (exact commit hash or branch name) latest dev
4594e97cc06508dd0f19c5d6397674da29009394
c0944fabc8b8292ac71378ca263cd4822c9c72bf
https://github.com/ibi-group/datatools-server/compare/4594e97cc06508dd0f19c5d6397674da29009394...c0944fabc8b8292ac71378ca263cd4822c9c72bf
diff --git a/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java b/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java index 829224d2..30e147c5 100644 --- a/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java +++ b/src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java @@ -332,6 +332,8 @@ public class MergeFeedsJob extends MonitorableJob { // Set up objects for tracking the rows encountered Map<String, String[]> rowValuesForStopOrRouteId = new HashMap<>(); Set<String> rowStrings = new HashSet<>(); + // Track shape_ids found in future feed in order to check for conflicts with active feed (MTC only). + Set<String> shapeIdsInFutureFeed = new HashSet<>(); int mergedLineNumber = 0; // Get the spec fields to export List<Field> specFields = table.specFields(); @@ -582,6 +584,37 @@ public class MergeFeedsJob extends MonitorableJob { } } break; + case "shapes": + // If a shape_id is found in both future and active datasets, all shape points from + // the active dataset must be feed-scoped. Otherwise, the merged dataset may contain + // shape_id:shape_pt_sequence values from both datasets (e.g., if future dataset contains + // sequences 1,2,3,10 and active contains 1,2,7,9,10; the merged set will contain + // 1,2,3,7,9,10). + if (field.name.equals("shape_id")) { + if (feedIndex == 0) { + // Track shape_id if working on future feed. + shapeIdsInFutureFeed.add(val); + } else if (shapeIdsInFutureFeed.contains(val)) { + // For the active feed, if the shape_id was already processed from the + // future feed, we need to add the feed-scope to avoid weird, hybrid shapes + // with points from both feeds. + valueToWrite = String.join(":", idScope, val); + // Update key value for subsequent ID conflict checks for this row. + keyValue = valueToWrite; + mergeFeedsResult.remappedIds.put( + getTableScopedValue(table, idScope, val), + valueToWrite + ); + // Re-check refs and uniqueness after changing shape_id value. (Note: this + // probably won't have any impact, but there's not much harm in including it.) + idErrors = referenceTracker + .checkReferencesAndUniqueness(keyValue, lineNumber, field, valueToWrite, + table, keyField, orderField); + } + } + // Skip record if normal duplicate errors are found. + if (hasDuplicateError(idErrors)) skipRecord = true; + break; case "trips": // trip_ids between active and future datasets must not match. If any trip_id is found // to be matching, the merge should fail with appropriate notification to user with the diff --git a/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java b/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java index 87701d1e..e2c37dda 100644 --- a/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java +++ b/src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java @@ -186,6 +186,12 @@ public class MergeFeedsJobTest extends UnitTest { 9, // Magic number represents the number of routes in the merged BART feed. mergeFeedsJob.mergedVersion.feedLoadResult.routes.rowCount ); + assertEquals( + "Merged feed shapes count should equal expected value.", + // During merge, if identical shape_id is found in both feeds, active feed shape_id should be feed-scoped. + bartVersion1.feedLoadResult.shapes.rowCount + bartVersion2.feedLoadResult.shapes.rowCount, + mergeFeedsJob.mergedVersion.feedLoadResult.shapes.rowCount + ); // Ensure there are no referential integrity errors or duplicate ID errors. TestUtils.assertThatFeedHasNoErrorsOfType( mergeFeedsJob.mergedVersion.namespace,
['src/main/java/com/conveyal/datatools/manager/jobs/MergeFeedsJob.java', 'src/test/java/com/conveyal/datatools/manager/jobs/MergeFeedsJobTest.java']
{'.java': 2}
2
2
0
0
2
963,644
194,421
22,441
153
2,851
415
33
1
1,007
139
246
19
1
0
"1970-01-01T00:26:15"
40
Java
{'Java': 1499491, 'Shell': 4860, 'Python': 3466, 'JavaScript': 2627, 'HTML': 824, 'Dockerfile': 588}
MIT License
1,325
googleapis/java-spanner/107/106
googleapis
java-spanner
https://github.com/googleapis/java-spanner/issues/106
https://github.com/googleapis/java-spanner/pull/107
https://github.com/googleapis/java-spanner/pull/107
1
fixes
Session pool metrics registered multiple times
The new metrics that have been added for the `SessionPool` are added multiple times if multiple different session pools are created by a `Spanner` instance. This could happen if the user creates database clients for different databases, or if multiple database clients using different `SessionPoolOptions` are requested. This again will lead to an `InvalidArgumentException` being thrown. See for example https://source.cloud.google.com/results/invocations/a8dc0694-336f-483b-bb8f-2ee502506a2b/targets/cloud-devrel%2Fjava%2Fjava-docs-samples%2Fjava8%2Fpresubmit/log
ea279c424689265fa2ad21922e948a616d850398
4a251ea5bd3306ceee4fd5c39e712f727d3ac11f
https://github.com/googleapis/java-spanner/compare/ea279c424689265fa2ad21922e948a616d850398...4a251ea5bd3306ceee4fd5c39e712f727d3ac11f
diff --git a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MetricRegistryConstants.java b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MetricRegistryConstants.java index 60111618..5902598c 100644 --- a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MetricRegistryConstants.java +++ b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MetricRegistryConstants.java @@ -15,6 +15,7 @@ */ package com.google.cloud.spanner; +import com.google.api.gax.core.GaxProperties; import com.google.common.collect.ImmutableList; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; @@ -23,20 +24,13 @@ import io.opencensus.metrics.LabelValue; class MetricRegistryConstants { // The label keys are used to uniquely identify timeseries. - private static final LabelKey DATABASE = LabelKey.create("database", "Target database"); - private static final LabelKey INSTANCE_ID = - LabelKey.create("instance_id", "Name of the instance"); private static final LabelKey LIBRARY_VERSION = LabelKey.create("library_version", "Library version"); - /** The label value is used to represent missing value. */ - private static final LabelValue UNSET_LABEL = LabelValue.create(null); - - static final ImmutableList<LabelKey> SPANNER_LABEL_KEYS = - ImmutableList.of(DATABASE, INSTANCE_ID, LIBRARY_VERSION); + static final ImmutableList<LabelKey> SPANNER_LABEL_KEYS = ImmutableList.of(LIBRARY_VERSION); static final ImmutableList<LabelValue> SPANNER_DEFAULT_LABEL_VALUES = - ImmutableList.of(UNSET_LABEL, UNSET_LABEL, UNSET_LABEL); + ImmutableList.of(LabelValue.create(GaxProperties.getLibraryVersion(SpannerImpl.class))); /** Unit to represent counts. */ static final String COUNT = "1"; diff --git a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java index 5023f0fa..729b01f7 100644 --- a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java +++ b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java @@ -69,10 +69,13 @@ import io.opencensus.trace.Span; import io.opencensus.trace.Status; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; +import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Set; @@ -1088,6 +1091,11 @@ final class SessionPool { RANDOM; } + private static final Object POOLS_LOCK = new Object(); + + @GuardedBy("POOLS_LOCK") + private static final Map<MetricRegistry, List<SessionPool>> REGISTERED_POOLS = new HashMap<>(); + private final SessionPoolOptions options; private final SessionClient sessionClient; private final ScheduledExecutorService executor; @@ -1150,15 +1158,12 @@ final class SessionPool { * Return pool is immediately ready for use, though getting a session might block for sessions to * be created. */ - static SessionPool createPool( - SpannerOptions spannerOptions, SessionClient sessionClient, List<LabelValue> labelValues) { + static SessionPool createPool(SpannerOptions spannerOptions, SessionClient sessionClient) { return createPool( spannerOptions.getSessionPoolOptions(), ((GrpcTransportOptions) spannerOptions.getTransportOptions()).getExecutorFactory(), sessionClient, - new Clock(), - Metrics.getMetricRegistry(), - labelValues); + new Clock()); } static SessionPool createPool( @@ -1210,6 +1215,14 @@ final class SessionPool { Clock clock, MetricRegistry metricRegistry, List<LabelValue> labelValues) { + synchronized (POOLS_LOCK) { + if (!REGISTERED_POOLS.containsKey(metricRegistry)) { + initMetricsCollection(metricRegistry, labelValues); + REGISTERED_POOLS.put(metricRegistry, new LinkedList<>(Arrays.asList(this))); + } else { + REGISTERED_POOLS.get(metricRegistry).add(this); + } + } this.options = options; this.executorFactory = executorFactory; this.executor = executor; @@ -1229,7 +1242,6 @@ final class SessionPool { this.sessionClient = sessionClient; this.clock = clock; this.poolMaintainer = new PoolMaintainer(); - this.initMetricsCollection(metricRegistry, labelValues); } @VisibleForTesting @@ -1862,11 +1874,36 @@ final class SessionPool { } } + private static final class Sum implements ToLongFunction<Void> { + private final MetricRegistry registry; + private final Function<SessionPool, Long> function; + + static Sum of(MetricRegistry registry, Function<SessionPool, Long> function) { + return new Sum(registry, function); + } + + private Sum(MetricRegistry registry, Function<SessionPool, Long> function) { + this.registry = registry; + this.function = function; + } + + @Override + public long applyAsLong(Void input) { + long res = 0L; + synchronized (POOLS_LOCK) { + for (SessionPool pool : REGISTERED_POOLS.get(registry)) { + res += function.apply(pool); + } + } + return res; + } + }; + /** * Initializes and creates Spanner session relevant metrics. When coupled with an exporter, it * allows users to monitor client behavior. */ - private void initMetricsCollection(MetricRegistry metricRegistry, List<LabelValue> labelValues) { + static void initMetricsCollection(MetricRegistry metricRegistry, List<LabelValue> labelValues) { DerivedLongGauge maxInUseSessionsMetric = metricRegistry.addDerivedLongGauge( MAX_IN_USE_SESSIONS, @@ -1925,68 +1962,80 @@ final class SessionPool { // invoked whenever metrics are collected. maxInUseSessionsMetric.createTimeSeries( labelValues, - this, - new ToLongFunction<SessionPool>() { - @Override - public long applyAsLong(SessionPool sessionPool) { - return sessionPool.maxSessionsInUse; - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return Long.valueOf(input.maxSessionsInUse); + } + })); // The value of a maxSessions is observed from a callback function. This function is invoked // whenever metrics are collected. maxAllowedSessionsMetric.createTimeSeries( labelValues, - options, - new ToLongFunction<SessionPoolOptions>() { - @Override - public long applyAsLong(SessionPoolOptions options) { - return options.getMaxSessions(); - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return Long.valueOf(input.options.getMaxSessions()); + } + })); // The value of a numSessionsInUse is observed from a callback function. This function is // invoked whenever metrics are collected. numInUseSessionsMetric.createTimeSeries( labelValues, - this, - new ToLongFunction<SessionPool>() { - @Override - public long applyAsLong(SessionPool sessionPool) { - return sessionPool.numSessionsInUse; - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return Long.valueOf(input.numSessionsInUse); + } + })); // The value of a numWaiterTimeouts is observed from a callback function. This function is // invoked whenever metrics are collected. sessionsTimeouts.createTimeSeries( labelValues, - this, - new ToLongFunction<SessionPool>() { - @Override - public long applyAsLong(SessionPool sessionPool) { - return sessionPool.getNumWaiterTimeouts(); - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return input.getNumWaiterTimeouts(); + } + })); numAcquiredSessionsMetric.createTimeSeries( labelValues, - this, - new ToLongFunction<SessionPool>() { - @Override - public long applyAsLong(SessionPool sessionPool) { - return sessionPool.numSessionsAcquired; - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return input.numSessionsAcquired; + } + })); numReleasedSessionsMetric.createTimeSeries( labelValues, - this, - new ToLongFunction<SessionPool>() { - @Override - public long applyAsLong(SessionPool sessionPool) { - return sessionPool.numSessionsReleased; - } - }); + null, + Sum.of( + metricRegistry, + new Function<SessionPool, Long>() { + @Override + public Long apply(SessionPool input) { + return input.numSessionsReleased; + } + })); } } diff --git a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java index 08089c89..0178d26a 100644 --- a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java +++ b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java @@ -16,7 +16,6 @@ package com.google.cloud.spanner; -import com.google.api.gax.core.GaxProperties; import com.google.api.gax.paging.Page; import com.google.cloud.BaseService; import com.google.cloud.PageImpl; @@ -28,11 +27,9 @@ import com.google.cloud.spanner.spi.v1.SpannerRpc.Paginated; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions; -import io.opencensus.metrics.LabelValue; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; import java.util.ArrayList; @@ -153,14 +150,8 @@ class SpannerImpl extends BaseService<SpannerOptions> implements Spanner { if (dbClients.containsKey(db)) { return dbClients.get(db); } else { - List<LabelValue> labelValues = - ImmutableList.of( - LabelValue.create(db.getDatabase()), - LabelValue.create(db.getInstanceId().getName()), - LabelValue.create(GaxProperties.getLibraryVersion(getOptions().getClass()))); SessionPool pool = - SessionPool.createPool( - getOptions(), SpannerImpl.this.getSessionClient(db), labelValues); + SessionPool.createPool(getOptions(), SpannerImpl.this.getSessionClient(db)); DatabaseClientImpl dbClient = createDatabaseClient(pool); dbClients.put(db, dbClient); return dbClient; diff --git a/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SessionPoolTest.java b/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SessionPoolTest.java index 2047b6c8..7a507d80 100644 --- a/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SessionPoolTest.java +++ b/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SessionPoolTest.java @@ -1577,11 +1577,7 @@ public class SessionPoolTest extends BaseSessionPoolTest { FakeClock clock = new FakeClock(); clock.currentTimeMillis = System.currentTimeMillis(); FakeMetricRegistry metricRegistry = new FakeMetricRegistry(); - List<LabelValue> labelValues = - Arrays.asList( - LabelValue.create("database1"), - LabelValue.create("instance1"), - LabelValue.create("1.0.0")); + List<LabelValue> labelValues = Arrays.asList(LabelValue.create("1.0.0")); setupMockSessionCreation(); pool = createPool(clock, metricRegistry, labelValues);
['google-cloud-spanner/src/test/java/com/google/cloud/spanner/SessionPoolTest.java', 'google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java', 'google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java', 'google-cloud-spanner/src/main/java/com/google/cloud/spanner/MetricRegistryConstants.java']
{'.java': 4}
4
4
0
0
4
5,948,480
1,322,723
167,404
280
6,361
1,210
170
3
565
60
137
1
1
0
"1970-01-01T00:26:24"
39
Java
{'Java': 13449843, 'Shell': 25900, 'PLpgSQL': 9025, 'Python': 1698, 'Batchfile': 933}
Apache License 2.0
1,065
avaje/avaje-http/114/113
avaje
avaje-http
https://github.com/avaje/avaje-http/issues/113
https://github.com/avaje/avaje-http/pull/114
https://github.com/avaje/avaje-http/pull/114
1
resolves
Support List/Array Types in client generation
The following fails to compile. ``` @Client public interface ApiClient { @Post("/post") HttpResponse<byte[]> call(Holder[] body); @Post("/post2") HttpResponse<byte[]> call2(List<Holder> body); public static record Holder(int s) {} } ``` It seems that imports are not being added correctly to the generated client. ``` import com.jojo.javalin.api.client.ApiClient; import com.jojo.javalin.api.client.ApiClient.Holder[]; import io.avaje.http.api.*; import io.avaje.http.client.HttpApiProvider; import io.avaje.http.client.HttpClientContext; import java.net.http.HttpResponse; import java.util.List; @Generated("avaje-http-client-generator") public class ApiClientHttpClient implements ApiClient { private final HttpClientContext clientContext; public ApiClientHttpClient(HttpClientContext ctx) { this.clientContext = ctx; } // POST /post @Override public HttpResponse<byte[]> call(Holder[] body) { return clientContext.request() .path("post") .body(body) .POST() .asByteArray(); } // POST /post2 @Override public HttpResponse<byte[]> call2(List<Holder> body) { return clientContext.request() .path("post2") .body(body) .POST() .asByteArray(); } ... rest of the generation is fine ```
b2d75dd302c6f1b33630a99285dc1fad961be0f1
2ef121c15d80c292fdd67dd8df9a173c06240e35
https://github.com/avaje/avaje-http/compare/b2d75dd302c6f1b33630a99285dc1fad961be0f1...2ef121c15d80c292fdd67dd8df9a173c06240e35
diff --git a/http-generator-client/src/main/java/io/avaje/http/generator/client/ClientMethodWriter.java b/http-generator-client/src/main/java/io/avaje/http/generator/client/ClientMethodWriter.java index ff0c4f3b..5c0abe1d 100644 --- a/http-generator-client/src/main/java/io/avaje/http/generator/client/ClientMethodWriter.java +++ b/http-generator-client/src/main/java/io/avaje/http/generator/client/ClientMethodWriter.java @@ -33,8 +33,13 @@ class ClientMethodWriter { void addImportTypes(ControllerReader reader) { reader.addImportTypes(returnType.importTypes()); - for (MethodParam param : method.params()) { - param.addImports(reader); + for (final MethodParam param : method.params()) { + final var type = param.utype(); + final var type0 = type.param0(); + final var type1 = type.param1(); + reader.addImportType(type.mainType().replace("[]", "")); + if (type0 != null) reader.addImportType(type0.replace("[]", "")); + if (type1 != null) reader.addImportType(type1.replace("[]", "")); } } @@ -263,4 +268,4 @@ class ClientMethodWriter { return type0.equals("java.net.http.HttpResponse"); } -} +} \\ No newline at end of file
['http-generator-client/src/main/java/io/avaje/http/generator/client/ClientMethodWriter.java']
{'.java': 1}
1
1
0
0
1
198,572
44,668
7,361
85
471
115
11
1
1,334
114
305
54
0
2
"1970-01-01T00:27:50"
39
Java
{'Java': 716599, 'Dockerfile': 1302}
Apache License 2.0
562
karamelchef/karamel/23/22
karamelchef
karamel
https://github.com/karamelchef/karamel/issues/22
https://github.com/karamelchef/karamel/pull/23
https://github.com/karamelchef/karamel/pull/23
1
resolves
chmod id_rsa to 600
The generated keys have too open permissions on apple/linux. Apple won't let you run "ssh -i .karamel/.ssh/id_rsa ubuntu@...." unless you change the permissions. It's a one-line fix, i guess.
ab39925225d9d75267385dcc62e20e484c5ab728
6c006d53ef530ef9cfb10ca630138ad5ed12223b
https://github.com/karamelchef/karamel/compare/ab39925225d9d75267385dcc62e20e484c5ab728...6c006d53ef530ef9cfb10ca630138ad5ed12223b
diff --git a/karamel-core/src/main/java/se/kth/karamel/common/SshKeyService.java b/karamel-core/src/main/java/se/kth/karamel/common/SshKeyService.java index a669166b..1b071f18 100644 --- a/karamel-core/src/main/java/se/kth/karamel/common/SshKeyService.java +++ b/karamel-core/src/main/java/se/kth/karamel/common/SshKeyService.java @@ -12,12 +12,17 @@ import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.Files; +import java.util.HashSet; import java.util.Map; import java.util.Scanner; +import java.util.Set; import org.apache.log4j.Logger; import org.jclouds.ssh.SshKeys; import se.kth.karamel.common.exception.SshKeysNotfoundException; + /** * * @author kamal @@ -42,6 +47,14 @@ public class SshKeyService { } File pubFile = new File(folder, Settings.SSH_PUBKEY_FILENAME); File priFile = new File(folder, Settings.SSH_PRIKEY_FILENAME); + Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_WRITE); + try { + Files.setPosixFilePermissions(priFile.toPath(), perms); + } catch (IOException ex) { + logger.error("If you are running Windows, this is not an error. Failed to set posix permissions on generated private ssh-key. ", ex); + } Map<String, String> keys = SshKeys.generate(); String pub = keys.get("public"); String pri = keys.get("private");
['karamel-core/src/main/java/se/kth/karamel/common/SshKeyService.java']
{'.java': 1}
1
1
0
0
1
315,644
69,325
9,902
107
554
123
13
1
193
29
49
5
0
0
"1970-01-01T00:23:48"
37
Java
{'Java': 598018, 'JavaScript': 396533, 'Ruby': 255788, 'HTML': 80815, 'CSS': 46174, 'SCSS': 9131, 'Scala': 2669, 'Shell': 1647}
Apache License 2.0
8,599
gwtmaterialdesign/gwt-material-addins/176/173
gwtmaterialdesign
gwt-material-addins
https://github.com/GwtMaterialDesign/gwt-material-addins/issues/173
https://github.com/GwtMaterialDesign/gwt-material-addins/pull/176
https://github.com/GwtMaterialDesign/gwt-material-addins/pull/176
1
fixes
Adding MaterialTreeItem programmatically does not set owning MaterialTree.
The onLoad handler and the addItem method do not follow the same strategy to add items to the tree.
7ba93c7f8ee7a15f6d8aa87942b0bf577e3fb8bc
3d4a7cfef047f56446a925143540efe17e45c3a9
https://github.com/gwtmaterialdesign/gwt-material-addins/compare/7ba93c7f8ee7a15f6d8aa87942b0bf577e3fb8bc...3d4a7cfef047f56446a925143540efe17e45c3a9
diff --git a/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java b/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java index e3c7837d..2c5669a3 100644 --- a/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java +++ b/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java @@ -110,8 +110,8 @@ public class MaterialTree extends MaterialWidget implements HasCloseHandlers<Mat @Override protected void add(Widget child, com.google.gwt.user.client.Element container) { if (child instanceof MaterialTreeItem) { - ((MaterialTreeItem) child).setTree(this); super.add(child, container); + ((MaterialTreeItem) child).setTree(this); } else { throw new IllegalArgumentException("MaterialTree can only contain MaterialTreeItem"); } @@ -120,8 +120,8 @@ public class MaterialTree extends MaterialWidget implements HasCloseHandlers<Mat @Override protected void insert(Widget child, com.google.gwt.user.client.Element container, int beforeIndex, boolean domInsert) { if (child instanceof MaterialTreeItem) { - ((MaterialTreeItem) child).setTree(this); super.insert(child, container, beforeIndex, domInsert); + ((MaterialTreeItem) child).setTree(this); } else { throw new IllegalArgumentException("MaterialTree can only contain MaterialTreeItem"); } diff --git a/src/main/java/gwt/material/design/addins/client/tree/MaterialTreeItem.java b/src/main/java/gwt/material/design/addins/client/tree/MaterialTreeItem.java index 34e81072..1752c69a 100644 --- a/src/main/java/gwt/material/design/addins/client/tree/MaterialTreeItem.java +++ b/src/main/java/gwt/material/design/addins/client/tree/MaterialTreeItem.java @@ -273,18 +273,18 @@ public class MaterialTreeItem extends AbstractIconButton implements HasImage, Ha @Override protected void add(Widget child, com.google.gwt.user.client.Element container) { + super.add(child, container); if (child instanceof MaterialTreeItem) { ((MaterialTreeItem) child).setTree(getTree()); } - super.add(child, container); } @Override protected void insert(Widget child, com.google.gwt.user.client.Element container, int beforeIndex, boolean domInsert) { + super.insert(child, container, beforeIndex, domInsert); if (child instanceof MaterialTreeItem) { ((MaterialTreeItem) child).setTree(getTree()); } - super.insert(child, container, beforeIndex, domInsert); } @Override diff --git a/src/test/java/gwt/material/design/addins/client/MaterialTreeTest.java b/src/test/java/gwt/material/design/addins/client/MaterialTreeTest.java index 35440b78..41e8bd66 100644 --- a/src/test/java/gwt/material/design/addins/client/MaterialTreeTest.java +++ b/src/test/java/gwt/material/design/addins/client/MaterialTreeTest.java @@ -26,7 +26,6 @@ import gwt.material.design.addins.client.base.constants.AddinsCssName; import gwt.material.design.addins.client.tree.MaterialTree; import gwt.material.design.addins.client.tree.MaterialTreeItem; import gwt.material.design.client.base.MaterialWidget; -import gwt.material.design.client.constants.CssName; import gwt.material.design.client.constants.IconType; import gwt.material.design.client.ui.MaterialIcon; import gwt.material.design.client.ui.MaterialImage; @@ -45,6 +44,42 @@ public class MaterialTreeTest extends MaterialAddinsTest { checkStructure(tree); checkSelectedItem(tree); checkExpandAndColapse(tree); + checkCreateItemAndSelect(tree); + checkInsertItemAndSelect(tree); + checkCreateSubItemAndSelect(tree); + checkInsertSubItemAndSelect(tree); + } + + protected void checkCreateItemAndSelect(MaterialTree tree) { + MaterialTreeItem treeItem = new MaterialTreeItem(); + treeItem.setText("Child"); + tree.add(treeItem); + treeItem.select(); + } + + protected void checkInsertItemAndSelect(MaterialTree tree) { + MaterialTreeItem treeItem = new MaterialTreeItem(); + treeItem.setText("Child"); + tree.insert(treeItem, 0); + treeItem.select(); + } + + protected void checkCreateSubItemAndSelect(MaterialTree tree) { + MaterialTreeItem root = new MaterialTreeItem("Root"); + tree.add(root); + MaterialTreeItem child = new MaterialTreeItem("Child"); + root.add(child); + tree.expand(); + child.select(); + } + + protected void checkInsertSubItemAndSelect(MaterialTree tree) { + MaterialTreeItem root = new MaterialTreeItem("Root"); + tree.add(root); + MaterialTreeItem child = new MaterialTreeItem("Child"); + root.insert(child, 0); + tree.expand(); + child.select(); } protected <T extends MaterialTree> void checkExpandAndColapse(T tree) {
['src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java', 'src/test/java/gwt/material/design/addins/client/MaterialTreeTest.java', 'src/main/java/gwt/material/design/addins/client/tree/MaterialTreeItem.java']
{'.java': 3}
3
3
0
0
3
457,487
100,104
14,872
154
424
88
8
2
100
19
21
1
0
0
"1970-01-01T00:24:41"
36
JavaScript
{'JavaScript': 3347930, 'Java': 1798807, 'CSS': 248665, 'Shell': 384}
Apache License 2.0
8,600
gwtmaterialdesign/gwt-material-addins/99/92
gwtmaterialdesign
gwt-material-addins
https://github.com/GwtMaterialDesign/gwt-material-addins/issues/92
https://github.com/GwtMaterialDesign/gwt-material-addins/pull/99
https://github.com/GwtMaterialDesign/gwt-material-addins/pull/99
1
fixed
MaterialAutoComplete.setFocus(true) does nothing
It appears that the call to **uiObject.getElement().focus()** in **FocusableMixin.java** results in **focus()** getting called on the underlying **DIV**, rather than on the **INPUT**, which is nested 3 levels deeper. The issue is related to **AutocompleteType.CHIP** GMD 1.5.1, GMA 1.5.1
183f6c666812191e2a2ab90221db4a67a80e187c
b6a882c1dd2989f9a7162ec7e96f72fcf100a007
https://github.com/gwtmaterialdesign/gwt-material-addins/compare/183f6c666812191e2a2ab90221db4a67a80e187c...b6a882c1dd2989f9a7162ec7e96f72fcf100a007
diff --git a/src/main/java/gwt/material/design/addins/client/autocomplete/MaterialAutoComplete.java b/src/main/java/gwt/material/design/addins/client/autocomplete/MaterialAutoComplete.java index dc7258f4..ee63a4d2 100644 --- a/src/main/java/gwt/material/design/addins/client/autocomplete/MaterialAutoComplete.java +++ b/src/main/java/gwt/material/design/addins/client/autocomplete/MaterialAutoComplete.java @@ -33,6 +33,7 @@ import gwt.material.design.client.MaterialDesignBase; import gwt.material.design.client.base.*; import gwt.material.design.client.base.mixin.CssTypeMixin; import gwt.material.design.client.base.mixin.ErrorMixin; +import gwt.material.design.client.base.mixin.FocusableMixin; import gwt.material.design.client.base.mixin.ProgressMixin; import gwt.material.design.client.constants.IconType; import gwt.material.design.client.constants.ProgressType; @@ -185,6 +186,9 @@ public class MaterialAutoComplete extends MaterialWidget implements HasError, Ha private final ErrorMixin<MaterialAutoComplete, MaterialLabel> errorMixin = new ErrorMixin<>(this, lblError, list); + + private FocusableMixin<MaterialWidget> focusableMixin; + public final CssTypeMixin<AutocompleteType, MaterialAutoComplete> typeMixin = new CssTypeMixin<>(this); /** @@ -431,6 +435,12 @@ public class MaterialAutoComplete extends MaterialWidget implements HasError, Ha clearErrorOrSuccess(); } + @Override + protected FocusableMixin<MaterialWidget> getFocusableMixin() { + if(focusableMixin == null) { focusableMixin = new FocusableMixin<>(new MaterialWidget(itemBox.getElement())); } + return focusableMixin; + } + /** * @return the item values on autocomplete * @see #getValue()
['src/main/java/gwt/material/design/addins/client/autocomplete/MaterialAutoComplete.java']
{'.java': 1}
1
1
0
0
1
369,015
79,869
11,882
118
370
79
10
1
288
39
80
4
0
0
"1970-01-01T00:24:26"
36
JavaScript
{'JavaScript': 3347930, 'Java': 1798807, 'CSS': 248665, 'Shell': 384}
Apache License 2.0
3,811
alfasoftware/morf/29/28
alfasoftware
morf
https://github.com/alfasoftware/morf/issues/28
https://github.com/alfasoftware/morf/pull/29
https://github.com/alfasoftware/morf/pull/29
1
fixes
Upgrade step with description longer than 200 characters fails when run
The `UpgradeAudit` table has a 200-character `description` field. This is populated with the `.getDescription()` from the `UpgradeStep` when it is applied. If the description is over 200 characters, this isn't detected until the upgrade step is run and the insert fails. `UpgradeTestHelper` is supposed to check this sort of thing.
e6edf2734a5bad17898e2ebca49f91937c901d02
75c68af1df32fdd4191cbd5c94183742434bc081
https://github.com/alfasoftware/morf/compare/e6edf2734a5bad17898e2ebca49f91937c901d02...75c68af1df32fdd4191cbd5c94183742434bc081
diff --git a/morf-testsupport/src/main/java/org/alfasoftware/morf/testing/UpgradeTestHelper.java b/morf-testsupport/src/main/java/org/alfasoftware/morf/testing/UpgradeTestHelper.java index 09c73f79..45af5dd8 100755 --- a/morf-testsupport/src/main/java/org/alfasoftware/morf/testing/UpgradeTestHelper.java +++ b/morf-testsupport/src/main/java/org/alfasoftware/morf/testing/UpgradeTestHelper.java @@ -189,6 +189,7 @@ public class UpgradeTestHelper { // Check the upgrade step has a description final String description = upgradeStep.getDescription(); assertTrue("Should have a description", StringUtils.isNotEmpty(description)); + assertTrue("Description must not be more than 200 characters", description.length() <= 200); // Descriptions should not end with full-stops if (description.endsWith(".")) {
['morf-testsupport/src/main/java/org/alfasoftware/morf/testing/UpgradeTestHelper.java']
{'.java': 1}
1
1
0
0
1
1,672,106
375,529
51,912
238
98
20
1
1
336
50
75
3
0
0
"1970-01-01T00:24:59"
34
Java
{'Java': 4030914, 'HTML': 4952}
Apache License 2.0
1,388
azuread/microsoft-authentication-library-common-for-android/771/770
azuread
microsoft-authentication-library-common-for-android
https://github.com/AzureAD/microsoft-authentication-library-common-for-android/issues/770
https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/771
https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/771
1
resolves
Null pointer on AcquireTokenResult.getSucceeded
COBO app reported a null pointer on a failed silent flow where`AcquireTokenResult` is null. StackTrace ``` com.microsoft.intune.common.presentationcomponent.abstraction.UiModelErrorState$Authentication@6b4a87a 2020-01-08T00:02:51.4700000 INFO com.microsoft.intune.authentication.authcomponent.abstraction.AadTokenRepo 9274 00002 Calling AAD auth library for Intune(ignored=true) token. 2020-01-08T00:02:51.6980000 WARNING com.microsoft.intune.authentication.authcomponent.implementation.MsalAuthWrapper 9274 00002 Silent MSAL auth failed. com.microsoft.identity.client.exception.MsalClientException: Attempt to invoke virtual method 'java.lang.Boolean com.microsoft.identity.common.internal.result.AcquireTokenResult.getSucceeded()' on a null object reference com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter.msalExceptionFromBaseException(MsalExceptionAdapter.java:51) com.microsoft.identity.client.PublicClientApplication$9.onError(PublicClientApplication.java:1668) com.microsoft.identity.client.PublicClientApplication$9.onError(PublicClientApplication.java:1658) com.microsoft.identity.common.internal.controllers.CommandDispatcher$2.run(CommandDispatcher.java:176) android.os.Handler.handleCallback(Handler.java:883) android.os.Handler.dispatchMessage(Handler.java:100) android.os.Looper.loop(Looper.java:214) android.app.ActivityThread.main(ActivityThread.java:7356) java.lang.reflect.Method.invoke(Native Method) com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) com.microsoft.identity.common.exception.ClientException: Attempt to invoke virtual method 'java.lang.Boolean com.microsoft.identity.common.internal.result.AcquireTokenResult.getSucceeded()' on a null object reference com.microsoft.identity.common.internal.controllers.ExceptionAdapter.baseExceptionFromException(ExceptionAdapter.java:252) com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:142) com.microsoft.identity.common.internal.controllers.CommandDispatcher.access$200(CommandDispatcher.java:52) com.microsoft.identity.common.internal.controllers.CommandDispatcher$1.run(CommandDispatcher.java:94) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) java.lang.Thread.run(Thread.java:919) java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.microsoft.identity.common.internal.result.AcquireTokenResult.getSucceeded()' on a null object reference com.microsoft.identity.common.internal.controllers.TokenCommand.execute(TokenCommand.java:77) com.microsoft.identity.common.internal.controllers.TokenCommand.execute(TokenCommand.java:42) com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:137) com.microsoft.identity.common.internal.controllers.CommandDispatcher.access$200(CommandDispatcher.java:52) com.microsoft.identity.common.internal.controllers.CommandDispatcher$1.run(CommandDispatcher.java:94) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) java.lang.Thread.run(Thread.java:919) ```
f8dc8cbf08faf3b8b58ac5e79c85fc8e4b83a52d
23396ed2cd3335cbbf712630e9621dddc9a8fbbd
https://github.com/azuread/microsoft-authentication-library-common-for-android/compare/f8dc8cbf08faf3b8b58ac5e79c85fc8e4b83a52d...23396ed2cd3335cbbf712630e9621dddc9a8fbbd
diff --git a/common/src/main/java/com/microsoft/identity/common/internal/controllers/TokenCommand.java b/common/src/main/java/com/microsoft/identity/common/internal/controllers/TokenCommand.java index 3f5b6e0cd..7748ade89 100644 --- a/common/src/main/java/com/microsoft/identity/common/internal/controllers/TokenCommand.java +++ b/common/src/main/java/com/microsoft/identity/common/internal/controllers/TokenCommand.java @@ -24,10 +24,7 @@ package com.microsoft.identity.common.internal.controllers; import android.content.Intent; -import androidx.annotation.NonNull; - import com.microsoft.identity.common.adal.internal.AuthenticationConstants; -import com.microsoft.identity.common.exception.BaseException; import com.microsoft.identity.common.exception.ClientException; import com.microsoft.identity.common.exception.ErrorStrings; import com.microsoft.identity.common.exception.UiRequiredException; @@ -35,9 +32,9 @@ import com.microsoft.identity.common.internal.request.AcquireTokenSilentOperatio import com.microsoft.identity.common.internal.request.OperationParameters; import com.microsoft.identity.common.internal.result.AcquireTokenResult; -import java.io.IOException; import java.util.List; -import java.util.concurrent.ExecutionException; + +import androidx.annotation.NonNull; public class TokenCommand extends BaseCommand<AcquireTokenResult> implements TokenOperation { @@ -74,7 +71,7 @@ public class TokenCommand extends BaseCommand<AcquireTokenResult> implements Tok (AcquireTokenSilentOperationParameters) getParameters() ); - if (result.getSucceeded()) { + if (result != null && result.getSucceeded()) { com.microsoft.identity.common.internal.logging.Logger.verbose( TAG + methodName, "Executing with controller: "
['common/src/main/java/com/microsoft/identity/common/internal/controllers/TokenCommand.java']
{'.java': 1}
1
1
0
0
1
1,906,695
364,736
49,294
338
328
51
9
1
3,444
105
683
38
0
1
"1970-01-01T00:26:18"
34
Java
{'Java': 6707989, 'Kotlin': 138989, 'C#': 122387, 'AIDL': 3757, 'Python': 3144, 'Shell': 2998}
MIT License
633
spineeventengine/core-java/1130/1000
spineeventengine
core-java
https://github.com/SpineEventEngine/core-java/issues/1000
https://github.com/SpineEventEngine/core-java/pull/1130
https://github.com/SpineEventEngine/core-java/pull/1130
1
resolves
Events.clearEnrichments should clear enrichments for all parent context
Current implementation clears enrichments only for the current context and its origin, but in theory, the `origin` of the current context origin can also have enrichment. In order to be sure that **no** enrichments are stored, the `clearEnrichments` should recursively clear enrichments from origins.
80d21ac9d7e9d1a1dca7a4483bff83c51cc3d6db
2dffe9f0d119e5bd9344d627b2aa9318adedfa12
https://github.com/spineeventengine/core-java/compare/80d21ac9d7e9d1a1dca7a4483bff83c51cc3d6db...2dffe9f0d119e5bd9344d627b2aa9318adedfa12
diff --git a/core/src/main/java/io/spine/core/Enrichments.java b/core/src/main/java/io/spine/core/Enrichments.java index 5fe65c1331..416cd571f3 100644 --- a/core/src/main/java/io/spine/core/Enrichments.java +++ b/core/src/main/java/io/spine/core/Enrichments.java @@ -26,8 +26,10 @@ import io.spine.core.Enrichment.Container; import io.spine.core.Enrichment.ModeCase; import io.spine.type.TypeName; +import java.util.Deque; import java.util.Optional; +import static com.google.common.collect.Queues.newArrayDeque; import static io.spine.protobuf.AnyPacker.unpack; import static io.spine.util.Exceptions.newIllegalStateException; @@ -86,4 +88,74 @@ final class Enrichments { .map(packed -> unpack(packed, enrichmentClass)); return result; } + + /** + * Clears the enrichments from the {@code event} and its origin. + */ + @SuppressWarnings("deprecation") // Uses the deprecated field to be sure to clean up old data. + static Event clear(Event event) { + EventContext context = event.getContext(); + EventContext.OriginCase originCase = context.getOriginCase(); + EventContext.Builder resultContext = context.toBuilder() + .clearEnrichment(); + if (originCase == EventContext.OriginCase.EVENT_CONTEXT) { + resultContext.setEventContext(context.getEventContext() + .toBuilder() + .clearEnrichment() + .build()); + } + Event result = event.toBuilder() + .setContext(resultContext.build()) + .build(); + return result; + } + + /** + * Clears the enrichments from the {@code event} and all of its parent contexts. + */ + @SuppressWarnings({ + "deprecation" /* Uses the deprecated field to be sure to clean up old data. */, + "ConstantConditions" /* Checked logically. */}) + static Event clearAll(Event event) { + EventContext.Builder eventContext = event.getContext() + .toBuilder() + .clearEnrichment(); + Deque<EventContext.Builder> contexts = eventContextHierarchy(eventContext); + + EventContext.Builder context = contexts.pollLast(); + EventContext.Builder next = contexts.pollLast(); + while (next != null) { + context = next.setEventContext(context); + next = contexts.pollLast(); + } + Event result = event.toBuilder() + .setContext(context.build()) + .build(); + return result; + } + + /** + * Traverses the event parent context hierarchy until non-{@link EventContext} origin is found. + * + * <p>All of the {@link EventContext}-kind origins are collected and returned as + * {@code Deque<EventContext.Builder>}, where the deepest origin resides last. + */ + @SuppressWarnings("deprecation") // Uses the deprecated field to be sure to clean up old data. + private static Deque<EventContext.Builder> + eventContextHierarchy(EventContext.Builder eventContext) { + + EventContext.Builder child = eventContext; + EventContext.OriginCase originCase = child.getOriginCase(); + Deque<EventContext.Builder> contexts = newArrayDeque(); + contexts.add(child); + while (originCase == EventContext.OriginCase.EVENT_CONTEXT) { + EventContext.Builder origin = child.getEventContext() + .toBuilder() + .clearEnrichment(); + contexts.add(origin); + child = origin; + originCase = child.getOriginCase(); + } + return contexts; + } } diff --git a/core/src/main/java/io/spine/core/EventMixin.java b/core/src/main/java/io/spine/core/EventMixin.java index 6029aceed3..833c32949c 100644 --- a/core/src/main/java/io/spine/core/EventMixin.java +++ b/core/src/main/java/io/spine/core/EventMixin.java @@ -103,32 +103,42 @@ public interface EventMixin extends Signal<EventId, EventMessage, EventContext>, * <li>the enrichment from the first-level origin.</li> * </ul> * - * <p>Enrichments will not be removed from second-level and deeper origins, - * because it's a heavy performance operation. + * <p>This method does not remove enrichments from second-level and deeper origins to avoid a + * heavy performance operation. + * + * <p>To remove enrichments from the whole parent context hierarchy, use + * {@link #clearAllEnrichments()}. * * @return the event without enrichments */ - @SuppressWarnings({ - "ClassReferencesSubclass", //`Event` is the only case of this mixin. - "deprecation" // Uses the `event_context` field to be sure to clean up old data. - }) + @SuppressWarnings("ClassReferencesSubclass") // `Event` is the only case of this mixin. @Internal default Event clearEnrichments() { - EventContext context = context(); - EventContext.OriginCase originCase = context.getOriginCase(); - EventContext.Builder resultContext = context.toBuilder() - .clearEnrichment(); - if (originCase == EventContext.OriginCase.EVENT_CONTEXT) { - resultContext.setEventContext(context.getEventContext() - .toBuilder() - .clearEnrichment() - .build()); - } - Event thisEvent = (Event) this; - Event result = thisEvent.toBuilder() - .setContext(resultContext.build()) - .build(); - return result; + return Enrichments.clear((Event) this); + } + + /** + * Creates a copy of this instance with enrichments cleared from self and all parent contexts. + * + * <p>Use this method to decrease a size of an event, if enrichments aren't important. + * + * <p>A result won't contain: + * <ul> + * <li>the enrichment from the event context;</li> + * <li>the enrichment from the first-level origin;</li> + * <li>the enrichment from the second-level and deeper origins.</li> + * </ul> + * + * <p>This method is performance-heavy. + * + * <p>For the "lightweight" version of the method, see {@link #clearEnrichments()}. + * + * @return the event without enrichments + */ + @SuppressWarnings("ClassReferencesSubclass") // `Event` is the only case of this mixin. + @Internal + default Event clearAllEnrichments() { + return Enrichments.clearAll((Event) this); } /** diff --git a/server/src/test/java/io/spine/core/EventTest.java b/server/src/test/java/io/spine/core/EventTest.java index e8009f78bd..1dcdc90b11 100644 --- a/server/src/test/java/io/spine/core/EventTest.java +++ b/server/src/test/java/io/spine/core/EventTest.java @@ -56,7 +56,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; * <p>This test suite is placed under the {@code server} module to avoid dependency on the event * generation code which belongs to server-side. */ -@DisplayName("Event should") +@DisplayName("`Event` should") public class EventTest extends UtilityClassTest<Events> { private static final TestActorRequestFactory requestFactory = @@ -204,11 +204,6 @@ public class EventTest extends UtilityClassTest<Events> { assertThat(event.tenant()) .isEqualTo(targetTenantId); } - - private EventContext.Builder contextWithoutOrigin() { - return context.toBuilder() - .clearOrigin(); - } } @Test @@ -234,4 +229,70 @@ public class EventTest extends UtilityClassTest<Events> { assertThat(event.isRejection()) .isFalse(); } + + @SuppressWarnings("deprecation") // Required for backward compatibility. + @Test + @DisplayName("clear enrichments from the event and its origin") + void clearEnrichments() { + Enrichment someEnrichment = Enrichment + .newBuilder() + .setDoNotEnrich(true) + .build(); + EventContext.Builder grandOriginContext = + context.toBuilder() + .setEnrichment(someEnrichment); + EventContext.Builder originContext = + contextWithoutOrigin() + .setEventContext(grandOriginContext) + .setEnrichment(someEnrichment); + EventContext eventContext = + contextWithoutOrigin() + .setEventContext(originContext) + .setEnrichment(someEnrichment) + .build(); + Event event = event(eventContext); + + Event eventWithoutEnrichments = event.clearEnrichments(); + + EventContext context = eventWithoutEnrichments.getContext(); + EventContext origin = context.getEventContext(); + EventContext grandOrigin = origin.getEventContext(); + + assertThat(context.hasEnrichment()).isFalse(); + assertThat(origin.hasEnrichment()).isFalse(); + assertThat(grandOrigin.hasEnrichment()).isTrue(); + } + + @SuppressWarnings("deprecation") // Required for backward compatibility. + @Test + @DisplayName("clear enrichment hierarchy") + void clearEnrichmentHierarchy() { + Enrichment someEnrichment = Enrichment + .newBuilder() + .setDoNotEnrich(true) + .build(); + EventContext.Builder grandOriginContext = + context.toBuilder() + .setEnrichment(someEnrichment); + EventContext.Builder originContext = + contextWithoutOrigin() + .setEventContext(grandOriginContext); + EventContext context = + contextWithoutOrigin() + .setEventContext(originContext) + .build(); + Event event = event(context); + + Event eventWithoutEnrichments = event.clearAllEnrichments(); + + EventContext grandOrigin = eventWithoutEnrichments.getContext() + .getEventContext() + .getEventContext(); + assertThat(grandOrigin.hasEnrichment()).isFalse(); + } + + private EventContext.Builder contextWithoutOrigin() { + return context.toBuilder() + .clearOrigin(); + } }
['core/src/main/java/io/spine/core/Enrichments.java', 'server/src/test/java/io/spine/core/EventTest.java', 'core/src/main/java/io/spine/core/EventMixin.java']
{'.java': 3}
3
3
0
0
3
2,673,423
540,425
72,727
698
5,754
1,074
124
2
304
44
62
3
0
0
"1970-01-01T00:26:04"
33
Java
{'Java': 6679521, 'Kotlin': 755047, 'Shell': 40419, 'CSS': 1739}
Apache License 2.0
635
spineeventengine/core-java/673/672
spineeventengine
core-java
https://github.com/SpineEventEngine/core-java/issues/672
https://github.com/SpineEventEngine/core-java/pull/673
https://github.com/SpineEventEngine/core-java/pull/673
1
fixes
The `targetVersion` of `CommandFactory.create(Message, int)` is not documented properly
Currently it is documented as follows. ```java @param targetVersion the ID of the entity for applying commands if {@code null} the commands can be applied to any entity ``` When clearly it isn't what we say about it. Also, for some reason, we check this `int`-typed parameter for not being `null`. In scope of this issue we need to fix the documentation and address the nullability check.
5f96796ffe20253464f547cc62b7fe0ea9125760
18153ada8ee6b7d7d2753fc7129c06563d11570b
https://github.com/spineeventengine/core-java/compare/5f96796ffe20253464f547cc62b7fe0ea9125760...18153ada8ee6b7d7d2753fc7129c06563d11570b
diff --git a/client/src/main/java/io/spine/client/ActorRequestFactory.java b/client/src/main/java/io/spine/client/ActorRequestFactory.java index 932c696a7e..ab2d1821b7 100644 --- a/client/src/main/java/io/spine/client/ActorRequestFactory.java +++ b/client/src/main/java/io/spine/client/ActorRequestFactory.java @@ -93,14 +93,32 @@ public class ActorRequestFactory { return result; } + /** + * Creates an instance of {@link QueryFactory} based on configuration of this + * {@code ActorRequestFactory} instance. + * + * @return an instance of {@link QueryFactory} + */ public QueryFactory query() { return new QueryFactory(this); } + /** + * Creates an instance of {@link TopicFactory} based on configuration of this + * {@code ActorRequestFactory} instance. + * + * @return an instance of {@link TopicFactory} + */ public TopicFactory topic() { return new TopicFactory(this); } + /** + * Creates an instance of {@link CommandFactory} based on configuration of this + * {@code ActorRequestFactory} instance. + * + * @return an instance of {@link CommandFactory} + */ public CommandFactory command() { return new CommandFactory(this); } diff --git a/client/src/main/java/io/spine/client/CommandFactory.java b/client/src/main/java/io/spine/client/CommandFactory.java index 2fb8b02ded..0c8330611f 100644 --- a/client/src/main/java/io/spine/client/CommandFactory.java +++ b/client/src/main/java/io/spine/client/CommandFactory.java @@ -41,17 +41,14 @@ import static io.spine.time.Time.getCurrentTime; import static io.spine.validate.Validate.checkValid; /** - * Public API for creating {@link Command} instances, using the {@code ActorRequestFactory} - * configuration. + * A factory of {@link Command} instances. * - * <p>During the creation of {@code Command} instances the source {@code Message} instances, passed - * into creation methods, are validated. The validation is performed according to the constraints - * set in Protobuf definition of each {@code Message}. In case the message isn't valid, - * an {@linkplain ValidationException exception} is thrown. + * <p>Uses the given {@link ActorRequestFactory} as the source of the command meta information, + * such as the actor, the tenant, etc. * - * <p>Therefore it is recommended to use a corresponding - * {@linkplain io.spine.validate.ValidatingBuilder ValidatingBuilder} implementation to create - * a command message. + * <p>The command messages passed to the factory are + * {@linkplain io.spine.validate.Validate#checkValid(Message) validated} according to their + * Proto definitions. If a given message is invalid, a {@link ValidationException} is thrown. * * @see ActorRequestFactory#command() */ @@ -64,14 +61,12 @@ public final class CommandFactory { } /** - * Creates new {@code Command} with the passed message. - * - * <p>The command contains a {@code CommandContext} instance with the current time. + * Creates a new {@link Command} with the given message. * * @param message the command message * @return new command instance * @throws ValidationException if the passed message does not satisfy the constraints - * set for it in its Protobuf definition + * set for it in its Protobuf definition */ public Command create(Message message) throws ValidationException { checkNotNull(message); @@ -83,24 +78,20 @@ public final class CommandFactory { } /** - * Creates new {@code Command} with the passed message and target entity version. - * - * <p>The command contains a {@code CommandContext} instance with the current time. + * Creates a new {@code Command} with the passed message and target entity version. * - * <p>The message passed is validated according to the constraints set in its Protobuf - * definition. In case the message isn't valid, an {@linkplain ValidationException - * exception} is thrown. + * <p>The {@code targetVersion} parameter defines the version of the entity which handles + * the resulting command. Note that the framework performs no validation of the target version + * before a command is handled. The validation may be performed by the user themselves instead. * * @param message the command message - * @param targetVersion the ID of the entity for applying commands if {@code null} - * the commands can be applied to any entity + * @param targetVersion the version of the entity for which this command is intended * @return new command instance * @throws ValidationException if the passed message does not satisfy the constraints * set for it in its Protobuf definition */ public Command create(Message message, int targetVersion) throws ValidationException { checkNotNull(message); - checkNotNull(targetVersion); checkValid(message); final CommandContext context = createContext(targetVersion); @@ -109,10 +100,7 @@ public final class CommandFactory { } /** - * Creates new {@code Command} with the passed {@code message} and {@code context}. - * - * <p>The timestamp of the resulting command is the <i>same</i> as in - * the passed {@code CommandContext}. + * Creates a new {@code Command} with the passed {@code message} and {@code context}. * * @param message the command message * @param context the command context @@ -157,10 +145,10 @@ public final class CommandFactory { } /** - * Creates a command instance with the given {@code message} and the {@code context}. + * Creates a command instance with the given {@code message} and {@code context}. * - * <p>If {@code Any} instance is passed as the first parameter it will be used as is. - * Otherwise, the command message will be packed into {@code Any}. + * <p>If an instance of {@link Any} is passed as the {@code message} parameter, the packed + * message is used for the command construction. * * <p>The ID of the new command instance is automatically generated. * @@ -169,9 +157,6 @@ public final class CommandFactory { * @return a new command */ private static Command createCommand(Message message, CommandContext context) { - checkNotNull(message); - checkNotNull(context); - final Any packed = AnyPacker.pack(message); final Command.Builder result = Command.newBuilder() .setId(Commands.generateId()) @@ -211,20 +196,18 @@ public final class CommandFactory { private static CommandContext createContext(@Nullable TenantId tenantId, UserId userId, ZoneOffset zoneOffset) { - checkNotNull(userId); - checkNotNull(zoneOffset); - final CommandContext.Builder result = newContextBuilder(tenantId, userId, zoneOffset); return result.build(); } /** - * Creates a new command context with the current time. + * Creates a new command context with the given parameters and + * {@link io.spine.time.Time#getCurrentTime() current time} as the {@code timestamp}. * * @param tenantId the ID of the tenant or {@code null} for single-tenant applications * @param userId the actor id * @param zoneOffset the offset of the timezone in which the user works - * @param targetVersion the the ID of the entity for applying commands + * @param targetVersion the version of the entity for which this command is intended * @return new {@code CommandContext} * @see CommandFactory#create(Message) */ @@ -233,10 +216,6 @@ public final class CommandFactory { UserId userId, ZoneOffset zoneOffset, int targetVersion) { - checkNotNull(userId); - checkNotNull(zoneOffset); - checkNotNull(targetVersion); - final CommandContext.Builder builder = newContextBuilder(tenantId, userId, zoneOffset); final CommandContext result = builder.setTargetVersion(targetVersion) .build(); @@ -262,13 +241,13 @@ public final class CommandFactory { /** * Creates a new instance of {@code CommandContext} based on the passed one. * - * <p>The returned instance gets new {@code timestamp} set to the time of the call. + * <p>The returned instance gets new {@code timestamp} set to + * the {@link io.spine.time.Time#getCurrentTime() current time}. * * @param value the instance from which to copy values * @return new {@code CommandContext} */ private static CommandContext contextBasedOn(CommandContext value) { - checkNotNull(value); final ActorContext.Builder withCurrentTime = value.getActorContext() .toBuilder() .setTimestamp(getCurrentTime()); diff --git a/client/src/main/java/io/spine/client/QueryBuilder.java b/client/src/main/java/io/spine/client/QueryBuilder.java index 7a6045969d..b61df55f4e 100644 --- a/client/src/main/java/io/spine/client/QueryBuilder.java +++ b/client/src/main/java/io/spine/client/QueryBuilder.java @@ -43,10 +43,10 @@ import static java.util.Collections.singleton; * * <p>The API of this class is inspired by the SQL syntax. * - * <p>Calling any of the methods is optional. Call {@link #build() build()} to retrieve - * the instance of {@link Query}. + * <p>Calling any of the methods is optional. Call {@link #build()} to retrieve the resulting + * instance of {@link Query}. * - * <p>Calling any of the builder methods overrides the previous call of the given method of + * <p>Calling any of the builder methods overrides the previous call of the given method or * any of its overloads. For example, calling sequentially * <pre> * {@code @@ -70,9 +70,9 @@ import static java.util.Collections.singleton; * {@code * final Query query = factory().query() * .select(Customer.class) - * .byId(getWestCostCustomersIds()) + * .byId(getWestCostCustomerIds()) * .withMask("name", "address", "email") - * .where({@link ColumnFilters#eq eq}("type", "permanent"), + * .where(eq("type", "permanent"), * eq("discountPercent", 10), * eq("companySize", Company.Size.SMALL)) * .build(); @@ -87,9 +87,10 @@ public final class QueryBuilder { private final QueryFactory queryFactory; private final Class<? extends Message> targetType; - /* All the optional fields are initialized only when and if set - The empty collections make effectively no influence, but null values allow us to create - the query `Target` more efficiently. + /* + All the optional fields are initialized only when and if set. + The empty collections make effectively no influence, but null values allow us to create + the query `Target` more efficiently. */ @Nullable @@ -107,13 +108,13 @@ public final class QueryBuilder { } /** - * Sets the ID predicate to the {@linkplain Query}. + * Sets the ID predicate to the {@link Query}. * * <p>Though it's not prohibited at compile-time, please make sure to pass instances of the * same type to the argument of this method. Moreover, the instances must be of the type of * the query target type identifier. * - * <p>This method or any of its overload do not check these + * <p>This method or any of its overloads do not check these * constrains an assume they are followed by the caller. * * <p>If there are no IDs (i.e. and empty {@link Iterable} is passed), the query retrieves all @@ -129,7 +130,7 @@ public final class QueryBuilder { } /** - * Sets the ID predicate to the {@linkplain Query}. + * Sets the ID predicate to the {@link Query}. * * @param ids the values of the IDs to look up * @return self for method chaining @@ -141,7 +142,7 @@ public final class QueryBuilder { } /** - * Sets the ID predicate to the {@linkplain Query}. + * Sets the ID predicate to the {@link Query}. * * @param ids the values of the IDs to look up * @return self for method chaining @@ -153,7 +154,7 @@ public final class QueryBuilder { } /** - * Sets the ID predicate to the {@linkplain Query}. + * Sets the ID predicate to the {@link Query}. * * @param ids the values of the IDs to look up * @return self for method chaining @@ -165,7 +166,7 @@ public final class QueryBuilder { } /** - * Sets the ID predicate to the {@linkplain Query}. + * Sets the ID predicate to the {@link Query}. * * @param ids the values of the IDs to look up * @return self for method chaining @@ -177,7 +178,7 @@ public final class QueryBuilder { } /** - * Sets the Entity Column predicate to the {@linkplain Query}. + * Sets the Entity Column predicate to the {@link Query}. * * <p>If there are no {@link ColumnFilter}s (i.e. the passed array is empty), all * the records will be retrieved regardless the Entity Columns values. @@ -198,7 +199,7 @@ public final class QueryBuilder { } /** - * Sets the Entity Column predicate to the {@linkplain Query}. + * Sets the Entity Column predicate to the {@link Query}. * * <p>If there are no {@link ColumnFilter}s (i.e. the passed array is empty), all * the records will be retrieved regardless the Entity Columns values. @@ -251,8 +252,7 @@ public final class QueryBuilder { * * <p>The {@code Option 1} is recommended in this case, since the filters are grouped logically, * though both builders produce effectively the same {@link Query} instances. Note, that - * those instances may not be equal in terms of {@link Object#equals(Object) Object.equals} - * method. + * those instances may not be equal in terms of {@link Object#equals(Object)} method. * * @param predicate a number of {@link CompositeColumnFilter} instances forming the query * predicate @@ -308,7 +308,6 @@ public final class QueryBuilder { */ public Query build() { final FieldMask mask = composeMask(); - // Implying AnyPacker.pack to be idempotent final Set<Any> entityIds = composeIdPredicate(); final Query result = queryFactory.composeQuery(targetType, entityIds, columns, mask); diff --git a/client/src/main/java/io/spine/client/QueryFactory.java b/client/src/main/java/io/spine/client/QueryFactory.java index e9937410ef..de84e7766f 100644 --- a/client/src/main/java/io/spine/client/QueryFactory.java +++ b/client/src/main/java/io/spine/client/QueryFactory.java @@ -31,12 +31,15 @@ import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static io.spine.Identifier.newUuid; import static io.spine.client.Queries.queryBuilderFor; import static java.lang.String.format; /** - * Public API for creating {@link Query} instances, using the {@code ActorRequestFactory} - * configuration. + * A factory of {@link Query} instances. + * + * <p>Uses the given {@link ActorRequestFactory} as the source of the query meta information, + * such as the actor. * * @see ActorRequestFactory#query() */ @@ -57,14 +60,14 @@ public final class QueryFactory { } private static QueryId newQueryId() { - final String formattedId = format(QUERY_ID_FORMAT, Identifier.newUuid()); + final String formattedId = format(QUERY_ID_FORMAT, newUuid()); return QueryId.newBuilder() .setValue(formattedId) .build(); } /** - * Creates a new instance of {@link QueryBuilder} for the further {@linkplain Query} + * Creates a new instance of {@link QueryBuilder} for the further {@link Query} * construction. * * @param targetType the {@linkplain Query query} target type diff --git a/client/src/main/java/io/spine/client/TopicFactory.java b/client/src/main/java/io/spine/client/TopicFactory.java index 661e4b2fb9..2f82425fa9 100644 --- a/client/src/main/java/io/spine/client/TopicFactory.java +++ b/client/src/main/java/io/spine/client/TopicFactory.java @@ -30,8 +30,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.client.Targets.composeTarget; /** - * Public API for creating {@link Topic} instances, using the {@code ActorRequestFactory} - * configuration. + * A factory of {@link Topic} instances. + * + * <p>Uses the given {@link ActorRequestFactory} as the source of the topic meta information, + * such as the actor. * * @see ActorRequestFactory#topic() */ @@ -45,11 +47,11 @@ public final class TopicFactory { } /** - * Creates a {@link Topic} for a subset of the entity states by specifying their IDs. + * Creates a {@link Topic} for the entity states with the given IDs. * * @param entityClass the class of a target entity * @param ids the IDs of interest - * @return the instance of {@code Topic} assembled according to the parameters. + * @return the instance of {@code Topic} assembled according to the parameters */ public Topic someOf(Class<? extends Message> entityClass, Set<? extends Message> ids) { checkNotNull(entityClass); @@ -64,7 +66,7 @@ public final class TopicFactory { * Creates a {@link Topic} for all of the specified entity states. * * @param entityClass the class of a target entity - * @return the instance of {@code Topic} assembled according to the parameters. + * @return the instance of {@code Topic} assembled according to the parameters */ public Topic allOf(Class<? extends Message> entityClass) { checkNotNull(entityClass); @@ -75,14 +77,13 @@ public final class TopicFactory { } /** - * Creates a {@link Topic} for the specified {@linkplain Target}. + * Creates a {@link Topic} for the specified {@link Target}. * - * <p>This method is intended for internal use only. To achieve the similar result, - * {@linkplain #allOf(Class) allOf()} and {@linkplain #someOf(Class, Set) someOf()} methods - * should be used. + * <p>This method is intended for internal use only. To achieve the similar result use + * {@linkplain #allOf(Class)} and {@linkplain #someOf(Class, Set)}. * - * @param target the {@code} Target to create a topic for. - * @return the instance of {@code Topic}. + * @param target the {@code Target} to create a topic for + * @return the instance of {@code Topic} */ @Internal public Topic forTarget(Target target) {
['client/src/main/java/io/spine/client/QueryFactory.java', 'client/src/main/java/io/spine/client/ActorRequestFactory.java', 'client/src/main/java/io/spine/client/TopicFactory.java', 'client/src/main/java/io/spine/client/CommandFactory.java', 'client/src/main/java/io/spine/client/QueryBuilder.java']
{'.java': 5}
5
5
0
0
5
1,899,725
380,937
51,150
430
9,326
2,014
154
5
426
67
90
12
0
1
"1970-01-01T00:25:19"
33
Java
{'Java': 6679521, 'Kotlin': 755047, 'Shell': 40419, 'CSS': 1739}
Apache License 2.0
9,856
ballerina-platform/openapi-tools/812/811
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/811
https://github.com/ballerina-platform/openapi-tools/pull/812
https://github.com/ballerina-platform/openapi-tools/pull/812
1
resolves
Invalid access of record field when the field name `key`
**Description:** Generated Code ```bal map<anydata> queryParam = {"id": id, "details": details, "key": self.apiKeyConfig.''key}; ``` Expected Code ```bal map<anydata> queryParam = {"id": id, "details": details, "key": self.apiKeyConfig.'key}; ``` Found in several connectors Ex: [BrowShot](https://github.com/ballerina-platform/openapi-connectors/blob/main/openapi/browshot/openapi.yaml) **Steps to reproduce:** **Affected Versions:** **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
03aec77c16c290a54ecb499d4f68d5cdeb1c68a0
2c88f8917ec1482e58d258be909051491f2ac92d
https://github.com/ballerina-platform/openapi-tools/compare/03aec77c16c290a54ecb499d4f68d5cdeb1c68a0...2c88f8917ec1482e58d258be909051491f2ac92d
diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java index 676c46d6..37efda31 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java @@ -728,7 +728,7 @@ public class FunctionBodyGenerator { createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), apiKeyConfigParamNode); SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode(createIdentifierToken( - getValidName(getValidName(apiKey, false), false))); + getValidName(apiKey, false))); SpecificFieldNode specificFieldNode; ExpressionNode apiKeyExpr = createFieldAccessExpressionNode( fieldExpr, createToken(DOT_TOKEN), valueExpr);
['openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java']
{'.java': 1}
1
1
0
0
1
987,456
189,381
20,808
128
132
23
2
1
1,180
139
263
30
1
2
"1970-01-01T00:27:19"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,857
ballerina-platform/openapi-tools/789/787
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/787
https://github.com/ballerina-platform/openapi-tools/pull/789
https://github.com/ballerina-platform/openapi-tools/pull/789
1
fix
OpenAPI build extension generate duplicate OAS for multiple service node in same ballerina file
**Description:** <!-- Give a brief description of the bug --> ```ballerina file import ballerina/http; listener http:Listener backendEP01 = check new(8080); listener http:Listener backendEP02 = check new(8081); service /v1 on backendEP01 { resource function get mock(@http:Payload json payload) returns string { return "Mock2 resource was invoked."; } } service /v1 on backendEP02 { resource function get .() returns string { return "Mock1 resource was invoked."; } } ``` This ballerina file build option generate duplicate yaml file **Steps to reproduce:** > bal build --export-openapi **Affected Versions:** Beta6 RC1 **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
ae85c2f26f9a0d41fa2c96a66a6108749016e83b
09458a860e6ec379722b10c96e1003ffd2c029ea
https://github.com/ballerina-platform/openapi-tools/compare/ae85c2f26f9a0d41fa2c96a66a6108749016e83b...09458a860e6ec379722b10c96e1003ffd2c029ea
diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/CodegenUtils.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/CodegenUtils.java index 66f6e3d9..7589282e 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/CodegenUtils.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/CodegenUtils.java @@ -34,6 +34,7 @@ import static io.ballerina.openapi.converter.Constants.YAML_EXTENSION; * Utilities used by ballerina openapi code generator. */ public final class CodegenUtils { + private static final String LINE_SEPARATOR = System.lineSeparator(); /** * Resolves path to write generated implementation source files. * diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java index 4fbe5503..4c278622 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java @@ -45,6 +45,8 @@ import io.ballerina.openapi.converter.diagnostic.DiagnosticMessages; import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.ballerina.tools.diagnostics.Location; import io.ballerina.tools.text.LinePosition; import io.ballerina.tools.text.LineRange; @@ -387,4 +389,9 @@ public class ConverterCommonUtils { return moduleNameOpt.isPresent() && Constants.HTTP.equals(moduleNameOpt.get()) && Constants.BALLERINA.equals(moduleSymbol.id().orgName()); } + + public static boolean containErrors(List<Diagnostic> diagnostics) { + return diagnostics != null && diagnostics.stream().anyMatch(diagnostic -> + diagnostic.diagnosticInfo().severity() == DiagnosticSeverity.ERROR); + } } diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java index efbe5b25..f8fd3e76 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java @@ -44,8 +44,6 @@ import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.model.OpenAPIInfo; import io.ballerina.openapi.converter.service.OpenAPIEndpointMapper; import io.ballerina.openapi.converter.service.OpenAPIServiceMapper; -import io.ballerina.tools.diagnostics.Diagnostic; -import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.ballerina.tools.diagnostics.Location; import io.swagger.v3.core.util.Json; import io.swagger.v3.core.util.Yaml; @@ -71,6 +69,7 @@ import static io.ballerina.openapi.converter.Constants.SLASH; import static io.ballerina.openapi.converter.Constants.SPECIAL_CHAR_REGEX; import static io.ballerina.openapi.converter.Constants.TITLE; import static io.ballerina.openapi.converter.Constants.VERSION; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.containErrors; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.getOpenApiFileName; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.isHttpService; @@ -131,11 +130,6 @@ public class ServiceToOpenAPIConverterUtils { return outputs; } - private static boolean containErrors(List<Diagnostic> diagnostics) { - return diagnostics != null && diagnostics.stream().anyMatch(diagnostic -> - diagnostic.diagnosticInfo().severity() == DiagnosticSeverity.ERROR); - } - /** * Filter all the end points and service nodes. */ diff --git a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java index 054479fa..727e5df9 100644 --- a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java +++ b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java @@ -17,14 +17,19 @@ package io.ballerina.openapi.build; import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.ServiceDeclarationSymbol; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; import io.ballerina.compiler.syntax.tree.ModulePartNode; import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.openapi.converter.diagnostic.DiagnosticMessages; import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; +import io.ballerina.openapi.converter.service.OpenAPIEndpointMapper; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; import io.ballerina.projects.BuildOptions; import io.ballerina.projects.Package; @@ -38,13 +43,20 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import static io.ballerina.openapi.build.PluginConstants.OAS_PATH_SEPARATOR; import static io.ballerina.openapi.build.PluginConstants.OPENAPI; +import static io.ballerina.openapi.build.PluginConstants.UNDERSCORE; +import static io.ballerina.openapi.converter.Constants.HYPHEN; +import static io.ballerina.openapi.converter.Constants.SLASH; import static io.ballerina.openapi.converter.utils.CodegenUtils.resolveContractFileName; import static io.ballerina.openapi.converter.utils.CodegenUtils.writeFile; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.containErrors; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.isHttpService; /** * SyntaxNodeAnalyzer for getting all service node. @@ -52,6 +64,7 @@ import static io.ballerina.openapi.converter.utils.CodegenUtils.writeFile; * @since 2.0.0 */ public class HttpServiceAnalysisTask implements AnalysisTask<SyntaxNodeAnalysisContext> { + @Override public void perform(SyntaxNodeAnalysisContext context) { SemanticModel semanticModel = context.semanticModel(); @@ -63,24 +76,26 @@ public class HttpServiceAnalysisTask implements AnalysisTask<SyntaxNodeAnalysisC if (!buildOptions.exportOpenAPI()) { return; } - // Take output path to target directory location in package. Path outPath = project.targetDir(); Optional<Path> path = currentPackage.project().documentPath(context.documentId()); Path inputPath = path.orElse(null); - // Traverse the service declaration nodes - ModulePartNode modulePartNode = syntaxTree.rootNode(); - List<OASResult> openAPIDefinitions = new ArrayList<>(); - for (Node node : modulePartNode.members()) { - SyntaxKind syntaxKind = node.kind(); - // Load a service declarations - if (syntaxKind == SyntaxKind.SERVICE_DECLARATION) { - openAPIDefinitions.addAll(ServiceToOpenAPIConverterUtils.generateOAS3Definition(syntaxTree, - semanticModel, null, false, inputPath)); - } - } + ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) context.node(); + List<ListenerDeclarationNode> endpoints = new ArrayList<>(); + Map<Integer, String> services = new HashMap<>(); List<Diagnostic> diagnostics = new ArrayList<>(); - if (!openAPIDefinitions.isEmpty()) { - extractOpenAPIYamlFromOutputs(outPath, openAPIDefinitions, diagnostics); + + // Spec generation won't proceed, If diagnostic includes error type. + if (containErrors(semanticModel.diagnostics())) { + diagnostics.addAll(semanticModel.diagnostics()); + } else if (isHttpService(serviceNode, semanticModel)) { + Optional<Symbol> serviceSymbol = semanticModel.symbol(serviceNode); + if (serviceSymbol.isPresent() && serviceSymbol.get() instanceof ServiceDeclarationSymbol) { + extractListenersAndServiceNodes(syntaxTree.rootNode(), endpoints, services, semanticModel); + OASResult oasResult = ServiceToOpenAPIConverterUtils.generateOAS(serviceNode, endpoints, + semanticModel, services.get(serviceSymbol.get().hashCode()), inputPath); + oasResult.setServiceName(constructFileName(syntaxTree, services, serviceSymbol.get())); + writeOpenAPIYaml(outPath, oasResult, diagnostics); + } } if (!diagnostics.isEmpty()) { for (Diagnostic diagnostic : diagnostics) { @@ -89,26 +104,79 @@ public class HttpServiceAnalysisTask implements AnalysisTask<SyntaxNodeAnalysisC } } - private void extractOpenAPIYamlFromOutputs(Path outPath, List<OASResult> openAPIDefinitions, - List<Diagnostic> diagnostics) { - for (OASResult oasResult: openAPIDefinitions) { - if (oasResult.getYaml().isPresent()) { - try { - // Create openapi directory if not exists in the path. If exists do not throw an error - Files.createDirectories(Paths.get(outPath + OAS_PATH_SEPARATOR + OPENAPI)); - String fileName = resolveContractFileName(outPath.resolve(OPENAPI), oasResult.getServiceName(), - false); - writeFile(outPath.resolve(OPENAPI + OAS_PATH_SEPARATOR + fileName), oasResult.getYaml().get()); - } catch (IOException e) { - DiagnosticMessages error = DiagnosticMessages.OAS_CONVERTOR_108; - ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), - error.getDescription(), null, e.toString()); - diagnostics.add(BuildExtensionUtil.getDiagnostics(diagnostic)); - } + /** + * This util function is to construct the generated file name. + * + * @param syntaxTree syntax tree for check the multiple services + * @param services service map for maintain the file name with updated name + * @param serviceSymbol symbol for taking the hash code of services + */ + private String constructFileName(SyntaxTree syntaxTree, Map<Integer, String> services, Symbol serviceSymbol) { + String fileName = services.get(serviceSymbol.hashCode()); + if (fileName.equals(SLASH)) { + return syntaxTree.filePath().split("\\\\.")[0]; + } else if (fileName.contains(HYPHEN) && fileName.split(HYPHEN)[0].equals(SLASH)) { + return syntaxTree.filePath().split("\\\\.")[0] + UNDERSCORE + + services.get(serviceSymbol.hashCode()).split(HYPHEN)[1]; + } else { + return services.get(serviceSymbol.hashCode()); + } + } + + private void writeOpenAPIYaml(Path outPath, OASResult oasResult, List<Diagnostic> diagnostics) { + if (oasResult.getYaml().isPresent()) { + try { + // Create openapi directory if not exists in the path. If exists do not throw an error + Files.createDirectories(Paths.get(outPath + OAS_PATH_SEPARATOR + OPENAPI)); + String fileName = resolveContractFileName(outPath.resolve(OPENAPI), oasResult.getServiceName(), + false); + writeFile(outPath.resolve(OPENAPI + OAS_PATH_SEPARATOR + fileName), oasResult.getYaml().get()); + } catch (IOException e) { + DiagnosticMessages error = DiagnosticMessages.OAS_CONVERTOR_108; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), + error.getDescription(), null, e.toString()); + diagnostics.add(BuildExtensionUtil.getDiagnostics(diagnostic)); + } + } + if (!oasResult.getDiagnostics().isEmpty()) { + for (OpenAPIConverterDiagnostic diagnostic : oasResult.getDiagnostics()) { + diagnostics.add(BuildExtensionUtil.getDiagnostics(diagnostic)); + } + } + } + + /** + * Filter all the end points and service nodes for avoiding the generated file name conflicts. + */ + private static void extractListenersAndServiceNodes(ModulePartNode modulePartNode, + List<ListenerDeclarationNode> endpoints, + Map<Integer, String> services, + SemanticModel semanticModel) { + List<String> allServices = new ArrayList<>(); + for (Node node : modulePartNode.members()) { + SyntaxKind syntaxKind = node.kind(); + // Load a listen_declaration for the server part in the yaml spec + if (syntaxKind.equals(SyntaxKind.LISTENER_DECLARATION)) { + ListenerDeclarationNode listener = (ListenerDeclarationNode) node; + endpoints.add(listener); } - if (!oasResult.getDiagnostics().isEmpty()) { - for (OpenAPIConverterDiagnostic diagnostic: oasResult.getDiagnostics()) { - diagnostics.add(BuildExtensionUtil.getDiagnostics(diagnostic)); + if (syntaxKind.equals(SyntaxKind.SERVICE_DECLARATION)) { + ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) node; + if (isHttpService(serviceNode, semanticModel)) { + // Here check the service is related to the http + // module by checking listener type that attached to service endpoints. + Optional<Symbol> serviceSymbol = semanticModel.symbol(serviceNode); + if (serviceSymbol.isPresent() && serviceSymbol.get() instanceof ServiceDeclarationSymbol) { + String service = OpenAPIEndpointMapper.ENDPOINT_MAPPER.getServiceBasePath(serviceNode); + String updateServiceName = service; + if (allServices.contains(service)) { + updateServiceName = service + HYPHEN + serviceSymbol.get().hashCode(); + } else { + // To generate for all services + allServices.add(service); + } + services.put(serviceSymbol.get().hashCode(), updateServiceName); + } } } } diff --git a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/PluginConstants.java b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/PluginConstants.java index 9a42f704..2376bc9b 100644 --- a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/PluginConstants.java +++ b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/PluginConstants.java @@ -23,4 +23,5 @@ package io.ballerina.openapi.build; public class PluginConstants { public static final String OPENAPI = "openapi"; public static final String OAS_PATH_SEPARATOR = "/"; + public static final String UNDERSCORE = "_"; }
['openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java', 'openapi-build-extension/src/main/java/io/ballerina/openapi/build/PluginConstants.java', 'openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java', 'openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java', 'openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/CodegenUtils.java']
{'.java': 5}
5
5
0
0
5
961,457
184,644
20,346
127
9,404
1,687
151
5
1,398
188
300
34
0
1
"1970-01-01T00:27:18"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,858
ballerina-platform/openapi-tools/736/735
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/735
https://github.com/ballerina-platform/openapi-tools/pull/736
https://github.com/ballerina-platform/openapi-tools/pull/736
1
fix
OpenAPI validator plugin gives error when ballerina file has multiple service
**Description:** Gives error for below example ```ballerina import ballerina/http; import ballerina/openapi; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { resource function get pets(http:Caller caller, http:Request req) returns error? { } resource function post pets(http:Caller caller, http:Request req) returns error? { } resource function get pets/[int petId](http:Caller caller, http:Request req) returns error? { } } @openapi:ServiceInfo { contract: "openapiwetherMap.yaml", tags: [ ], operations:[] } service /data/'2\\.5 on new http:Listener(9090) { resource function get weather(string? id, string? lat, string? lon, string? zip, string? units, string? lang, string? mode) returns string { return "hello"; } resource function get onecall(string lat, string lon, string? exclude, string? units, string? lang) returns string { return "hello"; } } ``` error ``` error: compilation failed: The compiler extension in package 'ballerina:openapi:0.9.0-beta.4' failed to complete. No value present ``` **expected** : give the warring diagnostic for relevant service node **Affected Versions:** Swank lanke Beta4 rc2 **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
a9df05e769a3016665c5247638ce470868da9b14
c537f44f4468d9c68e7154ed180b116dd9c13f12
https://github.com/ballerina-platform/openapi-tools/compare/a9df05e769a3016665c5247638ce470868da9b14...c537f44f4468d9c68e7154ed180b116dd9c13f12
diff --git a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java index 8b162e86..12fb5754 100644 --- a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java +++ b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java @@ -100,10 +100,13 @@ public class ServiceValidator implements AnalysisTask<SyntaxNodeAnalysisContext> // Load a service declarations for the path part in the yaml spec if (syntaxKind.equals(SyntaxKind.SERVICE_DECLARATION)) { ServiceDeclarationNode serviceDeclarationNode = (ServiceDeclarationNode) node; - location = serviceDeclarationNode.location(); - // Check annotation is available - kind = getDiagnosticFromServiceNode(functions, kind, filters, semanticModel, syntaxTree, - ballerinaFilePath, serviceDeclarationNode); + Optional<MetadataNode> metadata = serviceDeclarationNode.metadata(); + if (metadata.isPresent()) { + location = serviceDeclarationNode.location(); + // Check annotation is available + kind = getDiagnosticFromServiceNode(functions, kind, filters, semanticModel, syntaxTree, + ballerinaFilePath, serviceDeclarationNode); + } } } if (!validations.isEmpty()) {
['openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java']
{'.java': 1}
1
1
0
0
1
862,013
163,743
18,038
101
741
114
11
1
2,000
255
467
50
0
2
"1970-01-01T00:27:17"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,860
ballerina-platform/openapi-tools/575/573
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/573
https://github.com/ballerina-platform/openapi-tools/pull/575
https://github.com/ballerina-platform/openapi-tools/pull/575
1
fix
OpenAPI module compiler plugin breaks when the `contract` path is invalid in `openapi:ServiceInfo` annotation
**Description:** OpenAPI module compiler plugin breaks when the `contract` path is invalid in `openapi:ServiceInfo` annotation. **Steps to reproduce:** * Use following sample code. ```ballerina import ballerina/http; import ballerina/openapi; @openapi:ServiceInfo{ contract: "service_openapi.json" } @http:ServiceConfig {compression: {enable: http:COMPRESSION_AUTO}} service / on new http:Listener(9090) { resource function get greeting() returns string { return "Hello, World!"; } } ``` * Remove `service_openapi.json` from current working directory. * Build the ballerina project/file. * Following compilation error could be seen. (detailed stack-trace is attached to the issue) ``` error: compilation failed: The compiler extension in package 'ballerina:openapi:0.9.0-beta.2' failed to complete. null ``` [open-api-bug.txt](https://github.com/ballerina-platform/ballerina-openapi/files/7131331/open-api-bug.txt) **Affected Versions:** * Ballerina SL Beta 2
da96c0e264760391f1efdd2a855970efea7f155b
a4e010cdd6475766d1ecb4aed85cd17e4e6f2f27
https://github.com/ballerina-platform/openapi-tools/compare/da96c0e264760391f1efdd2a855970efea7f155b...a4e010cdd6475766d1ecb4aed85cd17e4e6f2f27
diff --git a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java index 72fd9f6a..e895df9e 100644 --- a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java +++ b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java @@ -67,6 +67,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static io.ballerina.openapi.validator.ValidatorErrorCode.BAL_OPENAPI_VALIDATOR_0018; import static io.ballerina.openapi.validator.ValidatorErrorCode.BAL_OPENAPI_VALIDATOR_0019; import static io.ballerina.openapi.validator.ValidatorErrorCode.BAL_OPENAPI_VALIDATOR_0020; @@ -139,7 +140,7 @@ public class ServiceValidator implements AnalysisTask<SyntaxNodeAnalysisContext> if (!validations.isEmpty()) { // when the contract has empty string for (Diagnostic diagnostic: validations) { - if (diagnostic.diagnosticInfo().code().equals(BAL_OPENAPI_VALIDATOR_0019) || + if (diagnostic.diagnosticInfo().code().equals(BAL_OPENAPI_VALIDATOR_0018) || diagnostic.diagnosticInfo().code().equals(BAL_OPENAPI_VALIDATOR_0020)) { isAnnotationExist = false; } @@ -150,6 +151,7 @@ public class ServiceValidator implements AnalysisTask<SyntaxNodeAnalysisContext> e.getMessage(), DiagnosticSeverity.ERROR); Diagnostic diagnostic = DiagnosticFactory.createDiagnostic(diagnosticInfo, location); validations.add(diagnostic); + isAnnotationExist = false; } } }
['openapi-validator/src/main/java/io/ballerina/openapi/validator/ServiceValidator.java']
{'.java': 1}
1
1
0
0
1
760,088
142,417
15,826
78
376
76
4
1
1,016
104
250
32
1
2
"1970-01-01T00:27:11"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,861
ballerina-platform/openapi-tools/543/544
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/544
https://github.com/ballerina-platform/openapi-tools/pull/543
https://github.com/ballerina-platform/openapi-tools/pull/543
1
fix
The Ballerina to OpenAPI command return type casting error for listeners
**Description:** Related issue https://github.com/wso2-enterprise/choreo/issues/7447 Since the Ballerina to OpenAPI command implement base on the HTTP protocol , it won't support for listener and other parameters from other packages
d5988a9d381c861e1bc6962e4d58e0d84c7db68d
c8619e5c20ddd8045d06644049e6c8c9c39ebea4
https://github.com/ballerina-platform/openapi-tools/compare/d5988a9d381c861e1bc6962e4d58e0d84c7db68d...c8619e5c20ddd8045d06644049e6c8c9c39ebea4
diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java index a7f8a624..7e20d736 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java @@ -158,7 +158,7 @@ public class OpenAPIEndpointMapper { if (list.isPresent()) { SeparatedNodeList<FunctionArgumentNode> arg = (list.get()).arguments(); port = arg.get(0).toString(); - if (arg.size() > 1) { + if (arg.size() > 1 && (arg.get(1) instanceof NamedArgumentNode)) { ExpressionNode bLangRecordLiteral = ((NamedArgumentNode) arg.get(1)).expression(); if (bLangRecordLiteral instanceof MappingConstructorExpressionNode) { host = extractHost((MappingConstructorExpressionNode) bLangRecordLiteral);
['openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java']
{'.java': 1}
1
1
0
0
1
740,817
138,685
15,359
77
114
33
2
1
234
28
51
3
1
0
"1970-01-01T00:27:09"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,863
ballerina-platform/openapi-tools/377/376
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/376
https://github.com/ballerina-platform/openapi-tools/pull/377
https://github.com/ballerina-platform/openapi-tools/pull/377
1
fix
Json open-api definition files are not supported in the tool
**Description:** > When executing `bal openapi -i openapi.json --mode client` on a json type open-api definition file following error is returned ``` Invalid file type. Provide either a .yaml or .json file. ``` **Suggested Labels:** * Bug
7ee67005fabd7dc795e89967c090f771c543f1cc
158f04d5ff699dcdec1a6fea0a2ccf49e534b398
https://github.com/ballerina-platform/openapi-tools/compare/7ee67005fabd7dc795e89967c090f771c543f1cc...158f04d5ff699dcdec1a6fea0a2ccf49e534b398
diff --git a/openapi-cli/src/main/java/io/ballerina/generators/GeneratorUtils.java b/openapi-cli/src/main/java/io/ballerina/generators/GeneratorUtils.java index 00c1f58c..e25c6c81 100644 --- a/openapi-cli/src/main/java/io/ballerina/generators/GeneratorUtils.java +++ b/openapi-cli/src/main/java/io/ballerina/generators/GeneratorUtils.java @@ -414,9 +414,8 @@ public class GeneratorUtils { if (!Files.exists(contractPath)) { throw new BallerinaOpenApiException(ErrorMessages.invalidFilePath(definitionPath.toString())); } - if (!(definitionPath.toString().endsWith(".yaml") || definitionPath.endsWith(".json") || - definitionPath.toString().endsWith( - ".yml"))) { + if (!(definitionPath.toString().endsWith(".yaml") || definitionPath.toString().endsWith(".json") || + definitionPath.toString().endsWith(".yml"))) { throw new BallerinaOpenApiException(ErrorMessages.invalidFileType()); } String openAPIFileContent = Files.readString(definitionPath);
['openapi-cli/src/main/java/io/ballerina/generators/GeneratorUtils.java']
{'.java': 1}
1
1
0
0
1
626,755
115,749
12,843
55
352
66
5
1
244
37
59
7
0
1
"1970-01-01T00:27:06"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
8,595
mythicdrops/mythicdrops/376/375
mythicdrops
mythicdrops
https://github.com/MythicDrops/MythicDrops/issues/375
https://github.com/MythicDrops/MythicDrops/pull/376
https://github.com/MythicDrops/MythicDrops/pull/376
1
fixes
Custom Socket Names Not Working
5.0.1 release candidate from the Discord, Spigot 1.13.2 Editing the socket-name in the socketting file stops the socket gems from working at all. For example if I have it set to `&5Power Gem - &6%socketgem%` it works fine, however if I even change it just to`&5Power Gem &7- &6%socketgem%` the gems no longer do anything. Ideally I'd like to be able to have custom symbols in it as well, such as having it as `&6✧ &5Power Gem &6✧ &7-- &d%socketgem%` due to having item drop names visible - the plugin parses the symbol fine and the item is given with the symbol, but as above due to the altered name it does nothing.
bc94d9fdb67b309a9a32a5f4db87e768215831dc
465cf9dedf4782d17dae667aa769c3725f3e3beb
https://github.com/mythicdrops/mythicdrops/compare/bc94d9fdb67b309a9a32a5f4db87e768215831dc...465cf9dedf4782d17dae667aa769c3725f3e3beb
diff --git a/src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/socketting/SockettingListener.java b/src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/socketting/SockettingListener.java index 6c5b8e2a..2e1bad33 100644 --- a/src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/socketting/SockettingListener.java +++ b/src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/socketting/SockettingListener.java @@ -34,12 +34,6 @@ import com.tealcube.minecraft.bukkit.mythicdrops.utils.ItemUtil; import com.tealcube.minecraft.bukkit.mythicdrops.utils.SocketGemUtil; import com.tealcube.minecraft.bukkit.mythicdrops.utils.StringListUtil; import com.tealcube.minecraft.bukkit.mythicdrops.utils.TierUtil; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.enchantments.Enchantment; @@ -54,9 +48,13 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; +import java.util.*; +import java.util.logging.Logger; + public final class SockettingListener implements Listener { private static final Logger LOGGER = MythicLoggerFactory.getLogger(SockettingListener.class); @@ -79,6 +77,10 @@ public final class SockettingListener implements Listener { LOGGER.fine("event.getAction() != RIGHT_CLICK_AIR && event.getAction() != RIGHT_CLICK_BLOCK"); return; } + if (event.getHand() != EquipmentSlot.HAND) { + LOGGER.fine("event.getHand() != EquipmentSlot.HAND"); + return; + } Player player = event.getPlayer(); if (player.getEquipment() == null) { LOGGER.fine("player.getEquipment() == null"); @@ -99,10 +101,10 @@ public final class SockettingListener implements Listener { LOGGER.fine("heldSocket.containsKey(" + player.getName() + ")"); socketItem(event, player, itemInMainHand, itemInMainHandType); heldSocket.remove(player.getName()); - } else { - LOGGER.fine("!heldSocket.containsKey(" + player.getName() + ")"); - addHeldSocket(event, player, itemInMainHand); + return; } + LOGGER.fine("!heldSocket.containsKey(" + player.getName() + ")"); + addHeldSocket(event, player, itemInMainHand); } private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) { @@ -122,7 +124,8 @@ public final class SockettingListener implements Listener { String socketGemNameFormat = replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", ""}}); String coloredSocketGemNameFormat = socketGemNameFormat.replace('&', '\\u00A7').replace("\\u00A7\\u00A7", "&"); String strippedSocketGemNameFormat = ChatColor.stripColor(coloredSocketGemNameFormat); - String type = ChatColor.stripColor(im.getDisplayName().replace(strippedSocketGemNameFormat, "")); + String strippedImDisplayName = ChatColor.stripColor(im.getDisplayName()); + String type = ChatColor.stripColor(strippedImDisplayName.replace(strippedSocketGemNameFormat, "")); if (type == null) { LOGGER.fine("type == null"); return; @@ -130,7 +133,6 @@ public final class SockettingListener implements Listener { String socketGemNameFormatWithType = replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", type}}); String coloredSocketGemNameFormatWithType = socketGemNameFormatWithType.replace('&', '\\u00A7').replace("\\u00A7\\u00A7", "&"); String strippedSocketGemNameFormatWithType = ChatColor.stripColor(coloredSocketGemNameFormatWithType); - String strippedImDisplayName = ChatColor.stripColor(im.getDisplayName()); if (!strippedSocketGemNameFormatWithType.equals(strippedImDisplayName)) { LOGGER.fine("!strippedSocketGemNameFormatWithType.equals(strippedImDisplayName): " + "strippedSocketGemNameFormatWithType=\\"" + strippedSocketGemNameFormatWithType + "\\" " +
['src/main/java/com/tealcube/minecraft/bukkit/mythicdrops/socketting/SockettingListener.java']
{'.java': 1}
1
1
0
0
1
440,579
98,499
12,395
75
1,040
221
24
1
625
113
174
7
0
0
"1970-01-01T00:26:03"
32
Kotlin
{'Kotlin': 1281863, 'JavaScript': 7655, 'CSS': 5286, 'Shell': 244}
MIT License
9,832
ballerina-platform/openapi-tools/1409/1401
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1401
https://github.com/ballerina-platform/openapi-tools/pull/1409
https://github.com/ballerina-platform/openapi-tools/pull/1409
1
resolves
OpenAPI LS Extension returns wrong response without running the code modifier
**Description:** We have introduced a default http payload parameter support in 2201.5.x. It automatically adds the payload annotation to a compatible signature parameter type using the code modifier. This change has been adhered to open API-tools by running the code modifiers before generating the document. But seems like we have missed adding this to the LS extension which is used for `Try it` feature in the VS code. **Steps to reproduce:** Use the [following BBE ](https://ballerina.io/learn/by-example/http-service-data-binding/)in the VS code and click on the `Try it` option to see the openAPI. The parameter is shown as a query parameter. This `Try it` feature uses the `openAPILSExtension/generateOpenAPI` API to generate the openAPI. **Affected Versions:** 2201.5.x, 2201.6.0
20520d8072a88961d28ff83acaf699e220b11bc5
91563ce8cfe610f0ad9e83031e4012a23da36138
https://github.com/ballerina-platform/openapi-tools/compare/20520d8072a88961d28ff83acaf699e220b11bc5...91563ce8cfe610f0ad9e83031e4012a23da36138
diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index 7015c08b..c098b301 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -30,10 +30,10 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; import io.ballerina.projects.Document; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; -import io.ballerina.projects.Package; import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -136,16 +136,21 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { response.setError("Error while getting the project."); return response; } - Package aPackage = module.get().currentPackage(); - Collection<Diagnostic> diagnostics = aPackage.getCompilation().diagnosticResult().diagnostics(); - boolean hasErrors = diagnostics.stream() + DiagnosticResult diagnosticsFromCodeGenAndModify = module.get() + .currentPackage() + .runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + Collection<Diagnostic> compilationDiagnostics = module.get().currentPackage() + .getCompilation().diagnosticResult().diagnostics(); + boolean hasCompilationErrors = compilationDiagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = aPackage.getDefaultModule(); + Module defaultModule = module.get().currentPackage().getDefaultModule(); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) {
['openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java']
{'.java': 1}
1
1
0
0
1
1,255,696
241,002
26,308
139
1,185
201
17
1
811
114
187
15
1
0
"1970-01-01T00:28:07"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,365
adessose/budgeteer/444/442
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/442
https://github.com/adessoSE/budgeteer/pull/444
https://github.com/adessoSE/budgeteer/pull/444
1
closes
contract: Contract summary creation is missing null safety when accessing attributes
If a Contract is missing the custom field value "rechnungsempfaenger" as required by ContractReportService.createSummary, it exits with an internal error, since ContractReportService.getAttribute is missing null safety. @tinne attached this stack trace: [budgeteer.-.ContractReportService.log](https://github.com/adessoAG/budgeteer/files/5545655/budgeteer.-.ContractReportService.log)
3e5af41d27ccd141ff1919172365c174b47d18fe
c360cb77db33d1839213566b77929ffd1b8fb396
https://github.com/adessose/budgeteer/compare/3e5af41d27ccd141ff1919172365c174b47d18fe...c360cb77db33d1839213566b77929ffd1b8fb396
diff --git a/budgeteer-report-exporter/src/main/java/org/wickedsource/budgeteer/SheetTemplate/SheetTemplateSerializable.java b/budgeteer-report-exporter/src/main/java/org/wickedsource/budgeteer/SheetTemplate/SheetTemplateSerializable.java index 55e50c1b..86503fdb 100644 --- a/budgeteer-report-exporter/src/main/java/org/wickedsource/budgeteer/SheetTemplate/SheetTemplateSerializable.java +++ b/budgeteer-report-exporter/src/main/java/org/wickedsource/budgeteer/SheetTemplate/SheetTemplateSerializable.java @@ -1,6 +1,22 @@ package org.wickedsource.budgeteer.SheetTemplate; +import java.util.Collection; +import java.util.Objects; +import java.util.stream.Stream; + public interface SheetTemplateSerializable { public String getName(); public Object getValue(); + + static String getAttribute(String attribute, Collection<? extends SheetTemplateSerializable> collection) { + Stream<? extends SheetTemplateSerializable> stream = collection == null ? Stream.empty() : collection.stream(); + + return stream + .filter(entry -> entry.getName().equals(attribute)) + .map(SheetTemplateSerializable::getValue) + .filter(Objects::nonNull) + .map(Object::toString) + .findFirst() + .orElse(""); + } } diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/budget/report/BudgetReportService.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/budget/report/BudgetReportService.java index 30f4a1ad..8b6a9096 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/budget/report/BudgetReportService.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/budget/report/BudgetReportService.java @@ -1,7 +1,6 @@ package org.wickedsource.budgeteer.service.budget.report; import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NotImplementedFunctionException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFSheet; @@ -29,10 +28,7 @@ import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; @Service @@ -113,7 +109,7 @@ public class BudgetReportService { private List<BudgetSummary> createBudgetSummary(List<BudgetReportData> budgetList) { Set<String> recipients = new HashSet<>(); budgetList.forEach( - budget -> recipients.add(getAttribute("rechnungsempfaenger", budget.getAttributes()))); + budget -> recipients.add(SheetTemplateSerializable.getAttribute("rechnungsempfaenger", budget.getAttributes()))); List<BudgetSummary> summary = recipients.stream().map(description -> new BudgetSummary(description)) .collect(Collectors.toList()); @@ -124,18 +120,6 @@ public class BudgetReportService { return templateService.getById(id).getWb(); } - private String getAttribute(String string, List<? extends SheetTemplateSerializable> list) { - if (null == list) { - return ""; - } - for (SheetTemplateSerializable listEntry : list) { - if (listEntry.getName().equals(string)) { - return listEntry.getValue().toString(); - } - } - return ""; - } - private File createOutputFile(XSSFWorkbook wb) { File outputFile = null; FileOutputStream out; diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/report/ContractReportService.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/report/ContractReportService.java index 1f72158a..9944c267 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/report/ContractReportService.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/report/ContractReportService.java @@ -18,6 +18,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; +import java.util.stream.Stream; @Transactional @Service @@ -69,25 +70,13 @@ public class ContractReportService { private List<ContractReportSummary> createSummary(List<ContractReportData> contractReportList) { Set<String> recipients = new HashSet<>(); contractReportList.forEach( - contract -> recipients.add(getAttribute("rechnungsempfaenger", contract.getAttributes()))); + contract -> recipients.add(SheetTemplateSerializable.getAttribute("rechnungsempfaenger", contract.getAttributes()))); List<ContractReportSummary> summary = recipients.stream().map(description -> new ContractReportSummary(description)) .collect(Collectors.toList()); return summary; } - private String getAttribute(String string, List<? extends SheetTemplateSerializable> list) { - if (null == list) { - return ""; - } - for (SheetTemplateSerializable listEntry : list) { - if (listEntry.getName().equals(string)) { - return listEntry.getValue().toString(); - } - } - return ""; - } - private File outputfile(XSSFWorkbook wb) { File outputFile = null; FileOutputStream out;
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/budget/report/BudgetReportService.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/report/ContractReportService.java', 'budgeteer-report-exporter/src/main/java/org/wickedsource/budgeteer/SheetTemplate/SheetTemplateSerializable.java']
{'.java': 3}
3
3
0
0
3
1,011,931
207,695
25,370
418
1,837
405
51
3
390
32
87
5
1
0
"1970-01-01T00:26:45"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,366
adessose/budgeteer/438/383
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/383
https://github.com/adessoSE/budgeteer/pull/438
https://github.com/adessoSE/budgeteer/pull/438
1
closes
Adding beginning and end to a late project
When I edit a project which existed before (in the view of the Budgeteer data model) a project had a start and end date, in its administration view the project time frame is displayed as the current year, e.g. 1/1/19–12/31/19. This works as expected, as it was the required migrational view. Now that I come and enter the real date data of the project, e.g., 1/1/16–12/31/16 and save, the view confirms the successful storage of the time frame and... reverts the view to 1/1/19–12/31/19. It should not be necessary to reload the view to see the correctly stored (but incorrectly not displayed) new project time frame. As it is a migrational issue, the priority is pretty low. Then again, it should be easy to fix and a good educational example.
3e5af41d27ccd141ff1919172365c174b47d18fe
45c0ec37691dafded2724a65dc20ba15e74bc23d
https://github.com/adessose/budgeteer/compare/3e5af41d27ccd141ff1919172365c174b47d18fe...45c0ec37691dafded2724a65dc20ba15e74bc23d
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/administration/ProjectAdministrationPage.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/administration/ProjectAdministrationPage.java index 3d1ef66d..86f41706 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/administration/ProjectAdministrationPage.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/administration/ProjectAdministrationPage.java @@ -70,8 +70,10 @@ public class ProjectAdministrationPage extends BasePage { } }; form.add(new TextField<String>("projectTitle", model(from(form.getModelObject()).getName()))); - DateRange defaultDateRange = new DateRange(DateUtil.getBeginOfYear(), DateUtil.getEndOfYear()); - form.add(new DateRangeInputField("projectStart", model(from(form.getModelObject()).getDateRange()), defaultDateRange, DateRangeInputField.DROP_LOCATION.DOWN)); + if (form.getModelObject().getDateRange().getStartDate() == null || form.getModelObject().getDateRange().getEndDate() == null) { + form.getModelObject().setDateRange(new DateRange(DateUtil.getBeginOfYear(), DateUtil.getEndOfYear())); + } + form.add(new DateRangeInputField("projectStart", model(from(form.getModelObject()).getDateRange()), DateRangeInputField.DROP_LOCATION.DOWN)); return form; }
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/administration/ProjectAdministrationPage.java']
{'.java': 1}
1
1
0
0
1
1,011,931
207,695
25,370
418
688
139
6
1
753
130
189
7
0
0
"1970-01-01T00:26:44"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,367
adessose/budgeteer/437/426
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/426
https://github.com/adessoSE/budgeteer/pull/437
https://github.com/adessoSE/budgeteer/pull/437
1
closes
Risk of calling WorkRecordRepository.updateDailyRates with null values
When updating the daily rates in the PersonService by calling the updateDailyRates method in the WorkRecordRepository there is the risk of executing this query with null values. This code snippet show the issue: ` workRecordRepository.updateDailyRates(rate.getBudget().getId(), person.getPersonId(), rate.getDateRange().getStartDate(), rate.getDateRange().getEndDate(), rate.getRate());` The rate is an instance of the class PersonRate, which got a NoArgsConstructor and a reset method. That's why there is the possibility of null values. Additionally, it should be investigated if the reset method should remain. By resetting a PersonRate there is the chance of inconsistent data because resetting the rate loses the connection to the WorkRecords. Then the rate remains in the work records but the rate itself is reset.
ed1cd425a003100fa57dca0cd6d62b587005667b
34306423841fb1f1e802521fd5c7af2fc0026ea7
https://github.com/adessose/budgeteer/compare/ed1cd425a003100fa57dca0cd6d62b587005667b...34306423841fb1f1e802521fd5c7af2fc0026ea7
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonRate.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonRate.java index 21289f46..951a6929 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonRate.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonRate.java @@ -1,11 +1,10 @@ package org.wickedsource.budgeteer.service.person; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; import org.joda.money.Money; import org.wickedsource.budgeteer.service.DateRange; import org.wickedsource.budgeteer.service.budget.BudgetBaseData; @@ -13,30 +12,11 @@ import org.wickedsource.budgeteer.service.budget.BudgetBaseData; import java.io.Serializable; @Data -@NoArgsConstructor +@NoArgsConstructor(access = AccessLevel.NONE) @AllArgsConstructor @Accessors(chain = true) public class PersonRate implements Serializable { - private Money rate; private BudgetBaseData budget; private DateRange dateRange; - - @Override - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - public boolean equals(Object obj) { - return EqualsBuilder.reflectionEquals(this, obj); - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - public void reset(){ - rate = null; - budget = null; - dateRange = null; - } - } diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonService.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonService.java index 05b267a7..918aa6c0 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonService.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonService.java @@ -20,7 +20,9 @@ import org.wickedsource.budgeteer.web.planning.Person; import javax.transaction.Transactional; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Optional; @Service @@ -85,10 +87,9 @@ public class PersonService { budget.setId(rateEntity.getBudget().getId()); budget.setName(rateEntity.getBudget().getName()); - PersonRate rate = new PersonRate(); - rate.setBudget(budget); - rate.setDateRange(new DateRange(rateEntity.getDateStart(), rateEntity.getDateEnd())); - rate.setRate(rateEntity.getRate()); + PersonRate rate = new PersonRate(rateEntity.getRate(), + budget, + new DateRange(rateEntity.getDateStart(), rateEntity.getDateEnd())); person.getRates().add(rate); } @@ -101,15 +102,24 @@ public class PersonService { * * @param person the data to save in the database. */ - public void savePersonWithRates(PersonWithRates person) { + public List<String> savePersonWithRates(PersonWithRates person) { PersonEntity personEntity = personRepository.findOne(person.getPersonId()); personEntity.setName(person.getName()); personEntity.setImportKey(person.getImportKey()); personEntity.setDefaultDailyRate(person.getDefaultDailyRate()); List<DailyRateEntity> dailyRates = new ArrayList<>(); - + List<String> errors = new ArrayList<>(); for (PersonRate rate : person.getRates()) { + List<String> errorList = this.updateDailyRates(rate.getBudget(), + person, + rate.getDateRange(), + rate.getRate()); + + if (!errorList.isEmpty()) { + errors.addAll(errorList); + continue; + } DailyRateEntity rateEntity = new DailyRateEntity(); rateEntity.setRate(rate.getRate()); @@ -118,14 +128,12 @@ public class PersonService { rateEntity.setDateStart(rate.getDateRange().getStartDate()); rateEntity.setDateEnd(rate.getDateRange().getEndDate()); dailyRates.add(rateEntity); - workRecordRepository.updateDailyRates(rate.getBudget().getId(), person.getPersonId(), - rate.getDateRange().getStartDate(), rate.getDateRange().getEndDate(), rate.getRate()); - } personEntity.getDailyRates().clear(); personEntity.getDailyRates().addAll(dailyRates); personRepository.save(personEntity); + return errors; } public List<String> getOverlapWithManuallyEditedRecords(PersonWithRates person, long projectId){ @@ -178,7 +186,33 @@ public class PersonService { } public void removeDailyRateFromPerson(PersonWithRates personWithRates, PersonRate rate) { - workRecordRepository.updateDailyRates(rate.getBudget().getId(), personWithRates.getPersonId(), - rate.getDateRange().getStartDate(), rate.getDateRange().getEndDate(), Money.zero(CurrencyUnit.EUR)); + this.updateDailyRates(rate.getBudget(), personWithRates, rate.getDateRange(), Money.zero(CurrencyUnit.EUR)); + } + + private List<String> updateDailyRates(BudgetBaseData budget, PersonWithRates person, DateRange dateRange, Money dailyRate) { + List<String> errorMessages = new ArrayList<>(); + if (budget == null) { + errorMessages.add("Budget shouldn't be null!"); + } + if (person == null){ + errorMessages.add("Person shouldn't be null!"); + } + if (dailyRate == null) { + errorMessages.add("Daily Rate shouldn't be null!"); + } + if (dateRange == null || dateRange.getStartDate() == null || dateRange.getEndDate() == null) { + errorMessages.add("Date Range shouldn't be null!"); + } + + if (!errorMessages.isEmpty()) { + errorMessages.add("The Daily Rate wasn't updated because of invalid values"); + return errorMessages; + } + workRecordRepository.updateDailyRates(budget.getId(), + person.getPersonId(), + dateRange.getStartDate(), + dateRange.getEndDate(), + dailyRate); + return Collections.emptyList(); } } diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/person/edit/personrateform/EditPersonForm.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/person/edit/personrateform/EditPersonForm.java index 569f2464..ca77b2ac 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/person/edit/personrateform/EditPersonForm.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/person/edit/personrateform/EditPersonForm.java @@ -150,12 +150,15 @@ public class EditPersonForm extends Form<PersonWithRates> { EditPersonForm.this.getModelObject().setName(nameTextField.getInput()); EditPersonForm.this.getModelObject().setImportKey(importKeyTextField.getInput()); EditPersonForm.this.getModelObject().setDefaultDailyRate(defaultDailyRate); - personService.savePersonWithRates(EditPersonForm.this.getModelObject()); + List<String> errors = personService.savePersonWithRates(EditPersonForm.this.getModelObject()); List<String> warnings = personService.getOverlapWithManuallyEditedRecords(EditPersonForm.this.getModelObject(), BudgeteerSession.get().getProjectId()); this.success(getString("form.success")); - for (String e : warnings) { - this.info(e); + for (String warning : warnings) { + this.info(warning); + } + for (String error : errors) { + this.error(error); } } showMissingDailyRateContainer(); @@ -193,10 +196,10 @@ public class EditPersonForm extends Form<PersonWithRates> { } List<PersonRate> missingRates = missingDailyRateForBudgetBeans.stream() - .map(missingDailyRate -> new PersonRate() - .setBudget(budgetService.loadBudgetBaseData(missingDailyRate.getBudgetId())) - .setRate(currentDefaultDailyRate) - .setDateRange(new DateRange(missingDailyRate.getStartDate(), missingDailyRate.getEndDate()))) + .map(missingDailyRate -> new PersonRate(currentDefaultDailyRate, + budgetService.loadBudgetBaseData(missingDailyRate.getBudgetId()), + new DateRange(missingDailyRate.getStartDate(), missingDailyRate.getEndDate()) + )) .collect(Collectors.toList()); EditPersonForm.this.getModelObject().getRates().addAll(missingRates); diff --git a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/person/PersonServiceIntegrationTest.java b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/person/PersonServiceIntegrationTest.java index 6bee7e12..26cbc79c 100644 --- a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/person/PersonServiceIntegrationTest.java +++ b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/person/PersonServiceIntegrationTest.java @@ -56,15 +56,13 @@ class PersonServiceIntegrationTest extends IntegrationTestTemplate { person.setPersonId(1L); person.setName("name"); person.setImportKey("name"); - PersonRate rate1 = new PersonRate(); - rate1.setRate(MoneyUtil.createMoneyFromCents(12300L)); - rate1.setDateRange(new DateRange(format.parse("01.01.2014"), format.parse("15.08.2014"))); - rate1.setBudget(new BudgetBaseData(1L, "budget1")); + PersonRate rate1 = new PersonRate(MoneyUtil.createMoneyFromCents(12300L), + new BudgetBaseData(1L, "budget1"), + new DateRange(format.parse("01.01.2014"), format.parse("15.08.2014"))); person.getRates().add(rate1); - PersonRate rate2 = new PersonRate(); - rate2.setRate(MoneyUtil.createMoneyFromCents(32100L)); - rate2.setDateRange(new DateRange(format.parse("01.01.2015"), format.parse("15.08.2015"))); - rate2.setBudget(new BudgetBaseData(1L, "budget1")); + PersonRate rate2 = new PersonRate(MoneyUtil.createMoneyFromCents(32100L), + new BudgetBaseData(1L, "budget1"), + new DateRange(format.parse("01.01.2015"), format.parse("15.08.2015"))); person.getRates().add(rate2); service.savePersonWithRates(person);
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonRate.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/person/PersonService.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/person/edit/personrateform/EditPersonForm.java', 'budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/person/PersonServiceIntegrationTest.java']
{'.java': 4}
4
4
0
0
4
1,018,916
208,940
25,478
418
4,511
798
97
3
844
111
164
8
0
0
"1970-01-01T00:26:44"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,368
adessose/budgeteer/436/422
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/422
https://github.com/adessoSE/budgeteer/pull/436
https://github.com/adessoSE/budgeteer/pull/436
1
fixes
Error displaying person details for non-existing people
In the current merge HEAD of project 1 (maybe after merging #413?) an internal error is triggered when displaying the details page of a person that has not yet been created but for whom hours have been imported - the expected behaviour is to display basic information and let the user create a new person as it used be. The logs contain the following stacktrace: ``` 16:12:14.541 [https-jsse-nio-8337-exec-10] ERROR o.a.wicket.DefaultExceptionMapper - Unexpected error occurred org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: could not instantiate class [org.wickedsource.budgeteer.persistence.person.PersonDetailDataBean] from tuple; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: could not instantiate class [org.wickedsource.budgeteer.persistence.person.PersonDetailDataBean] from tuple at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:246) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy108.findDetailDataByPersonId(Unknown Source) at org.wickedsource.budgeteer.service.person.PersonService.loadPersonDetailData(PersonService.java:64) at org.wickedsource.budgeteer.service.person.PersonService$$FastClassBySpringCGLIB$$4319f311.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) at org.wickedsource.budgeteer.service.person.PersonService$$EnhancerBySpringCGLIB$$40b2178.loadPersonDetailData(<generated>) at WICKET_org.wickedsource.budgeteer.service.person.PersonService$$FastClassByCGLIB$$4319f311.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.apache.wicket.proxy.LazyInitProxyFactory$AbstractCGLibInterceptor.intercept(LazyInitProxyFactory.java:350) at WICKET_org.wickedsource.budgeteer.service.person.PersonService$$EnhancerByCGLIB$$cec39961.loadPersonDetailData(<generated>) at org.wickedsource.budgeteer.web.pages.person.details.highlights.PersonHighlightsModel.load(PersonHighlightsModel.java:24) at org.wickedsource.budgeteer.web.pages.person.details.highlights.PersonHighlightsModel.load(PersonHighlightsModel.java:10) at org.apache.wicket.model.LoadableDetachableModel.getObject(LoadableDetachableModel.java:135) at org.wicketstuff.lazymodel.LazyModel.getObject(LazyModel.java:229) at org.wickedsource.budgeteer.web.components.datelabel.DateLabel.<init>(DateLabel.java:13) at org.wickedsource.budgeteer.web.pages.person.details.highlights.PersonHighlightsPanel.onInitialize(PersonHighlightsPanel.java:25) at org.apache.wicket.Component.fireInitialize(Component.java:878) at org.apache.wicket.MarkupContainer$3.component(MarkupContainer.java:1087) at org.apache.wicket.MarkupContainer$3.component(MarkupContainer.java:1083) at org.apache.wicket.util.visit.Visits.visitChildren(Visits.java:144) at org.apache.wicket.util.visit.Visits.visitChildren(Visits.java:123) at org.apache.wicket.util.visit.Visits.visitChildren(Visits.java:192) at org.apache.wicket.MarkupContainer.visitChildren(MarkupContainer.java:983) at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1082) at org.apache.wicket.Page.isPageStateless(Page.java:465) at org.apache.wicket.request.handler.render.WebPageRenderer.isPageStateless(WebPageRenderer.java:287) at org.apache.wicket.request.handler.render.WebPageRenderer.shouldRenderPageAndWriteResponse(WebPageRenderer.java:329) at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:193) at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175) at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:895) at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64) at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:265) at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:222) at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:293) at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:261) at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:203) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:284) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not instantiate class [org.wickedsource.budgeteer.persistence.person.PersonDetailDataBean] from tuple at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:513) at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206) at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ... 112 common frames omitted Caused by: org.hibernate.QueryException: could not instantiate class [org.wickedsource.budgeteer.persistence.person.PersonDetailDataBean] from tuple at org.hibernate.transform.AliasToBeanConstructorResultTransformer.transformTuple(AliasToBeanConstructorResultTransformer.java:41) at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75) at org.hibernate.loader.hql.QueryLoader.getResultList(QueryLoader.java:469) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423) at org.hibernate.loader.Loader.list(Loader.java:2418) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268) at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:567) at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:482) ... 126 common frames omitted Caused by: java.lang.reflect.InvocationTargetException: null at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.hibernate.transform.AliasToBeanConstructorResultTransformer.transformTuple(AliasToBeanConstructorResultTransformer.java:37) ... 137 common frames omitted Caused by: java.lang.NullPointerException: null at org.wickedsource.budgeteer.persistence.person.PersonDetailDataBean.<init>(PersonDetailDataBean.java:24) ... 142 common frames omitted ```
3e5af41d27ccd141ff1919172365c174b47d18fe
2aeefb083a387e0f1bf09ff538e0e443d2d9175e
https://github.com/adessose/budgeteer/compare/3e5af41d27ccd141ff1919172365c174b47d18fe...2aeefb083a387e0f1bf09ff538e0e443d2d9175e
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/person/PersonDetailDataBean.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/person/PersonDetailDataBean.java index da586e48..7dc00760 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/person/PersonDetailDataBean.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/person/PersonDetailDataBean.java @@ -21,7 +21,7 @@ public class PersonDetailDataBean { public PersonDetailDataBean(Long id, String name, Long valuedMinutes, Long valuedRate, Date firstBookedDate, Date lastBookedDate, Double hoursBooked, Long budgetBurnedInCents) { this.id = id; this.name = name; - if (valuedRate == 0L) + if (valuedRate == null || valuedRate == 0L) this.averageDailyRateInCents = 0L; else this.averageDailyRateInCents = valuedMinutes / valuedRate;
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/person/PersonDetailDataBean.java']
{'.java': 1}
1
1
0
0
1
1,011,931
207,695
25,370
418
83
27
2
1
17,118
453
3,413
169
0
1
"1970-01-01T00:26:44"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,369
adessose/budgeteer/425/175
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/175
https://github.com/adessoSE/budgeteer/pull/425
https://github.com/adessoSE/budgeteer/pull/425
1
closes
Aggregation period sorting defective
The Aggregation Period column of the Budget Bured table in all Week Reports on Budget is sorted lexically. It must be sorted by date. For projects that do not exceed a year, this is equivalent to sort by week number. However, I recommend to fix the general case, i.e., week 28 of 2020 should have sorting key "2020-28".
3e5af41d27ccd141ff1919172365c174b47d18fe
c79d9a094227178479af0107e4173212325a2313
https://github.com/adessose/budgeteer/compare/3e5af41d27ccd141ff1919172365c174b47d18fe...c79d9a094227178479af0107e4173212325a2313
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/AggregatedRecord.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/AggregatedRecord.java index c03fe2a5..8c094c30 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/AggregatedRecord.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/AggregatedRecord.java @@ -33,12 +33,12 @@ public class AggregatedRecord { aggregationPeriodStart = c.getTime(); c.add(Calendar.MONTH, 1); c.add(Calendar.DAY_OF_YEAR, -1); - aggregationPeriodTitle = String.format("%d/%02d", planAndWorkRecord.getYear(), planAndWorkRecord.getMonth() + 1); + aggregationPeriodTitle = String.format("Month %d-%02d", planAndWorkRecord.getYear(), planAndWorkRecord.getMonth() + 1); } else { c.set(Calendar.WEEK_OF_YEAR, planAndWorkRecord.getWeek()); aggregationPeriodStart = c.getTime(); c.add(Calendar.DAY_OF_YEAR, 6); - aggregationPeriodTitle = String.format("Week #%d", planAndWorkRecord.getWeek()); + aggregationPeriodTitle = String.format("Week %d-%d", planAndWorkRecord.getYear(), planAndWorkRecord.getWeek()); } aggregationPeriodEnd = c.getTime(); diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/RecordJoiner.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/RecordJoiner.java index fbbb9a13..23bdc48d 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/RecordJoiner.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/RecordJoiner.java @@ -140,7 +140,7 @@ public class RecordJoiner { record.setAggregationPeriodStart(c.getTime()); c.add(Calendar.DAY_OF_YEAR, 6); record.setAggregationPeriodEnd(c.getTime()); - record.setAggregationPeriodTitle(String.format("Week #%d", recordBean.getWeek())); + record.setAggregationPeriodTitle(String.format("Week %d-%d", recordBean.getYear(), recordBean.getWeek())); put(getKey(recordBean), record); } return record; @@ -158,7 +158,7 @@ public class RecordJoiner { c.add(Calendar.MONTH, 1); c.add(Calendar.DAY_OF_YEAR, -1); record.setAggregationPeriodEnd(c.getTime()); - record.setAggregationPeriodTitle(String.format("%d/%02d", recordBean.getYear(), recordBean.getMonth() + 1)); + record.setAggregationPeriodTitle(String.format("Month %d-%02d", recordBean.getYear(), recordBean.getMonth() + 1)); put(getKey(recordBean), record); } return record; diff --git a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/record/RecordJoinerTest.java b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/record/RecordJoinerTest.java index 0254eddb..5a49feee 100644 --- a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/record/RecordJoinerTest.java +++ b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/record/RecordJoinerTest.java @@ -28,21 +28,21 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("03.03.2014"), records.get(0).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("09.03.2014"), records.get(0).getAggregationPeriodEnd()); - Assertions.assertEquals("Week #10", records.get(0).getAggregationPeriodTitle()); + Assertions.assertEquals("Week 2014-10", records.get(0).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(50000), records.get(0).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(0).getBudgetPlanned_net()); Assertions.assertEquals(5d, records.get(0).getHours(), 0.1d); Assertions.assertEquals(format.parse("06.04.2015"), records.get(1).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("12.04.2015"), records.get(1).getAggregationPeriodEnd()); - Assertions.assertEquals("Week #15", records.get(1).getAggregationPeriodTitle()); + Assertions.assertEquals("Week 2015-15", records.get(1).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(50000), records.get(1).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(1).getBudgetPlanned_net()); Assertions.assertEquals(5d, records.get(1).getHours(), 0.1d); Assertions.assertEquals(format.parse("13.04.2015"), records.get(2).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("19.04.2015"), records.get(2).getAggregationPeriodEnd()); - Assertions.assertEquals("Week #16", records.get(2).getAggregationPeriodTitle()); + Assertions.assertEquals("Week 2015-16", records.get(2).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(60000), records.get(2).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(32100), records.get(2).getBudgetPlanned_net()); Assertions.assertEquals(6d, records.get(2).getHours(), 0.1d); @@ -55,7 +55,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("26.03.2018"), recordsWithTax.get(0).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("1.04.2018"), recordsWithTax.get(0).getAggregationPeriodEnd()); - Assertions.assertEquals("Week #13", recordsWithTax.get(0).getAggregationPeriodTitle()); + Assertions.assertEquals("Week 2018-13", recordsWithTax.get(0).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(16250), recordsWithTax.get(0).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(18750), recordsWithTax.get(0).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(17625), recordsWithTax.get(0).getBudgetBurned_gross()); @@ -64,7 +64,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("02.04.2018"), recordsWithTax.get(1).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("08.04.2018"), recordsWithTax.get(1).getAggregationPeriodEnd()); - Assertions.assertEquals("Week #14", recordsWithTax.get(1).getAggregationPeriodTitle()); + Assertions.assertEquals("Week 2018-14", recordsWithTax.get(1).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(3750), recordsWithTax.get(1).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(5000), recordsWithTax.get(1).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(4125), recordsWithTax.get(1).getBudgetBurned_gross()); @@ -79,21 +79,21 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.01.2014"), records.get(0).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.01.2014"), records.get(0).getAggregationPeriodEnd()); - Assertions.assertEquals("2014/01", records.get(0).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2014-01", records.get(0).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(50000), records.get(0).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(0).getBudgetPlanned_net()); Assertions.assertEquals(5d, records.get(0).getHours(), 0.1d); Assertions.assertEquals(format.parse("01.06.2015"), records.get(1).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("30.06.2015"), records.get(1).getAggregationPeriodEnd()); - Assertions.assertEquals("2015/06", records.get(1).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2015-06", records.get(1).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(50000), records.get(1).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(1).getBudgetPlanned_net()); Assertions.assertEquals(5d, records.get(1).getHours(), 0.1d); Assertions.assertEquals(format.parse("01.07.2015"), records.get(2).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.07.2015"), records.get(2).getAggregationPeriodEnd()); - Assertions.assertEquals("2015/07", records.get(2).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2015-07", records.get(2).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(60000), records.get(2).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(32100), records.get(2).getBudgetPlanned_net()); Assertions.assertEquals(6d, records.get(2).getHours(), 0.1d); @@ -107,7 +107,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.01.2014"), records.get(0).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.01.2014"), records.get(0).getAggregationPeriodEnd()); - Assertions.assertEquals("2014/01", records.get(0).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2014-01", records.get(0).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(100000), records.get(0).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(0).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(107500), records.get(0).getBudgetBurned_gross()); @@ -116,7 +116,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.06.2015"), records.get(1).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("30.06.2015"), records.get(1).getAggregationPeriodEnd()); - Assertions.assertEquals("2015/06", records.get(1).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2015-06", records.get(1).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(50000), records.get(1).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(12300), records.get(1).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(55000), records.get(1).getBudgetBurned_gross()); @@ -125,7 +125,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.07.2015"), records.get(2).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.07.2015"), records.get(2).getAggregationPeriodEnd()); - Assertions.assertEquals("2015/07", records.get(2).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2015-07", records.get(2).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(60000), records.get(2).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(20000), records.get(2).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(66000), records.get(2).getBudgetBurned_gross()); @@ -134,7 +134,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.01.2016"), records.get(3).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.01.2016"), records.get(3).getAggregationPeriodEnd()); - Assertions.assertEquals("2016/01", records.get(3).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2016-01", records.get(3).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(143750), records.get(3).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(156250), records.get(3).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(152219), records.get(3).getBudgetBurned_gross()); @@ -143,7 +143,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.06.2016"), records.get(4).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("30.06.2016"), records.get(4).getAggregationPeriodEnd()); - Assertions.assertEquals("2016/06", records.get(4).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2016-06", records.get(4).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(201250), records.get(4).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(208125), records.get(4).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(221375), records.get(4).getBudgetBurned_gross()); @@ -152,7 +152,7 @@ class RecordJoinerTest extends ServiceTestTemplate { Assertions.assertEquals(format.parse("01.07.2016"), records.get(5).getAggregationPeriodStart()); Assertions.assertEquals(format.parse("31.07.2016"), records.get(5).getAggregationPeriodEnd()); - Assertions.assertEquals("2016/07", records.get(5).getAggregationPeriodTitle()); + Assertions.assertEquals("Month 2016-07", records.get(5).getAggregationPeriodTitle()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(200000), records.get(5).getBudgetBurned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(208125), records.get(5).getBudgetPlanned_net()); Assertions.assertEquals(MoneyUtil.createMoneyFromCents(220000), records.get(5).getBudgetBurned_gross());
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/RecordJoiner.java', 'budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/record/RecordJoinerTest.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/record/AggregatedRecord.java']
{'.java': 3}
3
3
0
0
3
1,011,931
207,695
25,370
418
959
212
8
2
322
58
77
3
0
0
"1970-01-01T00:26:39"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,370
adessose/budgeteer/412/395
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/395
https://github.com/adessoSE/budgeteer/pull/412
https://github.com/adessoSE/budgeteer/pull/412
1
closes
Remove additional information not possible
A contract may have one or more fields of “additional information” which may be used, e.g., for project specific contract ids. Once I have added and saved some information to a specific contract and later decide to remove this piece of information from the field, the removal is not saved. Neither is a workaround, e.g., by replacing the information by whitespace only, supported. The information update is just ignored. This should be fixed. Any edit result, including the empty field content, should be accepted and saved.
ea5a68b94f4a5c1b85009ee7eca47f4a743e6afb
192538182a679b870e107dc53d73e1394a7605d1
https://github.com/adessose/budgeteer/compare/ea5a68b94f4a5c1b85009ee7eca47f4a743e6afb...192538182a679b870e107dc53d73e1394a7605d1
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/contract/ContractFieldEntity.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/contract/ContractFieldEntity.java index 3ea03cf5..e09882f0 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/contract/ContractFieldEntity.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/contract/ContractFieldEntity.java @@ -1,6 +1,8 @@ package org.wickedsource.budgeteer.persistence.contract; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; import org.wickedsource.budgeteer.persistence.project.ProjectContractField; import javax.persistence.*; @@ -8,6 +10,7 @@ import java.io.Serializable; @Data @Entity +@NoArgsConstructor @Table(name="CONTRACT_FIELD") public class ContractFieldEntity implements Serializable{ @@ -27,4 +30,9 @@ public class ContractFieldEntity implements Serializable{ @JoinColumn(name = "CONTRACT_ID") private ContractEntity contract; + public ContractFieldEntity(ProjectContractField field, String value) { + this.field = field; + this.value = value; + } + } diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/ContractService.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/ContractService.java index 50c047e7..5aa1511e 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/ContractService.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/ContractService.java @@ -1,5 +1,6 @@ package org.wickedsource.budgeteer.service.contract; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @@ -17,6 +18,8 @@ import org.wickedsource.budgeteer.web.pages.contract.overview.table.ContractOver import javax.transaction.Transactional; import java.math.BigDecimal; import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; @Service @Transactional @@ -38,7 +41,7 @@ public class ContractService { private ContractDataMapper mapper; @PreAuthorize("canReadProject(#projectId)") - public ContractOverviewTableModel getContractOverviewByProject(long projectId){ + public ContractOverviewTableModel getContractOverviewByProject(long projectId) { ContractOverviewTableModel result = new ContractOverviewTableModel(); result.setContracts(mapper.map(contractRepository.findByProjectId(projectId))); return result; @@ -57,11 +60,11 @@ public class ContractService { } @PreAuthorize("canReadProject(#projectId)") - public ContractBaseData getEmptyContractModel(long projectId){ + public ContractBaseData getEmptyContractModel(long projectId) { ProjectEntity project = projectRepository.findOne(projectId); ContractBaseData model = new ContractBaseData(projectId); Set<ProjectContractField> fields = project.getContractFields(); - for(ProjectContractField field : fields){ + for (ProjectContractField field : fields) { model.getContractAttributes().add(new DynamicAttributeField(field.getFieldName(), "")); } return model; @@ -73,7 +76,7 @@ public class ContractService { contractEntity.setId(0); contractEntity.setProject(project); - if(contractBaseData.getContractId() != 0){ + if (contractBaseData.getContractId() != 0) { contractEntity = contractRepository.findOne(contractBaseData.getContractId()); } //Update basic information @@ -85,37 +88,25 @@ public class ContractService { contractEntity.setLink(contractBaseData.getFileModel().getLink()); contractEntity.setFileName(contractBaseData.getFileModel().getFileName()); contractEntity.setFile(contractBaseData.getFileModel().getFile()); - if(contractBaseData.getTaxRate() < 0) { + if (contractBaseData.getTaxRate() < 0) { throw new IllegalArgumentException("Taxrate must be positive."); } else { contractEntity.setTaxRate(new BigDecimal(contractBaseData.getTaxRate())); } - //update additional information of the current contract - for(DynamicAttributeField fields : contractBaseData.getContractAttributes()){ - if(fields.getValue() != null && !fields.getValue().isEmpty()) { - boolean attributeFound = false; - //see, if the attribute already exists -> Update the value - for (ContractFieldEntity contractFieldEntity : contractEntity.getContractFields()) { - if (contractFieldEntity.getField().getFieldName().equals(fields.getName().trim())) { - contractFieldEntity.setValue(fields.getValue()); - attributeFound = true; - break; - } - } - // Create a new Attribute - if (!attributeFound) { - // see if the Project already contains a field with this name. If not, create a new one - ProjectContractField projectContractField = projectRepository.findContractFieldByName(contractBaseData.getProjectId(), fields.getName().trim()); - if (projectContractField == null) { - projectContractField = new ProjectContractField(0, fields.getName().trim(), project); - } - ContractFieldEntity field = new ContractFieldEntity(); - field.setId(0); - field.setField(projectContractField); - field.setValue(fields.getValue() == null ? "" : fields.getValue().trim()); - contractEntity.getContractFields().add(field); - } + // Use LinkedHashMap as backing map implementation to ensure insertion order + Map<String, ContractFieldEntity> contractFields = contractEntity.getContractFields().stream() + .collect(Collectors.toMap(field -> field.getField().getFieldName(), Function.identity(), (a, b) -> a, + LinkedHashMap::new)); + + for (DynamicAttributeField dynamicAttribute : contractBaseData.getContractAttributes()) { + ContractFieldEntity fieldEntity = contractFields.get(dynamicAttribute.getName().trim()); + if (fieldEntity != null) { + fieldEntity.setValue(StringUtils.trimToEmpty(dynamicAttribute.getValue())); + } else { + ContractFieldEntity newFieldEntity = createNewContractField(contractBaseData, dynamicAttribute, project); + contractEntity.getContractFields().add(newFieldEntity); + contractFields.put(newFieldEntity.getField().getFieldName(), newFieldEntity); } } contractRepository.save(contractEntity); @@ -145,7 +136,7 @@ public class ContractService { cal.setTime(contract.getStartDate()); Calendar currentDate = Calendar.getInstance(); currentDate.setTime(new Date()); - while(cal.before(currentDate)) { + while (cal.before(currentDate)) { months.add(cal.getTime()); cal.add(Calendar.MONTH, 1); } @@ -156,8 +147,8 @@ public class ContractService { public List<Date> getMonthListForProjectId(long projectId) { List<ContractEntity> contracts = contractRepository.findByProjectId(projectId); Date startDate = new Date(); - for(ContractEntity contract : contracts) { - if(contract.getStartDate().before(startDate)) { + for (ContractEntity contract : contracts) { + if (contract.getStartDate().before(startDate)) { startDate = contract.getStartDate(); } } @@ -167,7 +158,7 @@ public class ContractService { cal.setTime(startDate); Calendar currentDate = Calendar.getInstance(); currentDate.setTime(new Date()); - while(cal.before(currentDate)) { + while (cal.before(currentDate)) { months.add(cal.getTime()); cal.add(Calendar.MONTH, 1); } @@ -179,4 +170,13 @@ public class ContractService { List<ContractEntity> contracts = contractRepository.findByProjectId(projectId); return (null != contracts && !contracts.isEmpty()); } + + private ContractFieldEntity createNewContractField(ContractBaseData contractBaseData, + DynamicAttributeField dynamicAttribute, + ProjectEntity project) { + ProjectContractField projectContractField = Optional + .ofNullable(projectRepository.findContractFieldByName(contractBaseData.getProjectId(), dynamicAttribute.getName().trim())) + .orElse(new ProjectContractField(0, dynamicAttribute.getName().trim(), project)); + return new ContractFieldEntity(projectContractField, StringUtils.trimToEmpty(dynamicAttribute.getValue())); + } } diff --git a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/contract/ContractServiceTest.java b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/contract/ContractServiceTest.java index c0bfc214..35a0ab8e 100644 --- a/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/contract/ContractServiceTest.java +++ b/budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/contract/ContractServiceTest.java @@ -5,6 +5,7 @@ import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import org.apache.commons.lang3.time.DateUtils; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -51,7 +52,7 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { @Test @DatabaseSetup("contractTest.xml") @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) - void testSaveNewContract(){ + void testSaveNewContract() { ContractBaseData testObject = new ContractBaseData(); testObject.setBudget(MoneyUtil.createMoney(12)); testObject.setContractId(0); @@ -78,7 +79,7 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { @Test @DatabaseSetup("contractTest.xml") @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) - void testSaveNewContract2(){ + void testSaveNewContract2() { ContractBaseData testObject = new ContractBaseData(); testObject.setContractId(0); testObject.setProjectId(2); @@ -103,7 +104,7 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { @Test @DatabaseSetup("contractTest.xml") @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) - void testUpdateContract(){ + void testUpdateContract() { ContractBaseData testObject = service.getContractById(4); testObject.setBudget(MoneyUtil.createMoney(12)); @@ -128,8 +129,8 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { assertEquals(6, savedContract.getContractAttributes().size()); for (int i = 0; i < 6; i++) { boolean found = false; - for(DynamicAttributeField field : savedContract.getContractAttributes()){ - if(field.getName().equals(field.getValue()) && field.getValue().equals("test" + i)){ + for (DynamicAttributeField field : savedContract.getContractAttributes()) { + if (field.getName().equals(field.getValue()) && field.getValue().equals("test" + i)) { found = true; break; } @@ -146,7 +147,7 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { @Test @DatabaseSetup("contractTest.xml") @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) - void testUpdateContract1(){ + void testUpdateContract1() { ContractBaseData testObject = service.getContractById(5); testObject.setBudget(MoneyUtil.createMoney(12)); @@ -172,8 +173,8 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { assertEquals(7, savedContract.getContractAttributes().size()); for (int i = 0; i < 7; i++) { boolean found = false; - for(DynamicAttributeField field : savedContract.getContractAttributes()){ - if(field.getName().equals(field.getValue()) && field.getValue().equals("test" + i)){ + for (DynamicAttributeField field : savedContract.getContractAttributes()) { + if (field.getName().equals(field.getValue()) && field.getValue().equals("test" + i)) { found = true; break; } @@ -235,7 +236,7 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { private List<DynamicAttributeField> getListOfContractFields() { List<DynamicAttributeField> result = new LinkedList<DynamicAttributeField>(); DynamicAttributeField data = new DynamicAttributeField(); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { data = new DynamicAttributeField(); data.setName("test" + i); data.setValue("test" + i); @@ -257,7 +258,37 @@ class ContractServiceTest extends ServiceIntegrationTestTemplate { assertNull(service.getContractById(3)); } + @Test + @DatabaseSetup("contractTest.xml") + @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) + void shouldUpdateAttributeWithEmptyValue() { + ContractBaseData testObject = service.getContractById(4); + testObject.setContractAttributes(getListOfContractFields()); + DynamicAttributeField field = testObject.getContractAttributes().get(0); + field.setValue(null); + + long newContractId = service.save(testObject); + + ContractBaseData savedContract = service.getContractById(newContractId); + + Assertions.assertThat(savedContract.getContractAttributes()) + .contains(new DynamicAttributeField(field.getName(), "")); + } + + @Test + @DatabaseSetup("contractTest.xml") + @DatabaseTearDown(value = "contractTest.xml", type = DatabaseOperation.DELETE_ALL) + void shouldSaveAttributeWithEmptyValue() { + ContractBaseData testObject = service.getContractById(4); + testObject.setContractAttributes(getListOfContractFields()); + DynamicAttributeField field = new DynamicAttributeField("new-key", null); + testObject.getContractAttributes().add(field); + long newContractId = service.save(testObject); + ContractBaseData savedContract = service.getContractById(newContractId); + Assertions.assertThat(savedContract.getContractAttributes()) + .contains(new DynamicAttributeField(field.getName(), "")); + } }
['budgeteer-web-interface/src/test/java/org/wickedsource/budgeteer/service/contract/ContractServiceTest.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/contract/ContractFieldEntity.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/contract/ContractService.java']
{'.java': 3}
3
3
0
0
3
1,009,645
207,242
25,325
415
4,726
795
76
2
530
86
104
5
0
0
"1970-01-01T00:26:36"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,371
adessose/budgeteer/354/353
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/353
https://github.com/adessoSE/budgeteer/pull/354
https://github.com/adessoSE/budgeteer/pull/354
1
fixes
Budget without Contract - details NPE
In case I have a budget without an associated contract and actual work records exist on this budget, Budgeteer warns, "The budget is not assigned to a contract. Please assign a contract." Clicking on this warning sometimes leads to Edit Budget Details, sometimes, however, it leads to an internal server error. See [budgeteer.log.txt](https://github.com/adessoAG/budgeteer/files/2827511/budgeteer.log.txt) attached for the server side stacktrace.
8999c921b73647fefa64dab930834b3fb0a93c8d
58456362de38ded350195c1ac3222f9e64b83f4b
https://github.com/adessose/budgeteer/compare/8999c921b73647fefa64dab930834b3fb0a93c8d...58456362de38ded350195c1ac3222f9e64b83f4b
diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/BudgeteerSession.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/BudgeteerSession.java index 5c4116a9..b0180985 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/BudgeteerSession.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/BudgeteerSession.java @@ -13,6 +13,7 @@ import org.wickedsource.budgeteer.web.pages.templates.TemplateFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import java.util.ArrayList; import java.util.HashMap; public class BudgeteerSession extends WebSession { @@ -87,16 +88,24 @@ public class BudgeteerSession extends WebSession { } public BudgetTagFilter getBudgetFilter() { - return budgetFilter.get(getProjectId()); + BudgetTagFilter filter = budgetFilter.get(projectId); + + if (filter == null) { + filter = new BudgetTagFilter(new ArrayList<>(), projectId); + setBudgetFilter(filter); + } + + return filter; } public void setBudgetFilter(BudgetTagFilter budgetTagFilter) { this.budgetFilter.put(projectId, budgetTagFilter); } + public TemplateFilter getTemplateFilter() { - if(templateFilter.get(getProjectId()) == null){ + if (templateFilter.get(getProjectId()) == null) { return new TemplateFilter(getProjectId()); - }else { + } else { return templateFilter.get(getProjectId()); } } @@ -140,8 +149,7 @@ public class BudgeteerSession extends WebSession { * Sets the given {@link Authentication} in the current {@link SecurityContext} * and saves the context in the session. * - * @param authToken - * The {@link Authentication} to set in the {@link SecurityContext}. + * @param authToken The {@link Authentication} to set in the {@link SecurityContext}. */ private void setAuthInSecurityContext(Authentication authToken) { diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/edit/form/EditBudgetForm.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/edit/form/EditBudgetForm.java index 98b08ca9..f974892b 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/edit/form/EditBudgetForm.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/edit/form/EditBudgetForm.java @@ -92,7 +92,7 @@ public class EditBudgetForm extends Form<EditBudgetData> { public Object getDisplayValue(ContractBaseData object) { return object == null ? getString("no.contract") : object.getContractName(); } - }){ + }) { @Override protected String getNullValidDisplayValue() { return EditBudgetForm.this.getString("no.contract"); diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/overview/BudgetsOverviewPage.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/overview/BudgetsOverviewPage.java index 5692152e..1af12168 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/overview/BudgetsOverviewPage.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/overview/BudgetsOverviewPage.java @@ -9,7 +9,6 @@ import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.wickedsource.budgeteer.service.budget.BudgetService; -import org.wickedsource.budgeteer.service.budget.BudgetTagFilter; import org.wickedsource.budgeteer.web.BudgeteerSession; import org.wickedsource.budgeteer.web.Mount; import org.wickedsource.budgeteer.web.components.links.NetGrossLink; @@ -27,8 +26,6 @@ import org.wickedsource.budgeteer.web.pages.budgets.overview.table.FilteredBudge import org.wickedsource.budgeteer.web.pages.budgets.weekreport.multi.MultiBudgetWeekReportPage; import org.wickedsource.budgeteer.web.pages.dashboard.DashboardPage; -import java.util.ArrayList; - import static org.wicketstuff.lazymodel.LazyModel.from; import static org.wicketstuff.lazymodel.LazyModel.model; @@ -40,15 +37,11 @@ public class BudgetsOverviewPage extends BasePage { public BudgetsOverviewPage() { BudgetTagsModel tagsModel = new BudgetTagsModel(BudgeteerSession.get().getProjectId()); - if (BudgeteerSession.get().getBudgetFilter() == null) { - BudgetTagFilter filter = new BudgetTagFilter(new ArrayList<>(), BudgeteerSession.get().getProjectId()); - BudgeteerSession.get().setBudgetFilter(filter); - } add(new BudgetRemainingFilterPanel("remainingFilter", new RemainingBudgetFilterModel(BudgeteerSession.get().getProjectId()))); add(new BudgetTagFilterPanel("tagFilter", tagsModel)); FilteredBudgetModel filteredBudgetModel = new FilteredBudgetModel(BudgeteerSession.get().getProjectId(), model(from(BudgeteerSession.get().getBudgetFilter()))); filteredBudgetModel.setRemainingFilterModel(model(from(BudgeteerSession.get().getRemainingBudgetFilterValue()))); - add(new BudgetOverviewTable("budgetTable", filteredBudgetModel ,getBreadcrumbsModel())); + add(new BudgetOverviewTable("budgetTable", filteredBudgetModel, getBreadcrumbsModel())); add(new BookmarkablePageLink<MultiBudgetWeekReportPage>("weekReportLink", MultiBudgetWeekReportPage.class)); add(new BookmarkablePageLink<MultiBudgetMonthReportPage>("monthReportLink", MultiBudgetMonthReportPage.class)); add(createNewBudgetLink("createBudgetLink")); @@ -59,11 +52,11 @@ public class BudgetsOverviewPage extends BasePage { private Component createReportLink(String string) { Link link = new Link(string) { - @Override - public void onClick() { - setResponsePage(new BudgetReportPage(BudgetsOverviewPage.class, new PageParameters())); - } - }; + @Override + public void onClick() { + setResponsePage(new BudgetReportPage(BudgetsOverviewPage.class, new PageParameters())); + } + }; if (!budgetService.projectHasBudgets(BudgeteerSession.get().getProjectId())) { link.setEnabled(false); @@ -71,7 +64,7 @@ public class BudgetsOverviewPage extends BasePage { link.add(new AttributeModifier("title", BudgetsOverviewPage.this.getString("links.budget.label.no.budget"))); } return link; - } + } private Link createNewBudgetLink(String id) { return new Link(id) {
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/overview/BudgetsOverviewPage.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/BudgeteerSession.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/edit/form/EditBudgetForm.java']
{'.java': 3}
3
3
0
0
3
1,067,624
219,277
26,637
429
1,613
325
41
3
454
59
99
6
1
0
"1970-01-01T00:25:49"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,830
ballerina-platform/openapi-tools/1501/1500
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1500
https://github.com/ballerina-platform/openapi-tools/pull/1501
https://github.com/ballerina-platform/openapi-tools/pull/1501
1
resolves
vscode `try it` command not working for record type payload parameters
**Description:** $subject **Steps to reproduce:** Please try to run `try it` code lense for below bal service. `try it` windows is not loading and does not display any error message. ```bal import ballerina/http; type Album readonly & record {| string title; string artist; |}; table<Album> key(title) albums = table []; service / on new http:Listener(9090) { // The `album` parameter in the payload annotation represents the entity body of the inbound request. resource function post albums(Album album) returns Album { albums.add(album); return album; } } ``` **Affected Versions:** 2201.7.2 RC pack **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
6213ea77770272fff793b97879817e9e6d31ce15
17a8dec49dd6fa3d55be05a2c1a144f70089de9f
https://github.com/ballerina-platform/openapi-tools/compare/6213ea77770272fff793b97879817e9e6d31ce15...17a8dec49dd6fa3d55be05a2c1a144f70089de9f
diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index f374a819..58e9ffb0 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -127,22 +127,22 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { OpenAPIConverterResponse response = new OpenAPIConverterResponse(); Path filePath = Path.of(request.getDocumentFilePath()); Optional<SemanticModel> semanticModel = workspaceManager.semanticModel(filePath); - Optional<Project> module = workspaceManager.project(filePath); + Optional<Project> project = workspaceManager.project(filePath); if (semanticModel.isEmpty()) { response.setError("Error while generating semantic model."); return response; } - if (module.isEmpty()) { + if (project.isEmpty()) { response.setError("Error while getting the project."); return response; } - module = Optional.of(module.get().duplicate()); - DiagnosticResult diagnosticsFromCodeGenAndModify = module.get() + project = Optional.of(project.get().duplicate()); + DiagnosticResult diagnosticsFromCodeGenAndModify = project.get() .currentPackage() .runCodeGenAndModifyPlugins(); boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - Collection<Diagnostic> compilationDiagnostics = module.get().currentPackage() + Collection<Diagnostic> compilationDiagnostics = project.get().currentPackage() .getCompilation().diagnosticResult().diagnostics(); boolean hasCompilationErrors = compilationDiagnostics.stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); @@ -151,17 +151,17 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = module.get().currentPackage().getDefaultModule(); - + Module defaultModule = project.get().currentPackage().getDefaultModule(); + SemanticModel updatedSemanticModel = + project.get().currentPackage().getCompilation().getSemanticModel(defaultModule.moduleId()); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) { Document document = defaultModule.document(currentDocumentID); Optional<Path> path = defaultModule.project().documentPath(currentDocumentID); Path inputPath = path.orElse(null); SyntaxTree syntaxTree = document.syntaxTree(); - List<OASResult> oasResults = ServiceToOpenAPIConverterUtils.generateOAS3Definition(module.get(), - syntaxTree, semanticModel.get(), null, false, inputPath); - + List<OASResult> oasResults = ServiceToOpenAPIConverterUtils.generateOAS3Definition(project.get(), + syntaxTree, updatedSemanticModel, null, false, inputPath); generateServiceJson(response, document.syntaxTree().filePath(), oasResults, specs); } response.setContent(specs);
['openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java']
{'.java': 1}
1
1
0
0
1
1,270,361
243,797
26,563
139
1,425
241
20
1
1,397
192
299
40
0
1
"1970-01-01T00:28:12"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,831
ballerina-platform/openapi-tools/1445/1401
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1401
https://github.com/ballerina-platform/openapi-tools/pull/1445
https://github.com/ballerina-platform/openapi-tools/pull/1445
1
resolves
OpenAPI LS Extension returns wrong response without running the code modifier
**Description:** We have introduced a default http payload parameter support in 2201.5.x. It automatically adds the payload annotation to a compatible signature parameter type using the code modifier. This change has been adhered to open API-tools by running the code modifiers before generating the document. But seems like we have missed adding this to the LS extension which is used for `Try it` feature in the VS code. **Steps to reproduce:** Use the [following BBE ](https://ballerina.io/learn/by-example/http-service-data-binding/)in the VS code and click on the `Try it` option to see the openAPI. The parameter is shown as a query parameter. This `Try it` feature uses the `openAPILSExtension/generateOpenAPI` API to generate the openAPI. **Affected Versions:** 2201.5.x, 2201.6.0
3200391bf6031e0b76ea9d27bae47d68eecac00a
11340a9623cca4959e74c67f59eb4bd61aa50db7
https://github.com/ballerina-platform/openapi-tools/compare/3200391bf6031e0b76ea9d27bae47d68eecac00a...11340a9623cca4959e74c67f59eb4bd61aa50db7
diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index 7015c08b..c098b301 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -30,10 +30,10 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; import io.ballerina.projects.Document; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; -import io.ballerina.projects.Package; import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -136,16 +136,21 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { response.setError("Error while getting the project."); return response; } - Package aPackage = module.get().currentPackage(); - Collection<Diagnostic> diagnostics = aPackage.getCompilation().diagnosticResult().diagnostics(); - boolean hasErrors = diagnostics.stream() + DiagnosticResult diagnosticsFromCodeGenAndModify = module.get() + .currentPackage() + .runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + Collection<Diagnostic> compilationDiagnostics = module.get().currentPackage() + .getCompilation().diagnosticResult().diagnostics(); + boolean hasCompilationErrors = compilationDiagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = aPackage.getDefaultModule(); + Module defaultModule = module.get().currentPackage().getDefaultModule(); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) {
['openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java']
{'.java': 1}
1
1
0
0
1
1,256,244
241,139
26,310
139
1,185
201
17
1
811
114
187
15
1
0
"1970-01-01T00:28:08"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,372
adessose/budgeteer/326/267
adessose
budgeteer
https://github.com/adessoSE/budgeteer/issues/267
https://github.com/adessoSE/budgeteer/pull/326
https://github.com/adessoSE/budgeteer/pull/326
1
fixes
Import Working Hours: Budget Planned values of old budgets are deleted
I had a project with two budgets filled with data of the last few months. For testing purpose, I decided to add a third budget which should be assigned to a different contract. I downloaded the example import files, manipulated them to have data for the last months of a new budget and uploaded them again. Now the "Budget Planned"-values (seen in the Week and Month Overview) of the old two budgets are deleted in the time periods covered by the new budget.
78de3f820c35a41c9ae9d80baea3a4e4cb57bb1e
06396bc288ae2c344e36da791230fcc6b302f33a
https://github.com/adessose/budgeteer/compare/78de3f820c35a41c9ae9d80baea3a4e4cb57bb1e...06396bc288ae2c344e36da791230fcc6b302f33a
diff --git a/budgeteer-resourceplan-importer/src/main/java/org/wickedsource/budgeteer/importer/resourceplan/ResourcePlanImporter.java b/budgeteer-resourceplan-importer/src/main/java/org/wickedsource/budgeteer/importer/resourceplan/ResourcePlanImporter.java index 1144129f..16ecc86e 100644 --- a/budgeteer-resourceplan-importer/src/main/java/org/wickedsource/budgeteer/importer/resourceplan/ResourcePlanImporter.java +++ b/budgeteer-resourceplan-importer/src/main/java/org/wickedsource/budgeteer/importer/resourceplan/ResourcePlanImporter.java @@ -51,7 +51,7 @@ public class ResourcePlanImporter implements PlanRecordsImporter { List<DateColumn> dateColumns = getDateColumns(sheet); int i = FIRST_ENTRY_ROW; Row row = sheet.getRow(i); - while (row != null && row.getCell(0).getStringCellValue() != null) { + while (row != null && row.getCell(0) != null && row.getCell(0).getStringCellValue() != null) { List<ImportedPlanRecord> records = parseRow(row, dateColumns, currencyUnit, skippedRecords); resultList.addAll(records); row = sheet.getRow(++i); @@ -150,7 +150,7 @@ public class ResourcePlanImporter implements PlanRecordsImporter { ExampleFile file = new ExampleFile(); file.setFileName("resource_plan.xlsx"); file.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - + try { Date date = new Date(); Calendar calendar = Calendar.getInstance(); diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/record/PlanRecordRepository.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/record/PlanRecordRepository.java index 74feef8c..6ebfb4bd 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/record/PlanRecordRepository.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/record/PlanRecordRepository.java @@ -244,8 +244,8 @@ public interface PlanRecordRepository extends CrudRepository<PlanRecordEntity, L List<PlanRecordEntity> findByPersonBudgetDate(@Param("personId") long personId, @Param("budgetId") long budgetId, @Param("date") Date date); @Modifying - @Query("delete from PlanRecordEntity r where r.budget.id in ( select b.id from BudgetEntity b where b.project.id = :projectId) AND r.date >= :date") - void deleteByProjectIdAndDate(@Param("projectId") long projectId, @Param("date") Date date); + @Query("delete from PlanRecordEntity r where r.budget.id in ( select b.id from BudgetEntity b where b.project.id = :projectId AND b.importKey = :importKey) AND r.date >= :date") + void deleteByBudgetKeyAndDate(@Param("projectId") long projectId,@Param("importKey") String importKey, @Param("date") Date date); @Override @Query("select pr from PlanRecordEntity pr where pr.budget.project.id = :projectId") diff --git a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/imports/PlanRecordDatabaseImporter.java b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/imports/PlanRecordDatabaseImporter.java index 5d382e57..d502007c 100644 --- a/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/imports/PlanRecordDatabaseImporter.java +++ b/budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/imports/PlanRecordDatabaseImporter.java @@ -17,8 +17,10 @@ import org.wickedsource.budgeteer.persistence.record.PlanRecordEntity; import org.wickedsource.budgeteer.persistence.record.PlanRecordRepository; import javax.annotation.PostConstruct; +import javax.print.DocFlavor; import java.text.SimpleDateFormat; import java.util.*; +import java.util.stream.Collectors; @Component @Scope("prototype") @@ -53,22 +55,29 @@ public class PlanRecordDatabaseImporter extends RecordDatabaseImporter { Map<RecordKey, List<ImportedPlanRecord>> groupedRecords = groupRecords(records); //Because of Issue #70 all PlanRecords that are after the earliest of the imported ones, should be deleted - Date earliestDate = findEarliestDate(records); - planRecordRepository.deleteByProjectIdAndDate(getProjectId(), earliestDate); + + // Delete only records of the imported budgets + List<String> budgetNames = getBudgetNames(records); + for (String name : budgetNames) { + // Select which record to delete for each budget individually + List<ImportedPlanRecord> budgetRecords = getRecordsOfBudget(name, records); + Date earliestDate = findEarliestDate(budgetRecords); + planRecordRepository.deleteByBudgetKeyAndDate(getProjectId(), name, earliestDate); + } for (RecordKey key : groupedRecords.keySet()) { List<ImportedPlanRecord> importedPlanRecords = groupedRecords.get(key); List<List<String>> skippedPlanRecords = importRecordGroup(key, importedPlanRecords, filename); - if(skippedPlanRecords != null && !skippedPlanRecords.isEmpty()){ + if (skippedPlanRecords != null && !skippedPlanRecords.isEmpty()) { skippedRecords.addAll(skippedPlanRecords); } } //If all records haven been skipped the startDate of the import is new Date(Long.MAX_VALUE) and the EndDate is null. // This causes problems in our application, so they have to be set to properly values... - if(getImportRecord().getStartDate() == null || getImportRecord().getStartDate().equals(new Date(Long.MAX_VALUE))){ + if (getImportRecord().getStartDate() == null || getImportRecord().getStartDate().equals(new Date(Long.MAX_VALUE))) { getImportRecord().setStartDate(new Date()); } - if(getImportRecord().getEndDate() == null){ + if (getImportRecord().getEndDate() == null) { getImportRecord().setEndDate(new Date()); } getImportRecord().setNumberOfImportedFiles(getImportRecord().getNumberOfImportedFiles() + 1); @@ -85,6 +94,36 @@ public class PlanRecordDatabaseImporter extends RecordDatabaseImporter { return da; } + /** + * Get the names of all budgets in the imported records + * + * @param records imported records + * @return budget names of the imported records + */ + private List<String> getBudgetNames(List<ImportedPlanRecord> records) { + List<String> names = new ArrayList<>(); + + for (ImportedPlanRecord record : records) { + String name = record.getBudgetName(); + if (!names.contains(name)) { + names.add(name); + } + } + + return names; + } + + /** + * Get all records of one budget + * + * @param budgetname name of the budget + * @param records import records + * @return records of the budget + */ + private List<ImportedPlanRecord> getRecordsOfBudget(String budgetname, List<ImportedPlanRecord> records) { + return records.stream().filter(r -> r.getBudgetName().equals(budgetname)).collect(Collectors.toList()); + } + private Map<RecordKey, List<ImportedPlanRecord>> groupRecords(List<ImportedPlanRecord> records) { Map<RecordKey, List<ImportedPlanRecord>> result = new HashMap<>(); for (ImportedPlanRecord record : records) { @@ -121,10 +160,10 @@ public class PlanRecordDatabaseImporter extends RecordDatabaseImporter { recordEntity.setImportRecord(getImportRecord()); recordEntity.setDailyRate(record.getDailyRate()); - if((project.getProjectEnd() != null && record.getDate().after(project.getProjectEnd())) || - (project.getProjectStart() != null && record.getDate().before(project.getProjectStart()))){ + if ((project.getProjectEnd() != null && record.getDate().after(project.getProjectEnd())) || + (project.getProjectStart() != null && record.getDate().before(project.getProjectStart()))) { skippedRecords.add(getRecordAsString(recordEntity, filename)); - }else { + } else { entitiesToImport.add(recordEntity); @@ -136,7 +175,7 @@ public class PlanRecordDatabaseImporter extends RecordDatabaseImporter { } } } - if(entitiesToImport != null && !entitiesToImport.isEmpty()) { + if (entitiesToImport != null && !entitiesToImport.isEmpty()) { planRecordRepository.save(entitiesToImport); // updating start and end date for import record @@ -154,13 +193,13 @@ public class PlanRecordDatabaseImporter extends RecordDatabaseImporter { return getRecordAsString(recordEntity, filename, "Record is out of project-date-range"); } - private List<String> getRecordAsString(PlanRecordEntity recordEntity,String filename, String reason) { + private List<String> getRecordAsString(PlanRecordEntity recordEntity, String filename, String reason) { List<String> result = new LinkedList<>(); result.add(filename); result.add(recordEntity.getDate() != null ? formatter.format(recordEntity.getDate()) : ""); result.add(recordEntity.getPerson().getName()); result.add(recordEntity.getBudget().getName()); - result.add(""+recordEntity.getMinutes()); + result.add("" + recordEntity.getMinutes()); result.add(recordEntity.getDailyRate() != null ? recordEntity.getDailyRate().toString() : ""); result.add(reason); return result;
['budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/persistence/record/PlanRecordRepository.java', 'budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/service/imports/PlanRecordDatabaseImporter.java', 'budgeteer-resourceplan-importer/src/main/java/org/wickedsource/budgeteer/importer/resourceplan/ResourcePlanImporter.java']
{'.java': 3}
3
3
0
0
3
1,064,686
218,642
26,567
429
3,906
828
69
3
462
83
95
4
0
0
"1970-01-01T00:25:43"
32
Java
{'Java': 1745050, 'JavaScript': 1564690, 'HTML': 1517687, 'CSS': 576139, 'Less': 141886, 'PHP': 5016, 'Dockerfile': 312}
MIT License
9,833
ballerina-platform/openapi-tools/1408/1401
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1401
https://github.com/ballerina-platform/openapi-tools/pull/1408
https://github.com/ballerina-platform/openapi-tools/pull/1408
1
resolves
OpenAPI LS Extension returns wrong response without running the code modifier
**Description:** We have introduced a default http payload parameter support in 2201.5.x. It automatically adds the payload annotation to a compatible signature parameter type using the code modifier. This change has been adhered to open API-tools by running the code modifiers before generating the document. But seems like we have missed adding this to the LS extension which is used for `Try it` feature in the VS code. **Steps to reproduce:** Use the [following BBE ](https://ballerina.io/learn/by-example/http-service-data-binding/)in the VS code and click on the `Try it` option to see the openAPI. The parameter is shown as a query parameter. This `Try it` feature uses the `openAPILSExtension/generateOpenAPI` API to generate the openAPI. **Affected Versions:** 2201.5.x, 2201.6.0
a4b39270ba2091d3632a9429bf8bbbb3c18e77e9
b170d6c8b95cce033f42b3b8fec590a4ce054377
https://github.com/ballerina-platform/openapi-tools/compare/a4b39270ba2091d3632a9429bf8bbbb3c18e77e9...b170d6c8b95cce033f42b3b8fec590a4ce054377
diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index 7015c08b..c098b301 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -30,10 +30,10 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; import io.ballerina.projects.Document; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; -import io.ballerina.projects.Package; import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -136,16 +136,21 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { response.setError("Error while getting the project."); return response; } - Package aPackage = module.get().currentPackage(); - Collection<Diagnostic> diagnostics = aPackage.getCompilation().diagnosticResult().diagnostics(); - boolean hasErrors = diagnostics.stream() + DiagnosticResult diagnosticsFromCodeGenAndModify = module.get() + .currentPackage() + .runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + Collection<Diagnostic> compilationDiagnostics = module.get().currentPackage() + .getCompilation().diagnosticResult().diagnostics(); + boolean hasCompilationErrors = compilationDiagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = aPackage.getDefaultModule(); + Module defaultModule = module.get().currentPackage().getDefaultModule(); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) {
['openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java']
{'.java': 1}
1
1
0
0
1
1,255,696
241,002
26,308
139
1,185
201
17
1
811
114
187
15
1
0
"1970-01-01T00:28:07"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,834
ballerina-platform/openapi-tools/1406/1401
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1401
https://github.com/ballerina-platform/openapi-tools/pull/1406
https://github.com/ballerina-platform/openapi-tools/pull/1406
1
resolves
OpenAPI LS Extension returns wrong response without running the code modifier
**Description:** We have introduced a default http payload parameter support in 2201.5.x. It automatically adds the payload annotation to a compatible signature parameter type using the code modifier. This change has been adhered to open API-tools by running the code modifiers before generating the document. But seems like we have missed adding this to the LS extension which is used for `Try it` feature in the VS code. **Steps to reproduce:** Use the [following BBE ](https://ballerina.io/learn/by-example/http-service-data-binding/)in the VS code and click on the `Try it` option to see the openAPI. The parameter is shown as a query parameter. This `Try it` feature uses the `openAPILSExtension/generateOpenAPI` API to generate the openAPI. **Affected Versions:** 2201.5.x, 2201.6.0
cab0d62a96e38618c72eda2d923186b2c7d11de6
27846846f696c1fbe6ed320c8ef9ea62f453535c
https://github.com/ballerina-platform/openapi-tools/compare/cab0d62a96e38618c72eda2d923186b2c7d11de6...27846846f696c1fbe6ed320c8ef9ea62f453535c
diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index e8916fa5..79025149 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -30,10 +30,10 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; import io.ballerina.projects.Document; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; -import io.ballerina.projects.Package; import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -136,16 +136,21 @@ public class OpenAPIConverterService implements ExtendedLanguageServerService { response.setError("Error while getting the project."); return response; } - Package aPackage = module.get().currentPackage(); - Collection<Diagnostic> diagnostics = aPackage.getCompilation().diagnosticResult().diagnostics(); - boolean hasErrors = diagnostics.stream() + DiagnosticResult diagnosticsFromCodeGenAndModify = module.get() + .currentPackage() + .runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + Collection<Diagnostic> compilationDiagnostics = module.get().currentPackage() + .getCompilation().diagnosticResult().diagnostics(); + boolean hasCompilationErrors = compilationDiagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = aPackage.getDefaultModule(); + Module defaultModule = module.get().currentPackage().getDefaultModule(); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) {
['openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java']
{'.java': 1}
1
1
0
0
1
1,236,672
237,083
25,892
136
1,185
201
17
1
811
114
187
15
1
0
"1970-01-01T00:28:07"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,839
ballerina-platform/openapi-tools/1186/1185
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1185
https://github.com/ballerina-platform/openapi-tools/pull/1186
https://github.com/ballerina-platform/openapi-tools/pull/1186
1
resolves
utils.bal file not getting over written in regeneration of clients
**Description:** $subject **Steps to reproduce:** Regenerate a client using the openapi file within the same directory where the client is generated earlier **Affected Versions:** **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
116b448307833cfd7087b272e1b07575f1fcff2e
92b25eda09945f6f44b3a0bb1993d328fbb0f429
https://github.com/ballerina-platform/openapi-tools/compare/116b448307833cfd7087b272e1b07575f1fcff2e...92b25eda09945f6f44b3a0bb1993d328fbb0f429
diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java index 8174e355..55d4463e 100644 --- a/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java @@ -42,7 +42,7 @@ public class GenSrcFile { UTIL_SRC; public boolean isOverwritable() { - if (this == GEN_SRC || this == RES || this == MODEL_SRC) { + if (this == GEN_SRC || this == RES || this == MODEL_SRC || this == UTIL_SRC) { return true; }
['openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java']
{'.java': 1}
1
1
0
0
1
1,187,225
228,273
25,019
135
163
41
2
1
911
125
181
19
0
0
"1970-01-01T00:27:55"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,838
ballerina-platform/openapi-tools/1195/1185
ballerina-platform
openapi-tools
https://github.com/ballerina-platform/openapi-tools/issues/1185
https://github.com/ballerina-platform/openapi-tools/pull/1195
https://github.com/ballerina-platform/openapi-tools/pull/1195
1
resolves
utils.bal file not getting over written in regeneration of clients
**Description:** $subject **Steps to reproduce:** Regenerate a client using the openapi file within the same directory where the client is generated earlier **Affected Versions:** **OS, DB, other environment details and versions:** **Related Issues (optional):** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> **Suggested Labels (optional):** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees (optional):** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
ecd5fd924d9fce635f9d548f241d2279609d0d33
c96dab4da94fea83a78ba00f7420e82529a09bf2
https://github.com/ballerina-platform/openapi-tools/compare/ecd5fd924d9fce635f9d548f241d2279609d0d33...c96dab4da94fea83a78ba00f7420e82529a09bf2
diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java index 8174e355..55d4463e 100644 --- a/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java @@ -42,7 +42,7 @@ public class GenSrcFile { UTIL_SRC; public boolean isOverwritable() { - if (this == GEN_SRC || this == RES || this == MODEL_SRC) { + if (this == GEN_SRC || this == RES || this == MODEL_SRC || this == UTIL_SRC) { return true; }
['openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java']
{'.java': 1}
1
1
0
0
1
1,162,677
223,612
24,541
133
163
41
2
1
911
125
181
19
0
0
"1970-01-01T00:27:56"
32
Java
{'Java': 2065888, 'Ballerina': 865920}
Apache License 2.0
9,679
gchq/sleeper/1080/1073
gchq
sleeper
https://github.com/gchq/sleeper/issues/1073
https://github.com/gchq/sleeper/pull/1080
https://github.com/gchq/sleeper/pull/1080
1
resolves
WaitForStackToDelete doesn't deal with failed deletes
### Description When running `./scripts/test/tearDown.sh`, the `WaitForStackToDelete` class got stuck as the stack entered a state of `DELETE_FAILED`. ### Steps to reproduce The stack failed to delete because there were some files in the system test bucket. It's not clear why that was so it's hard to reproduce. ### Expected behaviour `WaitForStackToDelete` should detect that the stack has entered the state of `DELETE_FAILED`. It's not clear what's best to do after that. It could retry the delete or move on to the next part of the tear down process.
29ba6b34c237306d25d421faa8189d012ed6df31
0d2425aee2917677562ef597b570f8e54c49ce68
https://github.com/gchq/sleeper/compare/29ba6b34c237306d25d421faa8189d012ed6df31...0d2425aee2917677562ef597b570f8e54c49ce68
diff --git a/java/clients/src/main/java/sleeper/clients/teardown/WaitForStackToDelete.java b/java/clients/src/main/java/sleeper/clients/teardown/WaitForStackToDelete.java index aed4032fd..b0b359257 100644 --- a/java/clients/src/main/java/sleeper/clients/teardown/WaitForStackToDelete.java +++ b/java/clients/src/main/java/sleeper/clients/teardown/WaitForStackToDelete.java @@ -57,6 +57,9 @@ public class WaitForStackToDelete { try { Stack stack = cloudFormationClient.describeStacks(builder -> builder.stackName(stackName)).stacks() .stream().findFirst().orElseThrow(); + if (StackStatus.DELETE_FAILED.equals(stack.stackStatus())) { + throw new DeleteFailedException(stackName); + } LOGGER.info("Stack {} is currently in state {}", stackName, stack.stackStatus()); return stack.stackStatus().equals(StackStatus.DELETE_COMPLETE); } catch (CloudFormationException e) { @@ -64,4 +67,10 @@ public class WaitForStackToDelete { return true; } } + + public static class DeleteFailedException extends RuntimeException { + DeleteFailedException(String stackName) { + super("Failed to delete stack \\"" + stackName + "\\""); + } + } } diff --git a/java/clients/src/test/java/sleeper/clients/teardown/WaitForStackToDeleteIT.java b/java/clients/src/test/java/sleeper/clients/teardown/WaitForStackToDeleteIT.java index 5d7a780ea..afe87e2fc 100644 --- a/java/clients/src/test/java/sleeper/clients/teardown/WaitForStackToDeleteIT.java +++ b/java/clients/src/test/java/sleeper/clients/teardown/WaitForStackToDeleteIT.java @@ -74,6 +74,18 @@ class WaitForStackToDeleteIT { .isInstanceOf(PollWithRetries.TimedOutException.class); } + @Test + void shouldThrowExceptionWhenDeleteFailed(WireMockRuntimeInfo runtimeInfo) { + // Given + stubFor(describeStacksRequestWithStackName("test-stack") + .willReturn(aResponseWithStackName("test-stack", StackStatus.DELETE_FAILED))); + + // When/Then + assertThatThrownBy(() -> waitForStacksToDelete(runtimeInfo, "test-stack")) + .isInstanceOf(WaitForStackToDelete.DeleteFailedException.class) + .hasMessage("Failed to delete stack \\"test-stack\\""); + } + private static void waitForStacksToDelete(WireMockRuntimeInfo runtimeInfo, String stackName) throws InterruptedException { WaitForStackToDelete.from( PollWithRetries.intervalAndMaxPolls(0, 1),
['java/clients/src/test/java/sleeper/clients/teardown/WaitForStackToDeleteIT.java', 'java/clients/src/main/java/sleeper/clients/teardown/WaitForStackToDelete.java']
{'.java': 2}
2
2
0
0
2
2,998,420
588,565
71,523
641
362
61
9
1
573
89
124
13
0
0
"1970-01-01T00:28:10"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,673
gchq/sleeper/1158/1134
gchq
sleeper
https://github.com/gchq/sleeper/issues/1134
https://github.com/gchq/sleeper/pull/1158
https://github.com/gchq/sleeper/pull/1158
1
resolves
Average rates in reports include runs with no records
### Description The average record rate is computed as `NaN` if runs are present with no records. Here is an example of a report where the calculation was incorrect: [compactionPerformance.report.log](https://github.com/gchq/sleeper/files/12367795/compactionPerformance.report.2.log) ### Steps to reproduce 1. Run a compaction job on a compaction task 2. Run a compaction task that wont pick up any jobs 3. Run compaction task status report 4. Observe the average record rate is `NaN` ### Expected behaviour We should filter runs with no records out of the average record rate calculations
910a92e99cd23c798c0d3756e1532c44ffc231a0
6c5a66abb390af3d44bab508548747c20626955d
https://github.com/gchq/sleeper/compare/910a92e99cd23c798c0d3756e1532c44ffc231a0...6c5a66abb390af3d44bab508548747c20626955d
diff --git a/java/core/src/main/java/sleeper/core/record/process/AverageRecordRate.java b/java/core/src/main/java/sleeper/core/record/process/AverageRecordRate.java index 0218ef974..7941a1a6c 100644 --- a/java/core/src/main/java/sleeper/core/record/process/AverageRecordRate.java +++ b/java/core/src/main/java/sleeper/core/record/process/AverageRecordRate.java @@ -113,8 +113,12 @@ public class AverageRecordRate { recordsRead += summary.getRecordsRead(); recordsWritten += summary.getRecordsWritten(); totalRunDuration = totalRunDuration.plus(summary.getTimeInProcess()); - totalRecordsReadPerSecond += summary.getRecordsReadPerSecond(); - totalRecordsWrittenPerSecond += summary.getRecordsWrittenPerSecond(); + if (Double.isFinite(summary.getRecordsReadPerSecond())) { + totalRecordsReadPerSecond += summary.getRecordsReadPerSecond(); + } + if (Double.isFinite(summary.getRecordsWrittenPerSecond())) { + totalRecordsWrittenPerSecond += summary.getRecordsWrittenPerSecond(); + } return this; } diff --git a/java/core/src/test/java/sleeper/core/record/process/AverageRecordRateTest.java b/java/core/src/test/java/sleeper/core/record/process/AverageRecordRateTest.java index 7beffc9ad..8dd6a280f 100644 --- a/java/core/src/test/java/sleeper/core/record/process/AverageRecordRateTest.java +++ b/java/core/src/test/java/sleeper/core/record/process/AverageRecordRateTest.java @@ -110,6 +110,54 @@ public class AverageRecordRateTest { ).containsExactly(1, 100L, 100L, Duration.ofSeconds(20), 5.0, 5.0, 10.0, 10.0); } + @Test + void shouldExcludeRunsWithZeroRecordsReadFromAverageRateCalculation() { + AverageRecordRate rate = rateFrom( + new RecordsProcessedSummary( + new RecordsProcessed(0L, 10L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(10)), + new RecordsProcessedSummary( + new RecordsProcessed(10L, 10L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(10))); + + assertThat(rate).extracting("runCount", "recordsRead", "recordsWritten", "totalDuration", + "recordsReadPerSecond", "recordsWrittenPerSecond", + "averageRunRecordsReadPerSecond", "averageRunRecordsWrittenPerSecond" + ).containsExactly(2, 10L, 20L, Duration.ofSeconds(20), 0.5, 1.0, 0.5, 1.0); + } + + @Test + void shouldExcludeRunsWithZeroRecordsWrittenFromAverageRateCalculation() { + AverageRecordRate rate = rateFrom( + new RecordsProcessedSummary( + new RecordsProcessed(10L, 0L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(10)), + new RecordsProcessedSummary( + new RecordsProcessed(10L, 10L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(10))); + + assertThat(rate).extracting("runCount", "recordsRead", "recordsWritten", "totalDuration", + "recordsReadPerSecond", "recordsWrittenPerSecond", + "averageRunRecordsReadPerSecond", "averageRunRecordsWrittenPerSecond" + ).containsExactly(2, 20L, 10L, Duration.ofSeconds(20), 1.0, 0.5, 1.0, 0.5); + } + + @Test + void shouldExcludeRunsWithZeroDurationFromAverageRateCalculation() { + AverageRecordRate rate = rateFrom( + new RecordsProcessedSummary( + new RecordsProcessed(10L, 10L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(0)), + new RecordsProcessedSummary( + new RecordsProcessed(10L, 10L), + Instant.parse("2022-10-13T10:18:00.000Z"), Duration.ofSeconds(10))); + + assertThat(rate).extracting("runCount", "recordsRead", "recordsWritten", "totalDuration", + "recordsReadPerSecond", "recordsWrittenPerSecond", + "averageRunRecordsReadPerSecond", "averageRunRecordsWrittenPerSecond" + ).containsExactly(2, 20L, 20L, Duration.ofSeconds(10), 2.0, 2.0, 0.5, 0.5); + } + private static AverageRecordRate rateFrom(RecordsProcessedSummary... summaries) { return AverageRecordRate.of(Stream.of(summaries) .map(summary -> ProcessRun.finished(DEFAULT_TASK_ID,
['java/core/src/main/java/sleeper/core/record/process/AverageRecordRate.java', 'java/core/src/test/java/sleeper/core/record/process/AverageRecordRateTest.java']
{'.java': 2}
2
2
0
0
2
3,087,136
606,416
73,335
659
502
88
8
1
613
85
139
17
1
0
"1970-01-01T00:28:12"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,674
gchq/sleeper/1144/929
gchq
sleeper
https://github.com/gchq/sleeper/issues/929
https://github.com/gchq/sleeper/pull/1144
https://github.com/gchq/sleeper/pull/1144
1
resolves
Ingest batcher state store tests fail intermittently
A test failed to query pending records and assert the sort order. No records were returned at all, when 3 records were added to the store. It's not clear why this would happen. We can update this issue when it happens and try to figure it out. Here are several times this happened in DynamoDBIngestBatcherStoreIT$OrderFilesReturnedFromStore.shouldListPendingFilesInOrderRequestsReceivedOldestFirst: https://github.com/gchq/sleeper/actions/runs/5344363020/jobs/9688654804 https://github.com/gchq/sleeper/runs/14467112289 https://github.com/gchq/sleeper/actions/runs/5389911405/jobs/9784528532 https://github.com/gchq/sleeper/runs/14589403331 Here it happened in DynamoDBIngestBatcherStoreIT$AssignFilesToJobs.shouldFailToAssignFileWhenAssignmentAlreadyExists: https://github.com/gchq/sleeper/actions/runs/5654678408/job/15318234077 https://github.com/gchq/sleeper/runs/15318336515 Here it happened in DynamoDBIngestBatcherStoreIT$AssignFilesToJobs.shouldFailToAssignFilesWhenOneIsAlreadyAssigned, with just one of the files missing: https://github.com/mh674563/sleeper/actions/runs/5586589682/jobs/10210939461 https://github.com/mh674563/sleeper/actions/runs/5586589706/attempts/1 Here it happened in DynamoDBIngestBatcherStoreIT$OrderFilesReturnedFromStore.shouldReportAllFilesInOrderRequestsReceivedMostRecentFirst: https://github.com/gchq/sleeper/actions/runs/5760737290/attempts/1 Here are some transaction cancellation failures: https://github.com/gchq/sleeper/actions/runs/5521500088/jobs/10069693700 https://github.com/gchq/sleeper/runs/14949826850 https://github.com/gchq/sleeper/actions/runs/5654361346/job/15317281795?pr=1043
88d62b56dbac566bf3d82bd07e1ae149741d5f49
e32762d810a734361cc90d4af012fdb1aa33f2e2
https://github.com/gchq/sleeper/compare/88d62b56dbac566bf3d82bd07e1ae149741d5f49...e32762d810a734361cc90d4af012fdb1aa33f2e2
diff --git a/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java b/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java index 0441358ab..ac1c48f3e 100644 --- a/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java +++ b/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java @@ -18,15 +18,18 @@ package sleeper.ingest.batcher.store; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.BatchWriteItemRequest; +import com.amazonaws.services.dynamodbv2.model.ConsumedCapacity; import com.amazonaws.services.dynamodbv2.model.Delete; import com.amazonaws.services.dynamodbv2.model.DeleteRequest; import com.amazonaws.services.dynamodbv2.model.Put; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; +import com.amazonaws.services.dynamodbv2.model.PutItemResult; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.TransactWriteItem; import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsRequest; +import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsResult; import com.amazonaws.services.dynamodbv2.model.TransactionCanceledException; import com.amazonaws.services.dynamodbv2.model.WriteRequest; import org.slf4j.Logger; @@ -41,6 +44,7 @@ import sleeper.ingest.batcher.IngestBatcherStore; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -73,10 +77,12 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { @Override public void addFile(FileIngestRequest fileIngestRequest) { - dynamoDB.putItem(new PutItemRequest() + PutItemResult result = dynamoDB.putItem(new PutItemRequest() .withTableName(requestsTableName) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .withItem(DynamoDBIngestRequestFormat.createRecord(tablePropertiesProvider, fileIngestRequest))); + LOGGER.debug("Put request to ingest file {} to table {}, capacity consumed = {}", + fileIngestRequest.getFile(), fileIngestRequest.getTableName(), result.getConsumedCapacity().getCapacityUnits()); } @Override @@ -85,7 +91,8 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { for (int i = 0; i < filesInJob.size(); i += 50) { List<FileIngestRequest> filesInBatch = filesInJob.subList(i, Math.min(i + 50, filesInJob.size())); try { - dynamoDB.transactWriteItems(new TransactWriteItemsRequest() + TransactWriteItemsRequest request = new TransactWriteItemsRequest() + .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .withTransactItems(filesInBatch.stream() .flatMap(file -> Stream.of( new TransactWriteItem().withDelete(new Delete() @@ -99,11 +106,18 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { tablePropertiesProvider, file.toBuilder().jobId(jobId).build())) .withConditionExpression("attribute_not_exists(#filepath)") .withExpressionAttributeNames(Map.of("#filepath", FILE_PATH)))) - ).collect(Collectors.toList()))); + ).collect(Collectors.toList())); + TransactWriteItemsResult result = dynamoDB.transactWriteItems(request); + List<ConsumedCapacity> consumedCapacity = Optional.ofNullable(result.getConsumedCapacity()).orElse(List.of()); + double totalConsumed = consumedCapacity.stream().mapToDouble(ConsumedCapacity::getCapacityUnits).sum(); + LOGGER.debug("Assigned {} files to job {}, capacity consumed = {}", + filesInBatch.size(), jobId, totalConsumed); assignedFiles.addAll(filesInBatch); } catch (TransactionCanceledException e) { LOGGER.error("{} files could not be batched, leaving them for next batcher run.", filesInBatch.size()); - LOGGER.error("Cancellation reasons: {}", e.getCancellationReasons(), e); + long numFailures = e.getCancellationReasons().stream() + .filter(reason -> !"None".equals(reason.getCode())).count(); + LOGGER.error("Cancellation reasons ({} failures): {}", numFailures, e.getCancellationReasons(), e); } catch (RuntimeException e) { LOGGER.error("{} files could not be batched, leaving them for next batcher run.", filesInBatch.size(), e); } diff --git a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java index f721427dc..832ef8abf 100644 --- a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java +++ b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java @@ -256,9 +256,9 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // Given // Transaction limit is 100. 2 transactions are performed per job, so send 50 files List<FileIngestRequest> fileIngestRequests = IntStream.range(0, 50) - .mapToObj(i -> fileRequest().file("test-bucket/file-" + i + ".parquet").build()) + .mapToObj(i -> fileRequest().build()) .collect(Collectors.toUnmodifiableList()); - fileIngestRequests.forEach(store::addFile); + addFiles(fileIngestRequests); // Add files transactionally as DynamoDB local is inconsistent otherwise // When store.assignJobGetAssigned("test-job", fileIngestRequests); @@ -272,9 +272,9 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // Given // Transaction limit is 100. 2 transactions are performed per job, so send 51 files List<FileIngestRequest> fileIngestRequests = IntStream.range(0, 51) - .mapToObj(i -> fileRequest().file("test-bucket/file-" + i + ".parquet").build()) + .mapToObj(i -> fileRequest().build()) .collect(Collectors.toUnmodifiableList()); - fileIngestRequests.forEach(store::addFile); + addFiles(fileIngestRequests); // Add files transactionally as DynamoDB local is inconsistent otherwise // When store.assignJobGetAssigned("test-job", fileIngestRequests); diff --git a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java index 9386f9987..e01007d18 100644 --- a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java +++ b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java @@ -15,6 +15,10 @@ */ package sleeper.ingest.batcher.store; +import com.amazonaws.services.dynamodbv2.model.Put; +import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity; +import com.amazonaws.services.dynamodbv2.model.TransactWriteItem; +import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -23,9 +27,11 @@ import sleeper.configuration.properties.table.FixedTablePropertiesProvider; import sleeper.configuration.properties.table.TableProperties; import sleeper.configuration.properties.table.TablePropertiesProvider; import sleeper.dynamodb.tools.DynamoDBTestBase; +import sleeper.ingest.batcher.FileIngestRequest; import sleeper.ingest.batcher.IngestBatcherStore; import java.util.List; +import java.util.stream.Collectors; import static sleeper.configuration.properties.InstancePropertiesTestHelper.createTestInstanceProperties; import static sleeper.configuration.properties.instance.CommonProperty.ID; @@ -55,4 +61,14 @@ public class DynamoDBIngestBatcherStoreTestBase extends DynamoDBTestBase { void tearDown() { DynamoDBIngestBatcherStoreCreator.tearDown(instanceProperties, dynamoDBClient); } + + protected void addFiles(List<FileIngestRequest> fileIngestRequests) { + dynamoDBClient.transactWriteItems(new TransactWriteItemsRequest() + .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) + .withTransactItems(fileIngestRequests.stream() + .map(file -> new TransactWriteItem().withPut(new Put() + .withTableName(requestsTableName) + .withItem(DynamoDBIngestRequestFormat.createRecord(tablePropertiesProvider, file))) + ).collect(Collectors.toList()))); + } }
['java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java', 'java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java', 'java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java']
{'.java': 3}
3
3
0
0
3
3,066,944
602,390
72,831
652
1,803
331
22
1
1,646
95
466
31
12
0
"1970-01-01T00:28:11"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,675
gchq/sleeper/1129/1127
gchq
sleeper
https://github.com/gchq/sleeper/issues/1127
https://github.com/gchq/sleeper/pull/1129
https://github.com/gchq/sleeper/pull/1129
1
resolves
EMR instance types are invalid with the same weight for different types
### Description In all the EMR instance types properties, weights for the different instance types are set in-line with the instance types. A validation predicate has been added for those properties which ensures that duplicate instance types are not set, but it includes the weights in the duplication test. This means that you can't set the same weight for more than one instance type. ### Steps to reproduce 1. Open the admin client with EmrBulkImportStack deployed 2. Update table property `sleeper.table.bulk.import.emr.master.x86.instance.types` to `m5.xlarge,2,m6i.xlarge,2` 3. See the property change fails to validate ### Expected behaviour We should be able to set the same weight for multiple instance types on any instance types property.
64b25ae2789015e9df88eb60c3f8f0b768dc4357
46cdf0f74fe39ccd1b6031749019de233b10cbdc
https://github.com/gchq/sleeper/compare/64b25ae2789015e9df88eb60c3f8f0b768dc4357...46cdf0f74fe39ccd1b6031749019de233b10cbdc
diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java b/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java index 73c852553..9d5f312f5 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java @@ -75,6 +75,9 @@ public class EmrInstanceTypeConfig { } public static boolean isValidInstanceTypes(String value) { + if (value == null) { + return false; + } try { List<String> instanceTypes = readInstanceTypesProperty(readList(value), X86_64) .map(EmrInstanceTypeConfig::getInstanceType) diff --git a/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java b/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java index 6231d6fa0..d1f14d7da 100644 --- a/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java @@ -209,6 +209,12 @@ public class EmrInstanceTypeConfigTest { assertThat(EmrInstanceTypeConfig.isValidInstanceTypes("1,type-a")) .isFalse(); } + + @Test + void shouldFailValidationWhenInstanceTypesPropertyIsNull() { + assertThat(EmrInstanceTypeConfig.isValidInstanceTypes(null)) + .isFalse(); + } } public static Stream<EmrInstanceTypeConfig> readInstanceTypesProperty(List<String> instanceTypeEntries) {
['java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java', 'java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java']
{'.java': 2}
2
2
0
0
2
3,062,766
601,509
72,754
652
67
14
3
1
770
112
161
15
0
0
"1970-01-01T00:28:11"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,676
gchq/sleeper/1128/1127
gchq
sleeper
https://github.com/gchq/sleeper/issues/1127
https://github.com/gchq/sleeper/pull/1128
https://github.com/gchq/sleeper/pull/1128
1
resolves
EMR instance types are invalid with the same weight for different types
### Description In all the EMR instance types properties, weights for the different instance types are set in-line with the instance types. A validation predicate has been added for those properties which ensures that duplicate instance types are not set, but it includes the weights in the duplication test. This means that you can't set the same weight for more than one instance type. ### Steps to reproduce 1. Open the admin client with EmrBulkImportStack deployed 2. Update table property `sleeper.table.bulk.import.emr.master.x86.instance.types` to `m5.xlarge,2,m6i.xlarge,2` 3. See the property change fails to validate ### Expected behaviour We should be able to set the same weight for multiple instance types on any instance types property.
7fcb9fa29ff0340d4a3839c0863b02aaabf69b05
23ed30872c8620cf313b9ae95f0a0c2763007297
https://github.com/gchq/sleeper/compare/7fcb9fa29ff0340d4a3839c0863b02aaabf69b05...23ed30872c8620cf313b9ae95f0a0c2763007297
diff --git a/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/executor/EmrInstanceFleets.java b/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/executor/EmrInstanceFleets.java index 7577fbd3a..336074cda 100644 --- a/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/executor/EmrInstanceFleets.java +++ b/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/executor/EmrInstanceFleets.java @@ -35,7 +35,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import static sleeper.bulkimport.configuration.EmrInstanceTypeConfig.readInstanceTypes; import static sleeper.configuration.properties.instance.CommonProperty.SUBNETS; import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES; import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_EMR_EXECUTOR_MARKET_TYPE; @@ -45,6 +44,7 @@ import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_E import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES; import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES; import static sleeper.configuration.properties.table.TableProperty.BULK_IMPORT_EMR_MAX_EXECUTOR_CAPACITY; +import static sleeper.configuration.properties.validation.EmrInstanceTypeConfig.readInstanceTypes; public class EmrInstanceFleets implements EmrInstanceConfiguration { diff --git a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/PersistentEmrBulkImportStack.java b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/PersistentEmrBulkImportStack.java index aef3b527b..91239410c 100644 --- a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/PersistentEmrBulkImportStack.java +++ b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/PersistentEmrBulkImportStack.java @@ -47,7 +47,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import static sleeper.bulkimport.configuration.EmrInstanceTypeConfig.readInstanceTypes; import static sleeper.configuration.properties.instance.CommonProperty.ID; import static sleeper.configuration.properties.instance.CommonProperty.SUBNETS; import static sleeper.configuration.properties.instance.EMRProperty.BULK_IMPORT_EMR_EBS_VOLUMES_PER_INSTANCE; @@ -68,6 +67,7 @@ import static sleeper.configuration.properties.instance.PersistentEMRProperty.BU import static sleeper.configuration.properties.instance.SystemDefinedInstanceProperty.BULK_IMPORT_PERSISTENT_EMR_CLUSTER_NAME; import static sleeper.configuration.properties.instance.SystemDefinedInstanceProperty.BULK_IMPORT_PERSISTENT_EMR_JOB_QUEUE_URL; import static sleeper.configuration.properties.instance.SystemDefinedInstanceProperty.BULK_IMPORT_PERSISTENT_EMR_MASTER_DNS; +import static sleeper.configuration.properties.validation.EmrInstanceTypeConfig.readInstanceTypes; /** diff --git a/java/configuration/src/main/java/sleeper/configuration/Utils.java b/java/configuration/src/main/java/sleeper/configuration/Utils.java index 7753af077..414e43523 100644 --- a/java/configuration/src/main/java/sleeper/configuration/Utils.java +++ b/java/configuration/src/main/java/sleeper/configuration/Utils.java @@ -22,7 +22,6 @@ import sleeper.configuration.properties.SleeperProperties; import sleeper.configuration.properties.table.CompressionCodec; import sleeper.configuration.properties.validation.EmrInstanceArchitecture; -import java.util.List; import java.util.Set; import java.util.function.DoublePredicate; import java.util.function.IntPredicate; @@ -158,14 +157,6 @@ public class Utils { .allMatch(architecture -> EnumUtils.isValidEnumIgnoreCase(EmrInstanceArchitecture.class, architecture)); } - public static boolean isUniqueList(String input) { - if (input == null) { - return false; - } - List<String> inputList = SleeperProperties.readList(input); - return inputList.stream().distinct().count() == inputList.size(); - } - private static boolean parseAndCheckInteger(String string, IntPredicate check) { try { return check.test(Integer.parseInt(string)); diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java b/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java index 70824e5e8..e1291bd52 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java @@ -19,6 +19,7 @@ package sleeper.configuration.properties.instance; import sleeper.configuration.Utils; import sleeper.configuration.properties.SleeperPropertyIndex; +import sleeper.configuration.properties.validation.EmrInstanceTypeConfig; import java.util.List; @@ -38,32 +39,32 @@ public interface NonPersistentEMRProperty { .validationPredicate(Utils::isValidArchitecture) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.master.x86.instance.types") - .description("(Non-persistent EMR mode only) The default EC2 x86 instance types to be used for the master " + - "node of the EMR cluster. " + + .description("(Non-persistent EMR mode only) The default EC2 x86_64 instance types and weights to be " + + "used for the master node of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6i.xlarge") - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.x86.instance.types") - .description("(Non-persistent EMR mode only) The default EC2 x86_64 instance types to be used for the executor " + - "nodes of the EMR cluster. " + + .description("(Non-persistent EMR mode only) The default EC2 x86_64 instance types and weights to be " + + "used for the executor nodes of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6i.4xlarge") - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.master.arm.instance.types") - .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types to be used for the master " + - "node of the EMR cluster. " + + .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types and weights to be used " + + "for the master node of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6g.xlarge") - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.arm.instance.types") - .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types to be used for the executor " + - "nodes of the EMR cluster. " + + .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types and weights to be used " + + "for the executor nodes of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6g.4xlarge") - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_MARKET_TYPE = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.market.type") .description("(Non-persistent EMR mode only) The default purchasing option to be used for the executor " + diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java b/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java index c31c79c71..71e41cf29 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java @@ -19,6 +19,7 @@ package sleeper.configuration.properties.instance; import sleeper.configuration.Utils; import sleeper.configuration.properties.SleeperPropertyIndex; +import sleeper.configuration.properties.validation.EmrInstanceTypeConfig; import java.util.List; @@ -42,35 +43,35 @@ public interface PersistentEMRProperty { .validationPredicate(Utils::isValidArchitecture) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_MASTER_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.master.x86.instance.types") - .description("(Persistent EMR mode only) The EC2 x86 instance types used for the master node of the " + - "persistent EMR cluster. " + + .description("(Persistent EMR mode only) The EC2 x86_64 instance types and weights used for the master " + + "node of the persistent EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES.getDefaultValue()) - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_EXECUTOR_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.executor.x86.instance.types") - .description("(Persistent EMR mode only) The EC2 x86 instance types used for the executor nodes of the " + - "persistent EMR cluster. " + + .description("(Persistent EMR mode only) The EC2 x86_64 instance types and weights used for the executor " + + "nodes of the persistent EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES.getDefaultValue()) - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_MASTER_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.master.arm.instance.types") - .description("(Persistent EMR mode only) The EC2 ARM64 instance types used for the master node of the " + - "persistent EMR cluster. " + + .description("(Persistent EMR mode only) The EC2 ARM64 instance types and weights used for the master " + + "node of the persistent EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES.getDefaultValue()) - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_EXECUTOR_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.executor.arm.instance.types") - .description("(Persistent EMR mode only) The EC2 ARM64 instance types used for the executor nodes of the " + - "persistent EMR cluster. " + + .description("(Persistent EMR mode only) The EC2 ARM64 instance types and weights used for the executor " + + "nodes of the persistent EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES.getDefaultValue()) - .validationPredicate(Utils::isUniqueList) + .validationPredicate(EmrInstanceTypeConfig::isValidInstanceTypes) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_USE_MANAGED_SCALING = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.use.managed.scaling") diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/table/TableProperty.java b/java/configuration/src/main/java/sleeper/configuration/properties/table/TableProperty.java index 46a2dc1e6..9812e7cd7 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/table/TableProperty.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/table/TableProperty.java @@ -235,29 +235,29 @@ public interface TableProperty extends SleeperProperty { .build(); TableProperty BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.table.bulk.import.emr.master.x86.instance.types") .defaultProperty(DEFAULT_BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES) - .description("(Non-persistent EMR mode only) The EC2 x86_64 instance types to be used for the master node of the " + - "EMR cluster. " + + .description("(Non-persistent EMR mode only) The EC2 x86_64 instance types and weights to be used for " + + "the master node of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .propertyGroup(TablePropertyGroup.BULK_IMPORT) .build(); TableProperty BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.table.bulk.import.emr.executor.x86.instance.types") .defaultProperty(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES) - .description("(Non-persistent EMR mode only) The EC2 x86_64 instance types to be used for the executor nodes of " + - "the EMR cluster. " + + .description("(Non-persistent EMR mode only) The EC2 x86_64 instance types and weights to be used for " + + "the executor nodes of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .propertyGroup(TablePropertyGroup.BULK_IMPORT) .build(); TableProperty BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.table.bulk.import.emr.master.arm.instance.types") .defaultProperty(DEFAULT_BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES) - .description("(Non-persistent EMR mode only) The EC2 ARM64 instance types to be used for the master node of the " + - "EMR cluster. " + + .description("(Non-persistent EMR mode only) The EC2 ARM64 instance types and weights to be used for the " + + "master node of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .propertyGroup(TablePropertyGroup.BULK_IMPORT) .build(); TableProperty BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.table.bulk.import.emr.executor.arm.instance.types") .defaultProperty(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES) - .description("(Non-persistent EMR mode only) The EC2 ARM64 instance types to be used for the executor nodes of " + - "the EMR cluster. " + + .description("(Non-persistent EMR mode only) The EC2 ARM64 instance types and weights to be used for the " + + "executor nodes of the EMR cluster.\\n" + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .propertyGroup(TablePropertyGroup.BULK_IMPORT) .build(); diff --git a/java/bulk-import/bulk-import-common/src/main/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfig.java b/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java similarity index 87% rename from java/bulk-import/bulk-import-common/src/main/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfig.java rename to java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java index 7a96ec920..73c852553 100644 --- a/java/bulk-import/bulk-import-common/src/main/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfig.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfig.java @@ -13,21 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package sleeper.bulkimport.configuration; +package sleeper.configuration.properties.validation; import org.apache.commons.lang3.EnumUtils; import sleeper.configuration.properties.SleeperProperties; import sleeper.configuration.properties.instance.SleeperProperty; -import sleeper.configuration.properties.validation.EmrInstanceArchitecture; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.Stream; +import static sleeper.configuration.properties.SleeperProperties.readList; import static sleeper.configuration.properties.validation.EmrInstanceArchitecture.ARM64; +import static sleeper.configuration.properties.validation.EmrInstanceArchitecture.X86_64; public class EmrInstanceTypeConfig { private final EmrInstanceArchitecture architecture; @@ -72,6 +74,17 @@ public class EmrInstanceTypeConfig { return builders.stream().map(Builder::build); } + public static boolean isValidInstanceTypes(String value) { + try { + List<String> instanceTypes = readInstanceTypesProperty(readList(value), X86_64) + .map(EmrInstanceTypeConfig::getInstanceType) + .collect(Collectors.toUnmodifiableList()); + return instanceTypes.size() == instanceTypes.stream().distinct().count(); + } catch (IllegalArgumentException e) { + return false; + } + } + public static Builder builder() { return new Builder(); } diff --git a/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java b/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java index 1b2920d67..7d816dadd 100644 --- a/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java @@ -24,22 +24,6 @@ import static org.assertj.core.api.Assertions.assertThat; class UtilsTest { - @Nested - @DisplayName("Validate lists") - class ValidateLists { - @Test - void shouldValidateListWithUniqueElements() { - assertThat(Utils.isUniqueList("test-a,test-b,test-c")) - .isTrue(); - } - - @Test - void shouldFailToValidateListWithDuplicates() { - assertThat(Utils.isUniqueList("test-a,test-b,test-a")) - .isFalse(); - } - } - @Nested @DisplayName("Validate numbers") class ValidateNumbers { diff --git a/java/bulk-import/bulk-import-common/src/test/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfigTest.java b/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java similarity index 92% rename from java/bulk-import/bulk-import-common/src/test/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfigTest.java rename to java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java index a4a436d58..6231d6fa0 100644 --- a/java/bulk-import/bulk-import-common/src/test/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfigTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/properties/validation/EmrInstanceTypeConfigTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package sleeper.bulkimport.configuration; +package sleeper.configuration.properties.validation; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import sleeper.configuration.properties.instance.InstanceProperties; import sleeper.configuration.properties.table.TableProperties; -import sleeper.configuration.properties.validation.EmrInstanceArchitecture; import java.util.List; import java.util.stream.Stream; @@ -189,6 +188,29 @@ public class EmrInstanceTypeConfigTest { } } + @Nested + @DisplayName("Validate values") + class ValidateValue { + + @Test + void shouldFailValidationWhenSameInstanceTypeIsSpecifiedTwice() { + assertThat(EmrInstanceTypeConfig.isValidInstanceTypes("type-a,type-b,type-c,type-b")) + .isFalse(); + } + + @Test + void shouldPassValidationWhenTwoInstanceTypesHaveSameWeight() { + assertThat(EmrInstanceTypeConfig.isValidInstanceTypes("type-a,1,type-b,2,type-c,2")) + .isTrue(); + } + + @Test + void shouldFailValidationWhenWeightSpecifiedBeforeAnInstanceType() { + assertThat(EmrInstanceTypeConfig.isValidInstanceTypes("1,type-a")) + .isFalse(); + } + } + public static Stream<EmrInstanceTypeConfig> readInstanceTypesProperty(List<String> instanceTypeEntries) { return EmrInstanceTypeConfig.readInstanceTypesProperty(instanceTypeEntries, EmrInstanceArchitecture.X86_64); }
['java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/executor/EmrInstanceFleets.java', 'java/configuration/src/main/java/sleeper/configuration/properties/table/TableProperty.java', 'java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java', 'java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java', 'java/configuration/src/main/java/sleeper/configuration/Utils.java', 'java/bulk-import/bulk-import-common/src/test/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfigTest.java', 'java/bulk-import/bulk-import-common/src/main/java/sleeper/bulkimport/configuration/EmrInstanceTypeConfig.java', 'java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/PersistentEmrBulkImportStack.java', 'java/configuration/src/test/java/sleeper/configuration/UtilsTest.java']
{'.java': 9}
9
9
0
0
9
3,022,034
593,625
72,128
649
6,194
1,299
79
7
770
112
161
15
0
0
"1970-01-01T00:28:11"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,677
gchq/sleeper/1121/929
gchq
sleeper
https://github.com/gchq/sleeper/issues/929
https://github.com/gchq/sleeper/pull/1121
https://github.com/gchq/sleeper/pull/1121
1
resolves
Ingest batcher state store tests fail intermittently
A test failed to query pending records and assert the sort order. No records were returned at all, when 3 records were added to the store. It's not clear why this would happen. We can update this issue when it happens and try to figure it out. Here are several times this happened in DynamoDBIngestBatcherStoreIT$OrderFilesReturnedFromStore.shouldListPendingFilesInOrderRequestsReceivedOldestFirst: https://github.com/gchq/sleeper/actions/runs/5344363020/jobs/9688654804 https://github.com/gchq/sleeper/runs/14467112289 https://github.com/gchq/sleeper/actions/runs/5389911405/jobs/9784528532 https://github.com/gchq/sleeper/runs/14589403331 Here it happened in DynamoDBIngestBatcherStoreIT$AssignFilesToJobs.shouldFailToAssignFileWhenAssignmentAlreadyExists: https://github.com/gchq/sleeper/actions/runs/5654678408/job/15318234077 https://github.com/gchq/sleeper/runs/15318336515 Here it happened in DynamoDBIngestBatcherStoreIT$AssignFilesToJobs.shouldFailToAssignFilesWhenOneIsAlreadyAssigned, with just one of the files missing: https://github.com/mh674563/sleeper/actions/runs/5586589682/jobs/10210939461 https://github.com/mh674563/sleeper/actions/runs/5586589706/attempts/1 Here it happened in DynamoDBIngestBatcherStoreIT$OrderFilesReturnedFromStore.shouldReportAllFilesInOrderRequestsReceivedMostRecentFirst: https://github.com/gchq/sleeper/actions/runs/5760737290/attempts/1 Here are some transaction cancellation failures: https://github.com/gchq/sleeper/actions/runs/5521500088/jobs/10069693700 https://github.com/gchq/sleeper/runs/14949826850 https://github.com/gchq/sleeper/actions/runs/5654361346/job/15317281795?pr=1043
6c47b9ec65078a270a4859612697695185e4f1f2
5d17cbb132efff6b21d1a17ed2bc4b2bd0fdf61b
https://github.com/gchq/sleeper/compare/6c47b9ec65078a270a4859612697695185e4f1f2...5d17cbb132efff6b21d1a17ed2bc4b2bd0fdf61b
diff --git a/java/ingest/ingest-batcher-job-creator/src/test/java/sleeper/ingest/batcher/job/creator/IngestBatcherJobCreatorLambdaIT.java b/java/ingest/ingest-batcher-job-creator/src/test/java/sleeper/ingest/batcher/job/creator/IngestBatcherJobCreatorLambdaIT.java index 2ea932ba2..82f66f3f8 100644 --- a/java/ingest/ingest-batcher-job-creator/src/test/java/sleeper/ingest/batcher/job/creator/IngestBatcherJobCreatorLambdaIT.java +++ b/java/ingest/ingest-batcher-job-creator/src/test/java/sleeper/ingest/batcher/job/creator/IngestBatcherJobCreatorLambdaIT.java @@ -73,8 +73,8 @@ public class IngestBatcherJobCreatorLambdaIT { properties.set(DEFAULT_INGEST_BATCHER_MIN_JOB_SIZE, "0"); }); private final TableProperties tableProperties = createTestTableProperties(instanceProperties, schemaWithKey("key"), s3); - private final IngestBatcherStore store = new DynamoDBIngestBatcherStore(dynamoDB, instanceProperties, - new TablePropertiesProvider(s3, instanceProperties)); + private final IngestBatcherStore store = DynamoDBIngestBatcherStore.withConsistentReads( + dynamoDB, instanceProperties, new TablePropertiesProvider(s3, instanceProperties)); private IngestBatcherJobCreatorLambda lambdaWithTimesAndJobIds(List<Instant> times, List<String> jobIds) { return new IngestBatcherJobCreatorLambda( @@ -103,6 +103,7 @@ public class IngestBatcherJobCreatorLambdaIT { .fileSizeBytes(1024) .receivedTime(Instant.parse("2023-05-25T14:43:00Z")) .build()); + store.getAllFilesNewestFirst(); // Use consistent reads to ensure PutItem is completed // When lambdaWithTimesAndJobIds( diff --git a/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java b/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java index c85079569..ce96a7459 100644 --- a/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java +++ b/java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java @@ -54,13 +54,29 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { private final AmazonDynamoDB dynamoDB; private final String requestsTableName; private final TablePropertiesProvider tablePropertiesProvider; + private final boolean consistentReads; public DynamoDBIngestBatcherStore(AmazonDynamoDB dynamoDB, InstanceProperties instanceProperties, TablePropertiesProvider tablePropertiesProvider) { + this(dynamoDB, instanceProperties, tablePropertiesProvider, false); + } + + private DynamoDBIngestBatcherStore(AmazonDynamoDB dynamoDB, + InstanceProperties instanceProperties, + TablePropertiesProvider tablePropertiesProvider, + boolean consistentReads) { this.dynamoDB = dynamoDB; this.requestsTableName = ingestRequestsTableName(instanceProperties.get(ID)); this.tablePropertiesProvider = tablePropertiesProvider; + this.consistentReads = consistentReads; + } + + public static DynamoDBIngestBatcherStore withConsistentReads( + AmazonDynamoDB dynamoDB, + InstanceProperties instanceProperties, + TablePropertiesProvider tablePropertiesProvider) { + return new DynamoDBIngestBatcherStore(dynamoDB, instanceProperties, tablePropertiesProvider, true); } public static String ingestRequestsTableName(String instanceId) { @@ -97,7 +113,8 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { @Override public List<FileIngestRequest> getAllFilesNewestFirst() { return streamPagedItems(dynamoDB, new ScanRequest() - .withTableName(requestsTableName)) + .withTableName(requestsTableName) + .withConsistentRead(consistentReads)) .map(DynamoDBIngestRequestFormat::readRecord) .sorted(comparing(FileIngestRequest::getReceivedTime).reversed()) .collect(Collectors.toList()); @@ -107,6 +124,7 @@ public class DynamoDBIngestBatcherStore implements IngestBatcherStore { public List<FileIngestRequest> getPendingFilesOldestFirst() { return streamPagedItems(dynamoDB, new QueryRequest() .withTableName(requestsTableName) + .withConsistentRead(consistentReads) .withKeyConditionExpression("#JobId = :not_assigned") .withExpressionAttributeNames(Map.of("#JobId", JOB_ID)) .withExpressionAttributeValues(new DynamoDBRecordBuilder() diff --git a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java index 0eab8ac6c..c619fc269 100644 --- a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java +++ b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java @@ -118,6 +118,13 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // When store.addFile(fileIngestRequest1); store.addFile(fileIngestRequest2); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job", List.of(fileIngestRequest1, fileIngestRequest2)); // Then @@ -137,6 +144,13 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // When store.addFile(fileIngestRequest1); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job", List.of(fileIngestRequest1)); store.addFile(fileIngestRequest2); @@ -159,6 +173,13 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // When store.addFile(fileIngestRequest); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job", List.of(fileIngestRequest)); // Then @@ -178,6 +199,13 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest FileIngestRequest fileIngestRequest = fileRequest() .file("test-bucket/test.parquet").build(); store.addFile(fileIngestRequest); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job-1", List.of(fileIngestRequest)); // When / Then @@ -197,6 +225,13 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest .file("test-bucket/test-2.parquet").build(); store.addFile(fileIngestRequest1); store.addFile(fileIngestRequest2); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job-1", List.of(fileIngestRequest1)); // When / Then @@ -227,9 +262,22 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest FileIngestRequest fileIngestRequest = fileRequest() .file("test-bucket/sendTwice.parquet").build(); store.addFile(fileIngestRequest); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("duplicate-job", List.of(fileIngestRequest)); store.addFile(fileIngestRequest); + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + // When / Then List<FileIngestRequest> duplicateJob = List.of(fileIngestRequest); assertThatThrownBy(() -> store.assignJob("duplicate-job", duplicateJob)) @@ -300,7 +348,8 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest store.addFile(fileIngestRequest); // Then - assertThat(streamPagedItems(dynamoDBClient, new ScanRequest().withTableName(requestsTableName))) + assertThat(streamPagedItems(dynamoDBClient, new ScanRequest() + .withTableName(requestsTableName).withConsistentRead(true))) .extracting(item -> getLongAttribute(item, EXPIRY_TIME, 0L)) .containsExactly(expectedExpiryTime.getEpochSecond()); } @@ -316,10 +365,18 @@ public class DynamoDBIngestBatcherStoreIT extends DynamoDBIngestBatcherStoreTest // When store.addFile(fileIngestRequest); + + // Scan with consistent reads waits for PutItems to complete. + // TransactWriteItems will fail if a PutItem has not yet been committed. + // In production, a scan will happen before the update, so only files that exist in the store will be + // assigned to jobs. + store.getAllFilesNewestFirst(); + store.assignJob("test-job", List.of(fileIngestRequest)); // Then - assertThat(streamPagedItems(dynamoDBClient, new ScanRequest().withTableName(requestsTableName))) + assertThat(streamPagedItems(dynamoDBClient, new ScanRequest() + .withTableName(requestsTableName).withConsistentRead(true))) .extracting(item -> getLongAttribute(item, EXPIRY_TIME, 0L)) .containsExactly(expectedExpiryTime.getEpochSecond()); } diff --git a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java index 9386f9987..a61193cbd 100644 --- a/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java +++ b/java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java @@ -43,7 +43,7 @@ public class DynamoDBIngestBatcherStoreTestBase extends DynamoDBTestBase { private final TablePropertiesProvider tablePropertiesProvider = new FixedTablePropertiesProvider( List.of(table1, table2)); protected final String requestsTableName = DynamoDBIngestBatcherStore.ingestRequestsTableName(instanceProperties.get(ID)); - protected final IngestBatcherStore store = new DynamoDBIngestBatcherStore( + protected final IngestBatcherStore store = DynamoDBIngestBatcherStore.withConsistentReads( dynamoDBClient, instanceProperties, tablePropertiesProvider); @BeforeEach
['java/ingest/ingest-batcher-job-creator/src/test/java/sleeper/ingest/batcher/job/creator/IngestBatcherJobCreatorLambdaIT.java', 'java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreTestBase.java', 'java/ingest/ingest-batcher-store/src/test/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStoreIT.java', 'java/ingest/ingest-batcher-store/src/main/java/sleeper/ingest/batcher/store/DynamoDBIngestBatcherStore.java']
{'.java': 4}
4
4
0
0
4
3,022,034
593,625
72,128
649
1,029
179
20
1
1,646
95
466
31
12
0
"1970-01-01T00:28:11"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,678
gchq/sleeper/1098/1092
gchq
sleeper
https://github.com/gchq/sleeper/issues/1092
https://github.com/gchq/sleeper/pull/1098
https://github.com/gchq/sleeper/pull/1098
1
resolves
Deployment fails if duplicate x86 or arm64 instances are defined in properties
### Description CDK fails to configure the instance fleets if duplicate instances are defined in x86 or arm64 instance properties. An example error is below: `The instance fleet: Driver contains duplicate instance types [m6g.xlarge]` ### Steps to reproduce 1. Set one of the x86 or arm64 instance properties to contain duplicates in the list 2. Observe deployment fails ### Expected behaviour Duplicates should be disallowed in these properties. We can add a validation rule to do this.
34c9d4a402aa6ea880bb548b13bc0fb6bb9c413b
642ca221d877fc3464b3071e32037bd0d559c466
https://github.com/gchq/sleeper/compare/34c9d4a402aa6ea880bb548b13bc0fb6bb9c413b...642ca221d877fc3464b3071e32037bd0d559c466
diff --git a/java/configuration/src/main/java/sleeper/configuration/Utils.java b/java/configuration/src/main/java/sleeper/configuration/Utils.java index 891b89e87..7753af077 100644 --- a/java/configuration/src/main/java/sleeper/configuration/Utils.java +++ b/java/configuration/src/main/java/sleeper/configuration/Utils.java @@ -22,7 +22,6 @@ import sleeper.configuration.properties.SleeperProperties; import sleeper.configuration.properties.table.CompressionCodec; import sleeper.configuration.properties.validation.EmrInstanceArchitecture; -import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.DoublePredicate; @@ -159,10 +158,12 @@ public class Utils { .allMatch(architecture -> EnumUtils.isValidEnumIgnoreCase(EmrInstanceArchitecture.class, architecture)); } - public static <T, A extends T, B extends T> List<T> combineLists(List<A> list1, List<B> list2) { - List<T> combinedList = new ArrayList<>(list1); - combinedList.addAll(list2); - return combinedList; + public static boolean isUniqueList(String input) { + if (input == null) { + return false; + } + List<String> inputList = SleeperProperties.readList(input); + return inputList.stream().distinct().count() == inputList.size(); } private static boolean parseAndCheckInteger(String string, IntPredicate check) { diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java b/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java index 1be1ff384..70824e5e8 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java @@ -42,24 +42,28 @@ public interface NonPersistentEMRProperty { "node of the EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6i.xlarge") + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.x86.instance.types") .description("(Non-persistent EMR mode only) The default EC2 x86_64 instance types to be used for the executor " + "nodes of the EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6i.4xlarge") + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.master.arm.instance.types") .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types to be used for the master " + "node of the EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6g.xlarge") + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.arm.instance.types") .description("(Non-persistent EMR mode only) The default EC2 ARM64 instance types to be used for the executor " + "nodes of the EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue("m6g.4xlarge") + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT).build(); UserDefinedInstanceProperty DEFAULT_BULK_IMPORT_EMR_EXECUTOR_MARKET_TYPE = Index.propertyBuilder("sleeper.default.bulk.import.emr.executor.market.type") .description("(Non-persistent EMR mode only) The default purchasing option to be used for the executor " + diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java b/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java index e76822c68..c31c79c71 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java @@ -46,6 +46,7 @@ public interface PersistentEMRProperty { "persistent EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_MASTER_X86_INSTANCE_TYPES.getDefaultValue()) + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_EXECUTOR_X86_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.executor.x86.instance.types") @@ -53,6 +54,7 @@ public interface PersistentEMRProperty { "persistent EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_X86_INSTANCE_TYPES.getDefaultValue()) + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_MASTER_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.master.arm.instance.types") @@ -60,6 +62,7 @@ public interface PersistentEMRProperty { "persistent EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_MASTER_ARM_INSTANCE_TYPES.getDefaultValue()) + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_EXECUTOR_ARM_INSTANCE_TYPES = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.executor.arm.instance.types") @@ -67,6 +70,7 @@ public interface PersistentEMRProperty { "persistent EMR cluster. " + "For more information, see the Bulk import using EMR - Instance types section in docs/05-ingest.md") .defaultValue(DEFAULT_BULK_IMPORT_EMR_EXECUTOR_ARM_INSTANCE_TYPES.getDefaultValue()) + .validationPredicate(Utils::isUniqueList) .propertyGroup(InstancePropertyGroup.BULK_IMPORT) .runCDKDeployWhenChanged(true).build(); UserDefinedInstanceProperty BULK_IMPORT_PERSISTENT_EMR_USE_MANAGED_SCALING = Index.propertyBuilder("sleeper.bulk.import.persistent.emr.use.managed.scaling") diff --git a/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java b/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java index 5fb256685..1b2920d67 100644 --- a/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/UtilsTest.java @@ -16,88 +16,97 @@ package sleeper.configuration; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; -import static sleeper.configuration.Utils.combineLists; class UtilsTest { - @Test - void shouldCombineLists() { - // Given - List<String> list1 = List.of("test1", "test2"); - List<String> list2 = List.of("test3", "test4"); - - // When - List<String> combinedList = combineLists(list1, list2); - - // Then - assertThat(combinedList) - .containsExactly("test1", "test2", "test3", "test4"); - } - - @Test - void shouldNotThrowExceptionDuringPositiveIntegerCheck() { - // When/Then - assertThat(Utils.isPositiveInteger("123")) - .isTrue(); - assertThat(Utils.isPositiveInteger("ABC")) - .isFalse(); - } - - @Test - void shouldNotThrowExceptionDuringPositiveLongCheck() { - // When/Then - assertThat(Utils.isPositiveLong("123")) - .isTrue(); - assertThat(Utils.isPositiveLong("ABC")) - .isFalse(); - } - - @Test - void shouldNotThrowExceptionDuringPositiveDoubleCheck() { - // When/Then - assertThat(Utils.isPositiveDouble("123")) - .isTrue(); - assertThat(Utils.isPositiveDouble("ABC")) - .isFalse(); - } - - @Test - void shouldReadBytesSize() { - assertThat(Utils.readBytes("42")).isEqualTo(42L); - } - - @Test - void shouldReadKilobytesSize() { - assertThat(Utils.readBytes("2K")).isEqualTo(2048L); - } - - @Test - void shouldReadMegabytesSize() { - assertThat(Utils.readBytes("2M")).isEqualTo(2 * 1024 * 1024L); - } - - @Test - void shouldReadGigabytesSize() { - assertThat(Utils.readBytes("2G")).isEqualTo(2 * 1024 * 1024 * 1024L); - } - - @Test - void shouldReadTerabytesSize() { - assertThat(Utils.readBytes("2T")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L); + @Nested + @DisplayName("Validate lists") + class ValidateLists { + @Test + void shouldValidateListWithUniqueElements() { + assertThat(Utils.isUniqueList("test-a,test-b,test-c")) + .isTrue(); + } + + @Test + void shouldFailToValidateListWithDuplicates() { + assertThat(Utils.isUniqueList("test-a,test-b,test-a")) + .isFalse(); + } } - @Test - void shouldReadPetabytesSize() { - assertThat(Utils.readBytes("2P")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L * 1024L); + @Nested + @DisplayName("Validate numbers") + class ValidateNumbers { + @Test + void shouldNotThrowExceptionDuringPositiveIntegerCheck() { + // When/Then + assertThat(Utils.isPositiveInteger("123")) + .isTrue(); + assertThat(Utils.isPositiveInteger("ABC")) + .isFalse(); + } + + @Test + void shouldNotThrowExceptionDuringPositiveLongCheck() { + // When/Then + assertThat(Utils.isPositiveLong("123")) + .isTrue(); + assertThat(Utils.isPositiveLong("ABC")) + .isFalse(); + } + + @Test + void shouldNotThrowExceptionDuringPositiveDoubleCheck() { + // When/Then + assertThat(Utils.isPositiveDouble("123")) + .isTrue(); + assertThat(Utils.isPositiveDouble("ABC")) + .isFalse(); + } } - @Test - void shouldReadExabytesSize() { - assertThat(Utils.readBytes("2E")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L * 1024L * 1024L); + @Nested + @DisplayName("Validate bytes size") + class ValidateBytesSize { + @Test + void shouldReadBytesSize() { + assertThat(Utils.readBytes("42")).isEqualTo(42L); + } + + @Test + void shouldReadKilobytesSize() { + assertThat(Utils.readBytes("2K")).isEqualTo(2048L); + } + + @Test + void shouldReadMegabytesSize() { + assertThat(Utils.readBytes("2M")).isEqualTo(2 * 1024 * 1024L); + } + + @Test + void shouldReadGigabytesSize() { + assertThat(Utils.readBytes("2G")).isEqualTo(2 * 1024 * 1024 * 1024L); + } + + @Test + void shouldReadTerabytesSize() { + assertThat(Utils.readBytes("2T")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L); + } + + @Test + void shouldReadPetabytesSize() { + assertThat(Utils.readBytes("2P")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L * 1024L); + } + + @Test + void shouldReadExabytesSize() { + assertThat(Utils.readBytes("2E")).isEqualTo(2 * 1024 * 1024 * 1024L * 1024L * 1024L * 1024L); + } } }
['java/configuration/src/test/java/sleeper/configuration/UtilsTest.java', 'java/configuration/src/main/java/sleeper/configuration/properties/instance/PersistentEMRProperty.java', 'java/configuration/src/main/java/sleeper/configuration/properties/instance/NonPersistentEMRProperty.java', 'java/configuration/src/main/java/sleeper/configuration/Utils.java']
{'.java': 4}
4
4
0
0
4
3,001,371
589,398
71,589
642
959
196
19
3
509
77
106
16
0
0
"1970-01-01T00:28:10"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,680
gchq/sleeper/1005/1004
gchq
sleeper
https://github.com/gchq/sleeper/issues/1004
https://github.com/gchq/sleeper/pull/1005
https://github.com/gchq/sleeper/pull/1005
1
resolves
DeployNewInstance uses incorrect number of minimum arguments
### Description When you run `scripts/deploy/deployNew.sh` it invokes `DeployNewInstance`. If you don't specify your own instance.properties file, it fails and you get a usage message. In issue https://github.com/gchq/sleeper/issues/993, we corrected the minimum number of arguments in the shell script, but not in `DeployNewInstance`. ### Steps to reproduce Try to deploy an instance with `scripts/deploy/deployNew.sh`, setting just the instance ID, VPC, subnet and table name. You'll see the usage message coming from `DeployNewInstance`. ### Expected behavior It should deploy an instance, using the template for the instance.properties.
6763b6c4cdbd2a95df417ffcfd89affa1b54e624
2a6923addd3a70e14e103408a12e307d45024675
https://github.com/gchq/sleeper/compare/6763b6c4cdbd2a95df417ffcfd89affa1b54e624...2a6923addd3a70e14e103408a12e307d45024675
diff --git a/java/clients/src/main/java/sleeper/clients/deploy/DeployNewInstance.java b/java/clients/src/main/java/sleeper/clients/deploy/DeployNewInstance.java index 4064287d8..1b37910a7 100644 --- a/java/clients/src/main/java/sleeper/clients/deploy/DeployNewInstance.java +++ b/java/clients/src/main/java/sleeper/clients/deploy/DeployNewInstance.java @@ -82,7 +82,7 @@ public class DeployNewInstance { } public static void main(String[] args) throws IOException, InterruptedException { - if (args.length < 6 || args.length > 8) { + if (args.length < 5 || args.length > 8) { throw new IllegalArgumentException("Usage: <scripts-dir> <instance-id> <vpc> <subnet> <table-name> " + "<optional-instance-properties-file> <optional-deploy-paused-flag> <optional-split-points-file>"); }
['java/clients/src/main/java/sleeper/clients/deploy/DeployNewInstance.java']
{'.java': 1}
1
1
0
0
1
2,958,668
581,637
70,484
621
101
32
2
1
663
86
145
16
1
0
"1970-01-01T00:28:09"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,689
gchq/sleeper/700/697
gchq
sleeper
https://github.com/gchq/sleeper/issues/697
https://github.com/gchq/sleeper/pull/700
https://github.com/gchq/sleeper/pull/700
1
resolves
Compaction test fails if a job starts before it's reported as created
When you run the compaction performance system test, sometimes a compaction job may be pulled off the queue by a compaction task before the status update is recorded in DynamoDB to report that the job has been created. If that happens, the job start time can be recorded as happening before the creation of the job. There's a bug in the compaction reporting code where if a compaction job is started before it's created, it is not shown in the report. The compaction performance test code uses the same logic to detect when a compaction job was created. If it can't see a compaction job it's created, it thinks there's nothing left to do and stops.
b534ff968a00f9b7747a5dcc140f8f384ec6c15f
3fb18cfcc7f360c79769e7b2662f02ce24c61cba
https://github.com/gchq/sleeper/compare/b534ff968a00f9b7747a5dcc140f8f384ec6c15f...3fb18cfcc7f360c79769e7b2662f02ce24c61cba
diff --git a/java/compaction/compaction-core/src/main/java/sleeper/compaction/job/status/CompactionJobStatus.java b/java/compaction/compaction-core/src/main/java/sleeper/compaction/job/status/CompactionJobStatus.java index 4cf12ba81..dbb20eaae 100644 --- a/java/compaction/compaction-core/src/main/java/sleeper/compaction/job/status/CompactionJobStatus.java +++ b/java/compaction/compaction-core/src/main/java/sleeper/compaction/job/status/CompactionJobStatus.java @@ -18,7 +18,6 @@ package sleeper.compaction.job.status; import sleeper.core.record.process.status.JobStatusUpdates; import sleeper.core.record.process.status.ProcessRun; import sleeper.core.record.process.status.ProcessRuns; -import sleeper.core.record.process.status.ProcessStatusUpdate; import sleeper.core.record.process.status.ProcessStatusUpdateRecord; import java.time.Instant; @@ -59,15 +58,13 @@ public class CompactionJobStatus { } private static Optional<CompactionJobStatus> from(JobStatusUpdates updates) { - ProcessStatusUpdate firstUpdate = updates.getFirstRecord().getStatusUpdate(); - if (!(firstUpdate instanceof CompactionJobCreatedStatus)) { - return Optional.empty(); - } - return Optional.of(builder().jobId(updates.getJobId()) - .createdStatus((CompactionJobCreatedStatus) firstUpdate) - .jobRuns(updates.getRuns()) - .expiryDate(updates.getFirstRecord().getExpiryDate()) - .build()); + return updates.getFirstStatusUpdateOfType(CompactionJobCreatedStatus.class) + .map(createdStatus -> builder() + .jobId(updates.getJobId()) + .createdStatus(createdStatus) + .jobRuns(updates.getRuns()) + .expiryDate(updates.getFirstRecord().getExpiryDate()) + .build()); } public Instant getCreateUpdateTime() { diff --git a/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusFromRecordsTest.java b/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusFromRecordsTest.java index 71f68fb78..fd2c7e3f9 100644 --- a/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusFromRecordsTest.java +++ b/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusFromRecordsTest.java @@ -36,10 +36,10 @@ import static sleeper.core.record.process.status.TestProcessStatusUpdateRecords. import static sleeper.core.record.process.status.TestProcessStatusUpdateRecords.forJob; import static sleeper.core.record.process.status.TestRunStatusUpdates.finishedStatus; -public class CompactionJobStatusFromRecordsTest { +class CompactionJobStatusFromRecordsTest { @Test - public void shouldBuildCompactionJobStatusFromIndividualUpdates() { + void shouldBuildCompactionJobStatusFromIndividualUpdates() { // Given CompactionJobCreatedStatus created1 = CompactionJobCreatedStatus.builder() .updateTime(Instant.parse("2022-09-23T09:23:00.012Z")) @@ -72,7 +72,7 @@ public class CompactionJobStatusFromRecordsTest { } @Test - public void shouldIgnoreJobWithNoCreatedUpdate() { + void shouldIgnoreJobWithNoCreatedUpdate() { // Given CompactionJobStartedStatus started = startedCompactionStatus(Instant.parse("2022-09-23T09:23:30.001Z")); ProcessFinishedStatus finished = finishedStatus(started, Duration.ofSeconds(30), 200L, 100L); @@ -84,4 +84,26 @@ public class CompactionJobStatusFromRecordsTest { // Then assertThat(statuses).isEmpty(); } + + @Test + void shouldBuildJobStatusWhenCreatedUpdateStoredAfterStartedUpdate() { + // Given + CompactionJobCreatedStatus created = CompactionJobCreatedStatus.builder() + .updateTime(Instant.parse("2023-03-22T15:36:02Z")) + .partitionId("partition1").childPartitionIds(null) + .inputFilesCount(11) + .build(); + CompactionJobStartedStatus started = startedCompactionStatus(Instant.parse("2023-03-22T15:36:01Z")); + ProcessFinishedStatus finished = finishedStatus(started, Duration.ofSeconds(30), 200L, 100L); + + // When + List<CompactionJobStatus> statuses = jobStatusListFromUpdates( + forJob("test-job", created, started, finished)); + + // Then + assertThat(statuses).containsExactly( + CompactionJobStatus.builder().jobId("test-job").createdStatus(created) + .singleJobRun(ProcessRun.finished(DEFAULT_TASK_ID, started, finished)) + .expiryDate(DEFAULT_EXPIRY).build()); + } } diff --git a/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusTest.java b/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusTest.java index d28bee255..88fcdf730 100644 --- a/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusTest.java +++ b/java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusTest.java @@ -32,12 +32,12 @@ import static sleeper.compaction.job.CompactionJobStatusTestData.jobCreated; import static sleeper.compaction.job.CompactionJobStatusTestData.startedCompactionRun; import static sleeper.core.record.process.status.TestProcessStatusUpdateRecords.DEFAULT_TASK_ID; -public class CompactionJobStatusTest { +class CompactionJobStatusTest { private final CompactionJobTestDataHelper dataHelper = new CompactionJobTestDataHelper(); @Test - public void shouldBuildCompactionJobCreatedFromJob() { + void shouldBuildCompactionJobCreatedFromJob() { // Given Partition partition = dataHelper.singlePartition(); CompactionJob job = dataHelper.singleFileCompaction(partition); @@ -52,7 +52,7 @@ public class CompactionJobStatusTest { } @Test - public void shouldBuildSplittingCompactionJobCreatedFromJob() { + void shouldBuildSplittingCompactionJobCreatedFromJob() { // Given CompactionJob job = dataHelper.singleFileSplittingCompaction("root", "left", "right"); Instant updateTime = Instant.parse("2022-09-22T13:33:12.001Z"); @@ -66,7 +66,7 @@ public class CompactionJobStatusTest { } @Test - public void shouldReportCompactionJobNotStarted() { + void shouldReportCompactionJobNotStarted() { // Given CompactionJob job = dataHelper.singleFileCompaction(); Instant updateTime = Instant.parse("2022-09-22T13:33:12.001Z"); @@ -80,7 +80,7 @@ public class CompactionJobStatusTest { } @Test - public void shouldBuildCompactionJobStarted() { + void shouldBuildCompactionJobStarted() { // Given CompactionJob job = dataHelper.singleFileCompaction(); @@ -94,7 +94,7 @@ public class CompactionJobStatusTest { } @Test - public void shouldBuildCompactionJobFinished() { + void shouldBuildCompactionJobFinished() { // Given CompactionJob job = dataHelper.singleFileCompaction(); Instant startTime = Instant.parse("2022-09-22T13:33:10.001Z"); diff --git a/java/core/src/main/java/sleeper/core/record/process/status/JobStatusUpdates.java b/java/core/src/main/java/sleeper/core/record/process/status/JobStatusUpdates.java index 49ab61400..13ab5511d 100644 --- a/java/core/src/main/java/sleeper/core/record/process/status/JobStatusUpdates.java +++ b/java/core/src/main/java/sleeper/core/record/process/status/JobStatusUpdates.java @@ -17,6 +17,7 @@ package sleeper.core.record.process.status; import java.util.Comparator; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -57,6 +58,16 @@ public class JobStatusUpdates { return recordsLatestFirst.get(0); } + public <T extends ProcessStatusUpdate> Optional<T> getFirstStatusUpdateOfType(Class<T> updateType) { + for (int i = recordsLatestFirst.size() - 1; i >= 0; i--) { + ProcessStatusUpdate update = recordsLatestFirst.get(i).getStatusUpdate(); + if (updateType.isInstance(update)) { + return Optional.of(updateType.cast(update)); + } + } + return Optional.empty(); + } + public ProcessRuns getRuns() { return runs; }
['java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusTest.java', 'java/compaction/compaction-core/src/main/java/sleeper/compaction/job/status/CompactionJobStatus.java', 'java/compaction/compaction-core/src/test/java/sleeper/compaction/job/CompactionJobStatusFromRecordsTest.java', 'java/core/src/main/java/sleeper/core/record/process/status/JobStatusUpdates.java']
{'.java': 4}
4
4
0
0
4
2,435,615
478,358
58,439
515
1,428
263
28
2
650
116
139
5
0
0
"1970-01-01T00:27:59"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,696
gchq/sleeper/256/253
gchq
sleeper
https://github.com/gchq/sleeper/issues/253
https://github.com/gchq/sleeper/pull/256
https://github.com/gchq/sleeper/pull/256
1
resolves
DynamoDB connection closed before compaction task reported as finished
When a compaction task finishes, the DynamoDB client is shut down before it reports the task as finished. Sometimes it still manages to report it as finished, but often the connection is closed first and it fails.
f47295f5d78d87c808846aed99a9753491125a91
6ff3c245fc0b5467d64dfb70545e256f2c330b89
https://github.com/gchq/sleeper/compare/f47295f5d78d87c808846aed99a9753491125a91...6ff3c245fc0b5467d64dfb70545e256f2c330b89
diff --git a/java/clients/src/test/java/sleeper/status/report/compactiontask/CompactionTaskStatusReportTest.java b/java/clients/src/test/java/sleeper/status/report/compactiontask/CompactionTaskStatusReportTest.java index 67e29a91c..6d0101f93 100644 --- a/java/clients/src/test/java/sleeper/status/report/compactiontask/CompactionTaskStatusReportTest.java +++ b/java/clients/src/test/java/sleeper/status/report/compactiontask/CompactionTaskStatusReportTest.java @@ -44,7 +44,7 @@ public class CompactionTaskStatusReportTest { @Test public void shouldReportCompactionTaskUnfinished() throws Exception { // Given - CompactionTaskStatus task = CompactionTaskStatus + CompactionTaskStatus task = CompactionTaskStatus.builder() .started(Instant.parse("2022-10-06T12:17:00.001Z")) .taskId("A").build(); when(store.getTasksInProgress()).thenReturn(Collections.singletonList(task)); @@ -59,10 +59,10 @@ public class CompactionTaskStatusReportTest { @Test public void shouldReportCompactionTaskUnfinishedAndFinished() throws Exception { // Given - CompactionTaskStatus unfinishedTask = CompactionTaskStatus + CompactionTaskStatus unfinishedTask = CompactionTaskStatus.builder() .started(Instant.parse("2022-10-06T12:17:00.001Z")) .taskId("unfinished-task").build(); - CompactionTaskStatus finishedTask = CompactionTaskStatus + CompactionTaskStatus finishedTask = CompactionTaskStatus.builder() .started(Instant.parse("2022-10-06T12:20:00.001Z")) .taskId("finished-task") .finished(CompactionTaskFinishedStatus.builder() @@ -98,4 +98,8 @@ public class CompactionTaskStatusReportTest { query).run(); return output.toString(); } + + private static CompactionTaskStatus.Builder startedStatusBuilder(Instant startTime) { + return CompactionTaskStatus.builder().taskId("test-task-id").started(startTime); + } } diff --git a/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatus.java b/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatus.java index a08afcbf1..9e893b5b3 100644 --- a/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatus.java +++ b/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatus.java @@ -18,7 +18,6 @@ package sleeper.compaction.task; import java.time.Instant; import java.util.Objects; -import java.util.UUID; public class CompactionTaskStatus { private final String taskId; @@ -33,16 +32,6 @@ public class CompactionTaskStatus { expiryDate = builder.expiryDate; } - public static CompactionTaskStatus.Builder started(long startTime) { - return started(Instant.ofEpochMilli(startTime)); - } - - public static CompactionTaskStatus.Builder started(Instant startTime) { - return builder().taskId(UUID.randomUUID().toString()) - .started(startTime); - } - - public static Builder builder() { return new Builder(); } diff --git a/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusInPeriodTest.java b/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusInPeriodTest.java index 1b1eb9d13..80cc81275 100644 --- a/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusInPeriodTest.java +++ b/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusInPeriodTest.java @@ -31,8 +31,8 @@ public class CompactionTaskStatusInPeriodTest { @Test public void shouldBeInPeriodWithStartTimeOnly() { // Given - CompactionTaskStatus task = CompactionTaskStatus.started( - Instant.parse("2022-10-06T11:19:00.001Z")).build(); + CompactionTaskStatus task = taskWithStartTime( + Instant.parse("2022-10-06T11:19:00.001Z")); // When / Then assertThat(task.isInPeriod(EPOCH_START, FAR_FUTURE)).isTrue(); @@ -42,7 +42,7 @@ public class CompactionTaskStatusInPeriodTest { public void shouldNotBeInPeriodWithStartTimeOnlyWhenEndIsStartTime() { // Given Instant startTime = Instant.parse("2022-10-06T11:19:00.001Z"); - CompactionTaskStatus task = CompactionTaskStatus.started(startTime).build(); + CompactionTaskStatus task = taskWithStartTime(startTime); // When / Then assertThat(task.isInPeriod(EPOCH_START, startTime)).isFalse(); @@ -52,7 +52,7 @@ public class CompactionTaskStatusInPeriodTest { public void shouldNotBeInPeriodWithStartTimeOnlyWhenStartIsStartTime() { // Given Instant startTime = Instant.parse("2022-10-06T11:19:00.001Z"); - CompactionTaskStatus task = CompactionTaskStatus.started(startTime).build(); + CompactionTaskStatus task = taskWithStartTime(startTime); // When / Then assertThat(task.isInPeriod(startTime, FAR_FUTURE)).isFalse(); @@ -113,8 +113,12 @@ public class CompactionTaskStatusInPeriodTest { assertThat(task.isInPeriod(startTime, FAR_FUTURE)).isTrue(); } + private static CompactionTaskStatus taskWithStartTime(Instant startTime) { + return taskBuilder(startTime).build(); + } + private static CompactionTaskStatus taskWithStartAndFinishTime(Instant startTime, Instant finishTime) { - return CompactionTaskStatus.started(startTime) + return taskBuilder(startTime) .finished(CompactionTaskFinishedStatus.builder() .addJobSummary(new CompactionJobSummary( new CompactionJobRecordsProcessed(200, 100), @@ -122,4 +126,8 @@ public class CompactionTaskStatusInPeriodTest { )), finishTime) .build(); } + + private static CompactionTaskStatus.Builder taskBuilder(Instant startTime) { + return CompactionTaskStatus.builder().taskId("test-task-id").started(startTime); + } } diff --git a/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusTest.java b/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusTest.java index a86c32a8f..5fae8349a 100644 --- a/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusTest.java +++ b/java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusTest.java @@ -34,7 +34,7 @@ public class CompactionTaskStatusTest { Instant taskStartedTime = Instant.parse("2022-09-22T12:00:14.000Z"); // When - CompactionTaskStatus status = CompactionTaskStatus.started(taskStartedTime.toEpochMilli()).build(); + CompactionTaskStatus status = startedStatusBuilder(taskStartedTime).build(); // Then assertThat(status).extracting("startedStatus.startTime") @@ -48,7 +48,7 @@ public class CompactionTaskStatusTest { Instant jobFinishTime3 = Instant.parse("2022-09-22T16:00:14.000Z"); // When - CompactionTaskStatus.Builder taskStatusBuilder = CompactionTaskStatus.started(taskStartedTime.toEpochMilli()); + CompactionTaskStatus.Builder taskStatusBuilder = startedStatusBuilder(taskStartedTime); CompactionTaskFinishedStatus.Builder taskFinishedBuilder = CompactionTaskFinishedStatus.builder(); createJobSummaries().forEach(taskFinishedBuilder::addJobSummary); taskStatusBuilder.finished(taskFinishedBuilder, jobFinishTime3.toEpochMilli()); @@ -67,7 +67,7 @@ public class CompactionTaskStatusTest { Instant jobFinishTime3 = Instant.parse("2022-09-22T16:00:14.000Z"); // When - CompactionTaskStatus.Builder taskStatusBuilder = CompactionTaskStatus.started(taskStartedTime.toEpochMilli()); + CompactionTaskStatus.Builder taskStatusBuilder = startedStatusBuilder(taskStartedTime); CompactionTaskFinishedStatus.Builder taskFinishedBuilder = CompactionTaskFinishedStatus.builder(); createJobSummaries().forEach(taskFinishedBuilder::addJobSummary); taskStatusBuilder.finished(taskFinishedBuilder, jobFinishTime3.toEpochMilli()); @@ -79,7 +79,11 @@ public class CompactionTaskStatusTest { .containsExactly(taskStartedTime, jobFinishTime3, 3, 14400.0, 14400L, 7200L, 1.0, 0.5); } - private List<CompactionJobSummary> createJobSummaries() { + private static CompactionTaskStatus.Builder startedStatusBuilder(Instant startTime) { + return CompactionTaskStatus.builder().taskId("test-task-id").started(startTime); + } + + private static List<CompactionJobSummary> createJobSummaries() { Instant jobStartedUpdateTime1 = Instant.parse("2022-09-22T14:00:04.000Z"); Instant jobFinishTime1 = Instant.parse("2022-09-22T14:00:14.000Z"); diff --git a/java/compaction-job-execution/src/main/java/sleeper/compaction/jobexecution/CompactSortedFilesRunner.java b/java/compaction-job-execution/src/main/java/sleeper/compaction/jobexecution/CompactSortedFilesRunner.java index d4157e81b..d66751329 100644 --- a/java/compaction-job-execution/src/main/java/sleeper/compaction/jobexecution/CompactSortedFilesRunner.java +++ b/java/compaction-job-execution/src/main/java/sleeper/compaction/jobexecution/CompactSortedFilesRunner.java @@ -52,6 +52,8 @@ import sleeper.statestore.StateStoreProvider; import sleeper.utils.HadoopConfigurationProvider; import java.io.IOException; +import java.time.Instant; +import java.util.UUID; import static sleeper.configuration.properties.SystemDefinedInstanceProperty.COMPACTION_JOB_QUEUE_URL; import static sleeper.configuration.properties.SystemDefinedInstanceProperty.SPLITTING_COMPACTION_JOB_QUEUE_URL; @@ -77,8 +79,8 @@ public class CompactSortedFilesRunner { private final TablePropertiesProvider tablePropertiesProvider; private final StateStoreProvider stateStoreProvider; private final CompactionJobStatusStore jobStatusStore; + private final CompactionTaskStatusStore taskStatusStore; private final String taskId; - private final CompactionTaskFinishedStatus.Builder taskFinishedBuilder; private final CompactionJobSerDe compactionJobSerDe; private final String sqsJobQueueUrl; private final AmazonSQS sqsClient; @@ -93,7 +95,7 @@ public class CompactSortedFilesRunner { TablePropertiesProvider tablePropertiesProvider, StateStoreProvider stateStoreProvider, CompactionJobStatusStore jobStatusStore, - CompactionTaskFinishedStatus.Builder taskFinishedBuilder, + CompactionTaskStatusStore taskStatusStore, String taskId, String sqsJobQueueUrl, AmazonSQS sqsClient, @@ -104,7 +106,7 @@ public class CompactSortedFilesRunner { this.tablePropertiesProvider = tablePropertiesProvider; this.stateStoreProvider = stateStoreProvider; this.jobStatusStore = jobStatusStore; - this.taskFinishedBuilder = taskFinishedBuilder; + this.taskStatusStore = taskStatusStore; this.taskId = taskId; this.compactionJobSerDe = new CompactionJobSerDe(tablePropertiesProvider); this.sqsJobQueueUrl = sqsJobQueueUrl; @@ -121,14 +123,21 @@ public class CompactSortedFilesRunner { TablePropertiesProvider tablePropertiesProvider, StateStoreProvider stateStoreProvider, CompactionJobStatusStore jobStatusStore, - CompactionTaskFinishedStatus.Builder taskFinishedBuilder, + CompactionTaskStatusStore taskStatusStore, String taskId, String sqsJobQueueUrl, AmazonSQS sqsClient) { - this(instanceProperties, objectFactory, tablePropertiesProvider, stateStoreProvider, jobStatusStore, taskFinishedBuilder, taskId, sqsJobQueueUrl, sqsClient, 3, 20); + this(instanceProperties, objectFactory, tablePropertiesProvider, stateStoreProvider, jobStatusStore, taskStatusStore, taskId, sqsJobQueueUrl, sqsClient, 3, 20); } public void run() throws InterruptedException, IOException, ActionException { + + Instant startTime = Instant.now(); + CompactionTaskStatus.Builder taskStatusBuilder = CompactionTaskStatus + .builder().taskId(taskId).started(startTime); + LOGGER.info("Starting task {}", taskId); + taskStatusStore.taskStarted(taskStatusBuilder.build()); + CompactionTaskFinishedStatus.Builder taskFinishedBuilder = CompactionTaskFinishedStatus.builder(); long totalNumberOfMessagesProcessed = 0L; int numConsecutiveTimesNoMessages = 0; while (numConsecutiveTimesNoMessages < maxMessageRetrieveAttempts) { @@ -157,7 +166,14 @@ public class CompactSortedFilesRunner { } LOGGER.info("Returning from run() method in CompactSortedFilesRunner as no messages received in {} seconds", (numConsecutiveTimesNoMessages * 30)); - LOGGER.info("Total number of messages processed = " + totalNumberOfMessagesProcessed); + LOGGER.info("Total number of messages processed = {}", totalNumberOfMessagesProcessed); + + Instant finishTime = Instant.now(); + double runTimeInSeconds = (finishTime.toEpochMilli() - startTime.toEpochMilli()) / 1000.0; + LOGGER.info("CompactSortedFilesRunner total run time = {}", runTimeInSeconds); + + CompactionTaskStatus taskFinished = taskStatusBuilder.finished(taskFinishedBuilder, finishTime).build(); + taskStatusStore.taskFinished(taskFinished); } private CompactionJobSummary compact(CompactionJob compactionJob, Message message) throws IOException, IteratorException, ActionException { @@ -198,7 +214,6 @@ public class CompactSortedFilesRunner { System.exit(1); } - long startTime = System.currentTimeMillis(); AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.defaultClient(); AmazonSQS sqsClient = AmazonSQSClientBuilder.defaultClient(); AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); @@ -211,10 +226,6 @@ public class CompactSortedFilesRunner { StateStoreProvider stateStoreProvider = new StateStoreProvider(dynamoDBClient, instanceProperties, HadoopConfigurationProvider.getConfigurationForECS(instanceProperties)); CompactionJobStatusStore jobStatusStore = DynamoDBCompactionJobStatusStore.from(dynamoDBClient, instanceProperties); CompactionTaskStatusStore taskStatusStore = DynamoDBCompactionTaskStatusStore.from(dynamoDBClient, instanceProperties); - CompactionTaskFinishedStatus.Builder taskFinishedBuilder = CompactionTaskFinishedStatus.builder(); - - CompactionTaskStatus.Builder taskStatusBuilder = CompactionTaskStatus.started(startTime); - taskStatusStore.taskStarted(taskStatusBuilder.build()); String sqsJobQueueUrl; String type = args[1]; @@ -232,8 +243,8 @@ public class CompactSortedFilesRunner { tablePropertiesProvider, stateStoreProvider, jobStatusStore, - taskFinishedBuilder, - taskStatusBuilder.getTaskId(), + taskStatusStore, + UUID.randomUUID().toString(), sqsJobQueueUrl, sqsClient); runner.run(); @@ -244,11 +255,5 @@ public class CompactSortedFilesRunner { LOGGER.info("Shut down dynamoDBClient"); s3Client.shutdown(); LOGGER.info("Shut down s3Client"); - long finishTime = System.currentTimeMillis(); - double runTimeInSeconds = (finishTime - startTime) / 1000.0; - LOGGER.info("CompactSortedFilesRunner total run time = " + runTimeInSeconds); - - CompactionTaskStatus taskFinished = taskStatusBuilder.finished(taskFinishedBuilder, finishTime).build(); - taskStatusStore.taskFinished(taskFinished); } } diff --git a/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/CompactSortedFilesRunnerIT.java b/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/CompactSortedFilesRunnerIT.java index efedc916c..65af6db17 100644 --- a/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/CompactSortedFilesRunnerIT.java +++ b/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/CompactSortedFilesRunnerIT.java @@ -36,7 +36,9 @@ import sleeper.compaction.job.CompactionJobSerDe; import sleeper.compaction.job.CompactionJobStatusStore; import sleeper.compaction.status.job.DynamoDBCompactionJobStatusStore; import sleeper.compaction.status.job.DynamoDBCompactionJobStatusStoreCreator; -import sleeper.compaction.task.CompactionTaskFinishedStatus; +import sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStore; +import sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStoreCreator; +import sleeper.compaction.task.CompactionTaskStatusStore; import sleeper.configuration.jars.ObjectFactory; import sleeper.configuration.jars.ObjectFactoryException; import sleeper.configuration.properties.InstanceProperties; @@ -156,6 +158,8 @@ public class CompactSortedFilesRunnerIT { stateStore.initialise(); DynamoDBCompactionJobStatusStoreCreator.create(instanceProperties, dynamoDB); CompactionJobStatusStore jobStatusStore = DynamoDBCompactionJobStatusStore.from(dynamoDB, instanceProperties); + DynamoDBCompactionTaskStatusStoreCreator.create(instanceProperties, dynamoDB); + CompactionTaskStatusStore taskStatusStore = DynamoDBCompactionTaskStatusStore.from(dynamoDB, instanceProperties); // - Create four files of sorted data String folderName = folder.newFolder().getAbsolutePath(); String file1 = folderName + "/file1.parquet"; @@ -268,7 +272,7 @@ public class CompactSortedFilesRunnerIT { // When CompactSortedFilesRunner runner = new CompactSortedFilesRunner( instanceProperties, ObjectFactory.noUserJars(), - tablePropertiesProvider, stateStoreProvider, jobStatusStore, CompactionTaskFinishedStatus.builder(), + tablePropertiesProvider, stateStoreProvider, jobStatusStore, taskStatusStore, "task-id", instanceProperties.get(COMPACTION_JOB_QUEUE_URL), sqsClient, 1, 5); runner.run(); diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksByPeriodIT.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksByPeriodIT.java index aa3fc9bbf..ddd8cc093 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksByPeriodIT.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksByPeriodIT.java @@ -24,6 +24,7 @@ import sleeper.compaction.task.CompactionTaskStatus; import java.time.Instant; import java.time.Period; +import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -90,7 +91,7 @@ public class QueryCompactionTasksByPeriodIT extends DynamoDBCompactionTaskStatus } private CompactionTaskStatus taskWithStartAndFinishTime(Instant startTime, Instant finishTime) { - return CompactionTaskStatus.started(startTime) + return CompactionTaskStatus.builder().taskId(UUID.randomUUID().toString()).started(startTime) .finished(CompactionTaskFinishedStatus.builder() .addJobSummary(new CompactionJobSummary( new CompactionJobRecordsProcessed(200, 100), diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksInProgressIT.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksInProgressIT.java index b01aa5fd1..1ec4417b2 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksInProgressIT.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksInProgressIT.java @@ -55,10 +55,10 @@ public class QueryCompactionTasksInProgressIT extends DynamoDBCompactionTaskStat @Test public void shouldSortByStartTimeMostRecentFirst() { // Given - CompactionTaskStatus task1 = CompactionTaskStatus.started( - Instant.parse("2022-10-06T11:19:00.001Z")).build(); - CompactionTaskStatus task2 = CompactionTaskStatus.started( - Instant.parse("2022-10-06T11:19:10.001Z")).build(); + CompactionTaskStatus task1 = startedTaskWithDefaultsBuilder() + .started(Instant.parse("2022-10-06T11:19:00.001Z")).build(); + CompactionTaskStatus task2 = startedTaskWithDefaultsBuilder() + .started(Instant.parse("2022-10-06T11:19:10.001Z")).build(); // When store.taskStarted(task1); diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java index bad25e1fb..3d3cf710f 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java @@ -28,6 +28,7 @@ import sleeper.compaction.task.CompactionTaskStatusStore; import sleeper.configuration.properties.InstanceProperties; import java.time.Instant; +import java.util.UUID; import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStore.taskStatusTableName; import static sleeper.compaction.status.testutils.CompactionStatusStoreTestUtils.createInstanceProperties; @@ -64,7 +65,7 @@ public class DynamoDBCompactionTaskStatusStoreTestBase extends DynamoDBTestBase } protected static CompactionTaskStatus.Builder startedTaskWithDefaultsBuilder() { - return CompactionTaskStatus.started(defaultStartTime().toEpochMilli()); + return CompactionTaskStatus.builder().taskId(UUID.randomUUID().toString()).started(defaultStartTime()); } protected static CompactionTaskStatus finishedTaskWithDefaults() {
['java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java', 'java/clients/src/test/java/sleeper/status/report/compactiontask/CompactionTaskStatusReportTest.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksInProgressIT.java', 'java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatus.java', 'java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/CompactSortedFilesRunnerIT.java', 'java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusTest.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/task/QueryCompactionTasksByPeriodIT.java', 'java/compaction-core/src/test/java/sleeper/compaction/task/CompactionTaskStatusInPeriodTest.java', 'java/compaction-job-execution/src/main/java/sleeper/compaction/jobexecution/CompactSortedFilesRunner.java']
{'.java': 9}
9
9
0
0
9
1,784,842
348,549
41,985
340
3,130
583
54
2
213
37
43
1
0
0
"1970-01-01T00:27:45"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,695
gchq/sleeper/273/271
gchq
sleeper
https://github.com/gchq/sleeper/issues/271
https://github.com/gchq/sleeper/pull/273
https://github.com/gchq/sleeper/pull/273
1
resolves
Exception generated when querying finished Compaction Task
``` Exception in thread "main" java.lang.NumberFormatException: For input string: "1416.976" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:589) at java.lang.Long.parseLong(Long.java:631) at sleeper.compaction.status.DynamoDBAttributes.getLongAttribute(DynamoDBAttributes.java:75) at sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.addStatusUpdate(DynamoDBCompactionTaskStatusFormat.java:106) at sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.lambda$streamTaskStatuses$0(DynamoDBCompactionTaskStatusFormat.java:90) at java.util.ArrayList.forEach(ArrayList.java:1259) at sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.streamTaskStatuses(DynamoDBCompactionTaskStatusFormat.java:90) at sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStore.getTasksInProgress(DynamoDBCompactionTaskStatusStore.java:105) at sleeper.status.report.CompactionTaskStatusReport.run(CompactionTaskStatusReport.java:51) at sleeper.status.report.StatusReport.run(StatusReport.java:99) at sleeper.status.report.StatusReport.main(StatusReport.java:130) ``` Looks like duration for jobs is stored as double but retrieved as a long in DynamoDBCompactionTaskStatusFormat.
ca76f5c100e5e4bbe39dccfc48a13a47fe48a49f
f4ec70601cc7b4e3fbee67b978c4d262f7f911db
https://github.com/gchq/sleeper/compare/ca76f5c100e5e4bbe39dccfc48a13a47fe48a49f...f4ec70601cc7b4e3fbee67b978c4d262f7f911db
diff --git a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusFormat.java b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusFormat.java index 955bec6b8..1c4ab4fea 100644 --- a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusFormat.java +++ b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusFormat.java @@ -100,7 +100,7 @@ public class DynamoDBCompactionTaskStatusFormat { case FINISHED: builder.taskFinished(taskId, CompactionTaskFinishedStatus.builder() .finishTime(getInstantAttribute(item, FINISH_TIME)) - .totalRuntimeInSeconds(getLongAttribute(item, DURATION, 0)) + .totalRuntimeInSeconds(Double.parseDouble(getNumberAttribute(item, DURATION))) .totalJobs(getIntAttribute(item, NUMBER_OF_JOBS, 0)) .totalRecordsRead(getLongAttribute(item, LINES_READ, 0)) .totalRecordsWritten(getLongAttribute(item, LINES_WRITTEN, 0)) diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/StoreCompactionTaskIT.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/StoreCompactionTaskIT.java index b0066da2b..457ffcfad 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/StoreCompactionTaskIT.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/StoreCompactionTaskIT.java @@ -52,6 +52,22 @@ public class StoreCompactionTaskIT extends DynamoDBCompactionTaskStatusStoreTest .isEqualTo(taskStatus); } + @Test + public void shouldReportCompactionTaskFinishedWithDurationInSecondsNotAWholeNumber() { + // Given + CompactionTaskStatus taskStatus = finishedTaskWithDefaultsAndDurationInSecondsNotAWholeNumber(); + + // When + store.taskStarted(taskStatus); + store.taskFinished(taskStatus); + + // Then + assertThat(store.getTask(taskStatus.getTaskId())) + .usingRecursiveComparison(IGNORE_EXPIRY_DATE) + .isEqualTo(taskStatus); + + } + @Test public void shouldReportNoCompactionTaskExistsInStore() { // Given diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java index cb4b6035d..fa3b1742b 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java @@ -52,35 +52,52 @@ public class DynamoDBCompactionTaskStatusStoreTestBase extends DynamoDBTestBase dynamoDBClient.deleteTable(taskStatusTableName); } - protected static Instant defaultStartTime() { + private static Instant defaultJobStartTime() { + return Instant.parse("2022-09-22T14:00:04.000Z"); + } + + private static Instant defaultJobFinishTime() { + return Instant.parse("2022-09-22T14:00:14.000Z"); + } + + private static Instant defaultTaskStartTime() { return Instant.parse("2022-09-22T12:30:00.000Z"); } - protected static Instant defaultFinishTime() { + private static Instant defaultTaskFinishTime() { return Instant.parse("2022-09-22T16:30:00.000Z"); } + private static Instant taskFinishTimeWithDurationInSecondsNotAWholeNumber() { + return Instant.parse("2022-09-22T16:30:00.500Z"); + } + + private static CompactionJobSummary defaultJobSummary() { + return new CompactionJobSummary( + new CompactionJobRecordsProcessed(4800L, 2400L), + defaultJobStartTime(), defaultJobFinishTime()); + } + protected static CompactionTaskStatus startedTaskWithDefaults() { return startedTaskWithDefaultsBuilder().build(); } protected static CompactionTaskStatus.Builder startedTaskWithDefaultsBuilder() { - return CompactionTaskStatus.builder().taskId(UUID.randomUUID().toString()).started(defaultStartTime()); + return CompactionTaskStatus.builder().taskId(UUID.randomUUID().toString()).started(defaultTaskStartTime()); } protected static CompactionTaskStatus finishedTaskWithDefaults() { return startedTaskWithDefaultsBuilder().finished( CompactionTaskFinishedStatus.builder() .addJobSummary(defaultJobSummary()), - defaultFinishTime().toEpochMilli()).build(); + defaultTaskFinishTime().toEpochMilli()).build(); } - private static CompactionJobSummary defaultJobSummary() { - Instant jobStartedUpdateTime = Instant.parse("2022-09-22T14:00:04.000Z"); - Instant jobFinishTime = Instant.parse("2022-09-22T14:00:14.000Z"); - return new CompactionJobSummary( - new CompactionJobRecordsProcessed(4800L, 2400L), - jobStartedUpdateTime, jobFinishTime); + protected static CompactionTaskStatus finishedTaskWithDefaultsAndDurationInSecondsNotAWholeNumber() { + return startedTaskWithDefaultsBuilder().finished( + CompactionTaskFinishedStatus.builder() + .addJobSummary(defaultJobSummary()), + taskFinishTimeWithDurationInSecondsNotAWholeNumber().toEpochMilli()).build(); } protected static CompactionTaskStatus taskWithStartTime(Instant startTime) {
['java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusFormat.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/testutils/DynamoDBCompactionTaskStatusStoreTestBase.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/task/StoreCompactionTaskIT.java']
{'.java': 3}
3
3
0
0
3
1,794,748
350,443
42,260
343
204
31
2
1
1,303
51
280
16
0
1
"1970-01-01T00:27:45"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,694
gchq/sleeper/276/275
gchq
sleeper
https://github.com/gchq/sleeper/issues/275
https://github.com/gchq/sleeper/pull/276
https://github.com/gchq/sleeper/pull/276
1
resolves
Compaction Job status reports use local timezone in range query
When using the Compaction Job status reporter, entered ranges use the local timezone, whereas dates and times are stored in UTC in the database, leading to incorrect query results. Converting range input to UTC will prevent this.
0f6223f532b84f38c3c4491fda86603f9259a660
dcd81b27e2bddd242b632915e67b845b98301fb5
https://github.com/gchq/sleeper/compare/0f6223f532b84f38c3c4491fda86603f9259a660...dcd81b27e2bddd242b632915e67b845b98301fb5
diff --git a/java/clients/src/main/java/sleeper/status/report/CompactionJobStatusReport.java b/java/clients/src/main/java/sleeper/status/report/CompactionJobStatusReport.java index d6575f447..98df75c7b 100644 --- a/java/clients/src/main/java/sleeper/status/report/CompactionJobStatusReport.java +++ b/java/clients/src/main/java/sleeper/status/report/CompactionJobStatusReport.java @@ -40,15 +40,30 @@ import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Scanner; +import java.util.TimeZone; public class CompactionJobStatusReport { private final CompactionJobStatusReportArguments arguments; private final CompactionJobStatusReporter compactionJobStatusReporter; private final CompactionJobStatusCollector compactionJobStatusCollector; - private final SimpleDateFormat dateInputFormat = new SimpleDateFormat("yyyyMMddhhmmss"); + private static final String DATE_FORMAT = "yyyyMMddhhmmss"; private static final Instant DEFAULT_RANGE_START = Instant.now().minus(4L, ChronoUnit.HOURS); private static final Instant DEFAULT_RANGE_END = Instant.now(); + private static SimpleDateFormat createDateInputFormat() { + SimpleDateFormat dateInputFormat = new SimpleDateFormat(DATE_FORMAT); + dateInputFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateInputFormat; + } + + public static Instant parseDate(String input) throws ParseException { + return createDateInputFormat().parse(input).toInstant(); + } + + public static String formatDate(Instant input) { + return createDateInputFormat().format(Date.from(input)); + } + public CompactionJobStatusReport( CompactionJobStatusStore compactionJobStatusStore, CompactionJobStatusReportArguments arguments) { @@ -73,10 +88,8 @@ public class CompactionJobStatusReport { Instant startRange; Instant endRange; try { - Date startRangeDate = dateInputFormat.parse(arguments.getQueryParameters().split(",")[0]); - startRange = startRangeDate.toInstant(); - Date endRangeDate = dateInputFormat.parse(arguments.getQueryParameters().split(",")[1]); - endRange = endRangeDate.toInstant(); + startRange = parseDate(arguments.getQueryParameters().split(",")[0]); + endRange = parseDate(arguments.getQueryParameters().split(",")[1]); } catch (ParseException e) { System.out.println("Error while parsing input string, using system defaults (past 4 hours)"); startRange = DEFAULT_RANGE_START; @@ -145,16 +158,15 @@ public class CompactionJobStatusReport { while (true) { System.out.printf("Enter %s range in format %s (default is %s):", rangeName, - dateInputFormat.toPattern(), - dateInputFormat.format(Date.from(defaultRange))); + DATE_FORMAT, + formatDate(defaultRange)); String time = scanner.nextLine(); if ("".equals(time)) { - System.out.printf("Using default %s range %s%n", rangeName, dateInputFormat.format(Date.from(defaultRange))); + System.out.printf("Using default %s range %s%n", rangeName, formatDate(defaultRange)); break; } try { - Date date = dateInputFormat.parse(time); - return date.toInstant(); + return parseDate(time); } catch (ParseException e) { System.out.println("Error while parsing input string"); } diff --git a/java/clients/src/test/java/sleeper/status/report/compactionjob/StatusReporterRangeQueryTest.java b/java/clients/src/test/java/sleeper/status/report/compactionjob/StatusReporterRangeQueryTest.java index 5a36638de..aa48aaa68 100644 --- a/java/clients/src/test/java/sleeper/status/report/compactionjob/StatusReporterRangeQueryTest.java +++ b/java/clients/src/test/java/sleeper/status/report/compactionjob/StatusReporterRangeQueryTest.java @@ -18,9 +18,13 @@ package sleeper.status.report.compactionjob; import org.junit.Test; import sleeper.compaction.job.status.CompactionJobStatus; +import sleeper.status.report.CompactionJobStatusReport; +import java.text.SimpleDateFormat; +import java.time.Instant; import java.util.Collections; import java.util.List; +import java.util.TimeZone; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; import static org.assertj.core.api.Assertions.assertThat; @@ -52,4 +56,23 @@ public class StatusReporterRangeQueryTest extends StatusReporterTestBase { .isEqualTo(example("reports/compactionjobstatus/json/noJobs.json")); } + @Test + public void shouldConvertInputRangeToUTC() throws Exception { + // Given + Instant dateUTC = Instant.parse("2022-09-20T10:00:00.000Z"); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); + dateFormat.setTimeZone(TimeZone.getTimeZone("PST")); + String inputPST = "20220920100000"; + Instant datePST = dateFormat.parse(inputPST).toInstant(); + + // When + Instant parsedDatePST = CompactionJobStatusReport.parseDate(inputPST); + + // Then + assertThat(parsedDatePST) + .isEqualTo(dateUTC); + assertThat(parsedDatePST) + .isNotEqualTo(datePST); + } }
['java/clients/src/main/java/sleeper/status/report/CompactionJobStatusReport.java', 'java/clients/src/test/java/sleeper/status/report/compactionjob/StatusReporterRangeQueryTest.java']
{'.java': 2}
2
2
0
0
2
1,794,767
350,442
42,260
343
1,813
314
32
1
229
37
44
1
0
0
"1970-01-01T00:27:45"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,693
gchq/sleeper/424/423
gchq
sleeper
https://github.com/gchq/sleeper/issues/423
https://github.com/gchq/sleeper/pull/424
https://github.com/gchq/sleeper/pull/424
1
resolves
If sleeper.compaction.status.store.enabled is set to false, compaction crashes on reporting task status
When the status store is disabled, no DynamoDB table is created for compaction tasks, but the status store DynamoDB implementation is still used. This means all compaction tasks will crash at startup as they try to report that they've started.
c2ff0a495483df525df4ef1466ab9746341aeefb
69cdeac188481fc72e878308d014a2bff1b8d4c3
https://github.com/gchq/sleeper/compare/c2ff0a495483df525df4ef1466ab9746341aeefb...69cdeac188481fc72e878308d014a2bff1b8d4c3
diff --git a/java/cdk/src/main/java/sleeper/cdk/Utils.java b/java/cdk/src/main/java/sleeper/cdk/Utils.java index 371c11092..c752ef7f5 100644 --- a/java/cdk/src/main/java/sleeper/cdk/Utils.java +++ b/java/cdk/src/main/java/sleeper/cdk/Utils.java @@ -193,7 +193,7 @@ public class Utils { } public static RemovalPolicy removalPolicy(InstanceProperties properties) { - if (Boolean.TRUE.equals(properties.getBoolean(RETAIN_INFRA_AFTER_DESTROY))) { + if (properties.getBoolean(RETAIN_INFRA_AFTER_DESTROY)) { return RemovalPolicy.RETAIN; } else { return RemovalPolicy.DESTROY; diff --git a/java/compaction-core/src/main/java/sleeper/compaction/job/CompactionJobStatusStore.java b/java/compaction-core/src/main/java/sleeper/compaction/job/CompactionJobStatusStore.java index 9700df1ff..9725418bf 100644 --- a/java/compaction-core/src/main/java/sleeper/compaction/job/CompactionJobStatusStore.java +++ b/java/compaction-core/src/main/java/sleeper/compaction/job/CompactionJobStatusStore.java @@ -23,10 +23,8 @@ import java.util.Optional; public interface CompactionJobStatusStore { - static CompactionJobStatusStore none() { - return new CompactionJobStatusStore() { - }; - } + CompactionJobStatusStore NONE = new CompactionJobStatusStore() { + }; default void jobCreated(CompactionJob job) { } diff --git a/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatusStore.java b/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatusStore.java index bdff9452e..267e17577 100644 --- a/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatusStore.java +++ b/java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatusStore.java @@ -16,17 +16,13 @@ package sleeper.compaction.task; -import sleeper.compaction.job.CompactionJobStatusStore; - import java.time.Instant; import java.util.List; public interface CompactionTaskStatusStore { - static CompactionJobStatusStore none() { - return new CompactionJobStatusStore() { - }; - } + CompactionTaskStatusStore NONE = new CompactionTaskStatusStore() { + }; default void taskStarted(CompactionTaskStatus taskStatus) { } diff --git a/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/testutils/CompactSortedFilesTestUtils.java b/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/testutils/CompactSortedFilesTestUtils.java index a8b9cc208..e28f725af 100644 --- a/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/testutils/CompactSortedFilesTestUtils.java +++ b/java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/testutils/CompactSortedFilesTestUtils.java @@ -93,7 +93,7 @@ public class CompactSortedFilesTestUtils { public static CompactSortedFiles createCompactSortedFiles( Schema schema, CompactionJob compactionJob, StateStore stateStore, String taskId) { - return createCompactSortedFiles(schema, compactionJob, stateStore, CompactionJobStatusStore.none(), taskId); + return createCompactSortedFiles(schema, compactionJob, stateStore, CompactionJobStatusStore.NONE, taskId); } public static CompactSortedFiles createCompactSortedFiles( diff --git a/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStore.java b/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStore.java index dd4560434..4e3b0bc2a 100644 --- a/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStore.java +++ b/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStore.java @@ -64,10 +64,10 @@ public class DynamoDBCompactionJobStatusStore implements CompactionJobStatusStor } public static CompactionJobStatusStore from(AmazonDynamoDB dynamoDB, InstanceProperties properties) { - if (Boolean.TRUE.equals(properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED))) { + if (properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { return new DynamoDBCompactionJobStatusStore(dynamoDB, properties); } else { - return CompactionJobStatusStore.none(); + return CompactionJobStatusStore.NONE; } } diff --git a/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreator.java b/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreator.java index 082d84355..2607e5510 100644 --- a/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreator.java +++ b/java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreator.java @@ -28,6 +28,7 @@ import static sleeper.compaction.status.job.DynamoDBCompactionJobStatusFormat.EX import static sleeper.compaction.status.job.DynamoDBCompactionJobStatusFormat.JOB_ID; import static sleeper.compaction.status.job.DynamoDBCompactionJobStatusFormat.UPDATE_TIME; import static sleeper.compaction.status.job.DynamoDBCompactionJobStatusStore.jobStatusTableName; +import static sleeper.configuration.properties.UserDefinedInstanceProperty.COMPACTION_STATUS_STORE_ENABLED; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; import static sleeper.dynamodb.tools.DynamoDBUtils.configureTimeToLive; import static sleeper.dynamodb.tools.DynamoDBUtils.initialiseTable; @@ -38,6 +39,9 @@ public class DynamoDBCompactionJobStatusStoreCreator { } public static void create(InstanceProperties properties, AmazonDynamoDB dynamoDB) { + if (!properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { + return; + } String tableName = jobStatusTableName(properties.get(ID)); initialiseTable(dynamoDB, tableName, Arrays.asList( @@ -48,4 +52,11 @@ public class DynamoDBCompactionJobStatusStoreCreator { new KeySchemaElement(UPDATE_TIME, KeyType.RANGE))); configureTimeToLive(dynamoDB, tableName, EXPIRY_DATE); } + + public static void tearDown(InstanceProperties properties, AmazonDynamoDB dynamoDBClient) { + if (!properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { + return; + } + dynamoDBClient.deleteTable(jobStatusTableName(properties.get(ID))); + } } diff --git a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStore.java b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStore.java index 7b8e8f79c..1d0a51327 100644 --- a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStore.java +++ b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStore.java @@ -40,6 +40,7 @@ import java.util.Map; import java.util.stream.Collectors; import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.TASK_ID; +import static sleeper.configuration.properties.UserDefinedInstanceProperty.COMPACTION_STATUS_STORE_ENABLED; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; import static sleeper.dynamodb.tools.DynamoDBAttributes.createStringAttribute; import static sleeper.dynamodb.tools.DynamoDBUtils.instanceTableName; @@ -120,8 +121,12 @@ public class DynamoDBCompactionTaskStatusStore implements CompactionTaskStatusSt return dynamoDB.putItem(putItemRequest); } - public static DynamoDBCompactionTaskStatusStore from(AmazonDynamoDB dynamoDB, InstanceProperties properties) { - return new DynamoDBCompactionTaskStatusStore(dynamoDB, properties); + public static CompactionTaskStatusStore from(AmazonDynamoDB dynamoDB, InstanceProperties properties) { + if (properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { + return new DynamoDBCompactionTaskStatusStore(dynamoDB, properties); + } else { + return CompactionTaskStatusStore.NONE; + } } public static String taskStatusTableName(String instanceId) { diff --git a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreator.java b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreator.java index e78edec5f..844e8f154 100644 --- a/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreator.java +++ b/java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreator.java @@ -28,6 +28,7 @@ import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat. import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.TASK_ID; import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusFormat.UPDATE_TIME; import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStore.taskStatusTableName; +import static sleeper.configuration.properties.UserDefinedInstanceProperty.COMPACTION_STATUS_STORE_ENABLED; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; import static sleeper.dynamodb.tools.DynamoDBUtils.configureTimeToLive; import static sleeper.dynamodb.tools.DynamoDBUtils.initialiseTable; @@ -38,6 +39,9 @@ public class DynamoDBCompactionTaskStatusStoreCreator { } public static void create(InstanceProperties properties, AmazonDynamoDB dynamoDB) { + if (!properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { + return; + } String tableName = taskStatusTableName(properties.get(ID)); initialiseTable(dynamoDB, tableName, Arrays.asList( @@ -48,4 +52,11 @@ public class DynamoDBCompactionTaskStatusStoreCreator { new KeySchemaElement(UPDATE_TIME, KeyType.RANGE))); configureTimeToLive(dynamoDB, tableName, EXPIRY_DATE); } + + public static void tearDown(InstanceProperties properties, AmazonDynamoDB dynamoDBClient) { + if (!properties.getBoolean(COMPACTION_STATUS_STORE_ENABLED)) { + return; + } + dynamoDBClient.deleteTable(taskStatusTableName(properties.get(ID))); + } } diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreatorIT.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreatorIT.java index 13003b38c..2bc06d252 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreatorIT.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreatorIT.java @@ -16,14 +16,18 @@ package sleeper.compaction.status.job; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; +import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import org.junit.After; import org.junit.Test; +import sleeper.compaction.job.CompactionJobStatusStore; import sleeper.configuration.properties.InstanceProperties; import sleeper.dynamodb.tools.DynamoDBTestBase; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static sleeper.compaction.status.job.DynamoDBCompactionJobStatusStore.jobStatusTableName; import static sleeper.compaction.status.testutils.CompactionStatusStoreTestUtils.createInstanceProperties; +import static sleeper.configuration.properties.UserDefinedInstanceProperty.COMPACTION_STATUS_STORE_ENABLED; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; public class DynamoDBCompactionJobStatusStoreCreatorIT extends DynamoDBTestBase { @@ -35,14 +39,34 @@ public class DynamoDBCompactionJobStatusStoreCreatorIT extends DynamoDBTestBase public void shouldCreateStore() { // When DynamoDBCompactionJobStatusStoreCreator.create(instanceProperties, dynamoDBClient); + CompactionJobStatusStore store = DynamoDBCompactionJobStatusStore.from(dynamoDBClient, instanceProperties); // Then assertThat(dynamoDBClient.describeTable(tableName)) .extracting(DescribeTableResult::getTable).isNotNull(); + assertThat(store).isInstanceOf(DynamoDBCompactionJobStatusStore.class); + } + + @Test + public void shouldNotCreateStoreIfDisabled() { + // Given + instanceProperties.set(COMPACTION_STATUS_STORE_ENABLED, "false"); + + // When + DynamoDBCompactionJobStatusStoreCreator.create(instanceProperties, dynamoDBClient); + CompactionJobStatusStore store = DynamoDBCompactionJobStatusStore.from(dynamoDBClient, instanceProperties); + + // Then + assertThatThrownBy(() -> dynamoDBClient.describeTable(tableName)) + .isInstanceOf(ResourceNotFoundException.class); + assertThat(store).isSameAs(CompactionJobStatusStore.NONE); + assertThatThrownBy(() -> store.getAllJobs("some-table")).isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> store.getUnfinishedJobs("some-table")).isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> store.getJob("some-job")).isInstanceOf(UnsupportedOperationException.class); } @After public void tearDown() { - dynamoDBClient.deleteTable(tableName); + DynamoDBCompactionJobStatusStoreCreator.tearDown(instanceProperties, dynamoDBClient); } } diff --git a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreatorIT.java b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreatorIT.java index c564fb02b..f7a901898 100644 --- a/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreatorIT.java +++ b/java/compaction-status-store/src/test/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreatorIT.java @@ -16,14 +16,18 @@ package sleeper.compaction.status.task; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; +import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import org.junit.After; import org.junit.Test; +import sleeper.compaction.task.CompactionTaskStatusStore; import sleeper.configuration.properties.InstanceProperties; import sleeper.dynamodb.tools.DynamoDBTestBase; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static sleeper.compaction.status.task.DynamoDBCompactionTaskStatusStore.taskStatusTableName; import static sleeper.compaction.status.testutils.CompactionStatusStoreTestUtils.createInstanceProperties; +import static sleeper.configuration.properties.UserDefinedInstanceProperty.COMPACTION_STATUS_STORE_ENABLED; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; public class DynamoDBCompactionTaskStatusStoreCreatorIT extends DynamoDBTestBase { @@ -35,14 +39,34 @@ public class DynamoDBCompactionTaskStatusStoreCreatorIT extends DynamoDBTestBase public void shouldCreateStore() { // When DynamoDBCompactionTaskStatusStoreCreator.create(instanceProperties, dynamoDBClient); + CompactionTaskStatusStore store = DynamoDBCompactionTaskStatusStore.from(dynamoDBClient, instanceProperties); // Then assertThat(dynamoDBClient.describeTable(tableName)) .extracting(DescribeTableResult::getTable).isNotNull(); + assertThat(store).isInstanceOf(DynamoDBCompactionTaskStatusStore.class); + } + + @Test + public void shouldNotCreateStoreIfDisabled() { + // Given + instanceProperties.set(COMPACTION_STATUS_STORE_ENABLED, "false"); + + // When + DynamoDBCompactionTaskStatusStoreCreator.create(instanceProperties, dynamoDBClient); + CompactionTaskStatusStore store = DynamoDBCompactionTaskStatusStore.from(dynamoDBClient, instanceProperties); + + // Then + assertThatThrownBy(() -> dynamoDBClient.describeTable(tableName)) + .isInstanceOf(ResourceNotFoundException.class); + assertThat(store).isSameAs(CompactionTaskStatusStore.NONE); + assertThatThrownBy(store::getAllTasks).isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(store::getTasksInProgress).isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> store.getTask("some-task")).isInstanceOf(UnsupportedOperationException.class); } @After public void tearDown() { - dynamoDBClient.deleteTable(tableName); + DynamoDBCompactionTaskStatusStoreCreator.tearDown(instanceProperties, dynamoDBClient); } } diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java b/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java index 60aa6cad7..933e6080a 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java @@ -65,7 +65,7 @@ public abstract class SleeperProperties<T extends SleeperProperty> { return properties.getProperty(property.getPropertyName(), property.getDefaultValue()); } - public Boolean getBoolean(T property) { + public boolean getBoolean(T property) { return Boolean.parseBoolean(get(property)); } diff --git a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/job/status/DynamoDBIngestJobStatusStore.java b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/job/status/DynamoDBIngestJobStatusStore.java index 72cdb33fa..79b35dc4d 100644 --- a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/job/status/DynamoDBIngestJobStatusStore.java +++ b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/job/status/DynamoDBIngestJobStatusStore.java @@ -37,7 +37,7 @@ public class DynamoDBIngestJobStatusStore implements IngestJobStatusStore { } public static IngestJobStatusStore from(AmazonDynamoDB dynamoDB, InstanceProperties properties) { - if (Boolean.TRUE.equals(properties.getBoolean(INGEST_STATUS_STORE_ENABLED))) { + if (properties.getBoolean(INGEST_STATUS_STORE_ENABLED)) { return new DynamoDBIngestJobStatusStore(dynamoDB, properties); } else { return IngestJobStatusStore.none();
['java/cdk/src/main/java/sleeper/cdk/Utils.java', 'java/compaction-core/src/main/java/sleeper/compaction/task/CompactionTaskStatusStore.java', 'java/compaction-core/src/main/java/sleeper/compaction/job/CompactionJobStatusStore.java', 'java/ingest/ingest-status-store/src/main/java/sleeper/ingest/job/status/DynamoDBIngestJobStatusStore.java', 'java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStore.java', 'java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreator.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStoreCreatorIT.java', 'java/compaction-job-execution/src/test/java/sleeper/compaction/jobexecution/testutils/CompactSortedFilesTestUtils.java', 'java/compaction-status-store/src/test/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreatorIT.java', 'java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java', 'java/compaction-status-store/src/main/java/sleeper/compaction/status/task/DynamoDBCompactionTaskStatusStore.java', 'java/compaction-status-store/src/main/java/sleeper/compaction/status/job/DynamoDBCompactionJobStatusStoreCreator.java']
{'.java': 12}
12
12
0
0
12
1,930,537
378,633
46,399
400
2,745
522
55
9
243
40
49
1
0
0
"1970-01-01T00:27:49"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,691
gchq/sleeper/618/611
gchq
sleeper
https://github.com/gchq/sleeper/issues/611
https://github.com/gchq/sleeper/pull/618
https://github.com/gchq/sleeper/pull/618
1
resolves
Bulk import fails with serialisation error
A recent change has caused bulk import jobs to fail with an error due to Kryo serialisation being unable to deal with the list of row key types in a partition being an unmodifiable list. This change has been introduced since the last release, and is due to the change in `getMappedFields` in `Schema` to return an unmodifiable list. Steps to reproduce the problem: - Run the system tests with ingest mode set to queue. - Pause the system so the ingest tasks don't run. - Wait for some unsorted, uningested files to have been written. - Reinitialise the table with the 512 split points file from scripts/test/splitpoint. - Put a JSON message on the bulk import queue telling it to ingest the files that the ingest tasks wrote. - Look at the steps tab on the EMR cluster that will fire up.
94c3c82bc2c34597774ce5231a1c93c086becddd
6c0cb7559bd163463426df3c19550ee95c5f1907
https://github.com/gchq/sleeper/compare/94c3c82bc2c34597774ce5231a1c93c086becddd...6c0cb7559bd163463426df3c19550ee95c5f1907
diff --git a/java/core/src/main/java/sleeper/core/schema/Schema.java b/java/core/src/main/java/sleeper/core/schema/Schema.java index e7d806c6a..fcfe982e2 100644 --- a/java/core/src/main/java/sleeper/core/schema/Schema.java +++ b/java/core/src/main/java/sleeper/core/schema/Schema.java @@ -103,7 +103,7 @@ public class Schema { private <T> List<T> getMappedFields(Stream<Field> fields, Function<Field, T> mapping) { return fields .map(mapping) - .collect(Collectors.toUnmodifiableList()); + .collect(Collectors.toList()); } public List<Field> getAllFields() {
['java/core/src/main/java/sleeper/core/schema/Schema.java']
{'.java': 1}
1
1
0
0
1
2,348,707
460,999
56,276
483
107
15
2
1
798
143
176
10
0
0
"1970-01-01T00:27:57"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,690
gchq/sleeper/641/290
gchq
sleeper
https://github.com/gchq/sleeper/issues/290
https://github.com/gchq/sleeper/pull/641
https://github.com/gchq/sleeper/pull/641
1
resolves
Can't deploy environment EC2 into existing VPC
The documentation suggests that the following should allow you to use the Environment stack to deploy an EC2 only, but it fails with the error "Caused by: java.lang.RuntimeException: Error: App at '' should be created in the scope of a Stack, but no Stack found": cdk deploy -c instanceId=myenv -c vpcId=myvpc "*-BuildEC2"
404ba9d621e2a1bd3495fa15e94ec2c64847ba66
4a43eee203b30ac2b467792cf89b5944db1047d4
https://github.com/gchq/sleeper/compare/404ba9d621e2a1bd3495fa15e94ec2c64847ba66...4a43eee203b30ac2b467792cf89b5944db1047d4
diff --git a/java/cdk-environment/src/main/java/sleeper/environment/cdk/buildec2/BuildEC2Stack.java b/java/cdk-environment/src/main/java/sleeper/environment/cdk/buildec2/BuildEC2Stack.java index f116d7e26..cdb7e8fbb 100644 --- a/java/cdk-environment/src/main/java/sleeper/environment/cdk/buildec2/BuildEC2Stack.java +++ b/java/cdk-environment/src/main/java/sleeper/environment/cdk/buildec2/BuildEC2Stack.java @@ -52,7 +52,7 @@ public class BuildEC2Stack extends Stack { AppContext context = AppContext.of(this); BuildEC2Parameters params = BuildEC2Parameters.from(context); vpc = context.get(VPC_ID) - .map(vpcId -> Vpc.fromLookup(scope, "Vpc", VpcLookupOptions.builder().vpcId(vpcId).build())) + .map(vpcId -> Vpc.fromLookup(this, "Vpc", VpcLookupOptions.builder().vpcId(vpcId).build())) .orElse(inheritVpc); BuildEC2Image image = params.image();
['java/cdk-environment/src/main/java/sleeper/environment/cdk/buildec2/BuildEC2Stack.java']
{'.java': 1}
1
1
0
0
1
2,358,500
463,075
56,584
489
218
64
2
1
329
52
82
3
0
0
"1970-01-01T00:27:57"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,681
gchq/sleeper/980/979
gchq
sleeper
https://github.com/gchq/sleeper/issues/979
https://github.com/gchq/sleeper/pull/980
https://github.com/gchq/sleeper/pull/980
1
resolves
DynamoDBIngestJobStatusStore is used directly even when store may not be enabled
It's not possible to disable the ingest job status store fully because DynamoDBIngestJobStatusStore is used directly in several places. IngestJobStatusStoreFactory should be used instead.
50d50906e4370f81c7b4dc5c1d247471049dd976
43a30e6b865cae446b6e55498217738792fd02bd
https://github.com/gchq/sleeper/compare/50d50906e4370f81c7b4dc5c1d247471049dd976...43a30e6b865cae446b6e55498217738792fd02bd
diff --git a/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/BulkImportStarterLambda.java b/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/BulkImportStarterLambda.java index 321bb58ec..fade1c2a4 100644 --- a/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/BulkImportStarterLambda.java +++ b/java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/BulkImportStarterLambda.java @@ -33,7 +33,7 @@ import sleeper.bulkimport.starter.executor.PlatformExecutor; import sleeper.configuration.properties.InstanceProperties; import sleeper.configuration.properties.table.TablePropertiesProvider; import sleeper.ingest.job.status.IngestJobStatusStore; -import sleeper.ingest.status.store.job.DynamoDBIngestJobStatusStore; +import sleeper.ingest.status.store.job.IngestJobStatusStoreFactory; import sleeper.statestore.StateStoreProvider; import sleeper.utils.HadoopPathUtils; @@ -69,7 +69,7 @@ public class BulkImportStarterLambda implements RequestHandler<SQSEvent, Void> { PlatformExecutor platformExecutor = PlatformExecutor.fromEnvironment( instanceProperties, tablePropertiesProvider); hadoopConfig = new Configuration(); - ingestJobStatusStore = new DynamoDBIngestJobStatusStore(dynamo, instanceProperties); + ingestJobStatusStore = IngestJobStatusStoreFactory.getStatusStore(dynamo, instanceProperties); executor = new BulkImportExecutor(instanceProperties, tablePropertiesProvider, new StateStoreProvider(dynamo, instanceProperties), ingestJobStatusStore, s3, platformExecutor, Instant::now); diff --git a/java/bulk-import/bulk-import-starter/src/test/java/sleeper/bulkimport/starter/executor/BulkImportExecutorIT.java b/java/bulk-import/bulk-import-starter/src/test/java/sleeper/bulkimport/starter/executor/BulkImportExecutorIT.java index f9832dfbd..493a8a65c 100644 --- a/java/bulk-import/bulk-import-starter/src/test/java/sleeper/bulkimport/starter/executor/BulkImportExecutorIT.java +++ b/java/bulk-import/bulk-import-starter/src/test/java/sleeper/bulkimport/starter/executor/BulkImportExecutorIT.java @@ -43,6 +43,7 @@ import sleeper.core.schema.type.StringType; import sleeper.ingest.job.status.IngestJobStatusStore; import sleeper.ingest.status.store.job.DynamoDBIngestJobStatusStore; import sleeper.ingest.status.store.job.DynamoDBIngestJobStatusStoreCreator; +import sleeper.ingest.status.store.job.IngestJobStatusStoreFactory; import sleeper.statestore.FixedStateStoreProvider; import sleeper.statestore.StateStoreProvider; @@ -93,7 +94,7 @@ class BulkImportExecutorIT { private final TableProperties tableProperties = createTestTableProperties(instanceProperties, SCHEMA); private final String bucketName = UUID.randomUUID().toString(); private final String tableName = "myTable"; - private final IngestJobStatusStore ingestJobStatusStore = new DynamoDBIngestJobStatusStore(dynamoDB, instanceProperties); + private final IngestJobStatusStore ingestJobStatusStore = IngestJobStatusStoreFactory.getStatusStore(dynamoDB, instanceProperties); @BeforeEach void setup() { diff --git a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/DynamoDBIngestJobStatusStore.java b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/DynamoDBIngestJobStatusStore.java index df78b056b..1c3cb3118 100644 --- a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/DynamoDBIngestJobStatusStore.java +++ b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/DynamoDBIngestJobStatusStore.java @@ -59,11 +59,7 @@ public class DynamoDBIngestJobStatusStore implements IngestJobStatusStore { private final String statusTableName; private final DynamoDBIngestJobStatusFormat format; - public DynamoDBIngestJobStatusStore(AmazonDynamoDB dynamoDB, InstanceProperties properties) { - this(dynamoDB, properties, Instant::now); - } - - public DynamoDBIngestJobStatusStore(AmazonDynamoDB dynamoDB, InstanceProperties properties, Supplier<Instant> getTimeNow) { + DynamoDBIngestJobStatusStore(AmazonDynamoDB dynamoDB, InstanceProperties properties, Supplier<Instant> getTimeNow) { this.dynamoDB = dynamoDB; this.statusTableName = jobStatusTableName(properties.get(ID)); int timeToLiveInSeconds = properties.getInt(UserDefinedInstanceProperty.INGEST_JOB_STATUS_TTL_IN_SECONDS); diff --git a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/IngestJobStatusStoreFactory.java b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/IngestJobStatusStoreFactory.java index ca2a2ea95..43754c21d 100644 --- a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/IngestJobStatusStoreFactory.java +++ b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/IngestJobStatusStoreFactory.java @@ -21,6 +21,9 @@ import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import sleeper.configuration.properties.InstanceProperties; import sleeper.ingest.job.status.IngestJobStatusStore; +import java.time.Instant; +import java.util.function.Supplier; + import static sleeper.configuration.properties.UserDefinedInstanceProperty.INGEST_STATUS_STORE_ENABLED; public class IngestJobStatusStoreFactory { @@ -29,8 +32,12 @@ public class IngestJobStatusStoreFactory { } public static IngestJobStatusStore getStatusStore(AmazonDynamoDB dynamoDB, InstanceProperties properties) { + return getStatusStore(dynamoDB, properties, Instant::now); + } + + public static IngestJobStatusStore getStatusStore(AmazonDynamoDB dynamoDB, InstanceProperties properties, Supplier<Instant> getTimeNow) { if (properties.getBoolean(INGEST_STATUS_STORE_ENABLED)) { - return new DynamoDBIngestJobStatusStore(dynamoDB, properties); + return new DynamoDBIngestJobStatusStore(dynamoDB, properties, getTimeNow); } else { return IngestJobStatusStore.NONE; } diff --git a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestJobStatusStoreTestBase.java b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestJobStatusStoreTestBase.java index 5887a8bc5..b67d11bd2 100644 --- a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestJobStatusStoreTestBase.java +++ b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestJobStatusStoreTestBase.java @@ -85,7 +85,7 @@ public class DynamoDBIngestJobStatusStoreTestBase extends DynamoDBTestBase { } protected IngestJobStatusStore storeWithUpdateTimes(Instant... updateTimes) { - return new DynamoDBIngestJobStatusStore(dynamoDBClient, instanceProperties, + return IngestJobStatusStoreFactory.getStatusStore(dynamoDBClient, instanceProperties, Arrays.stream(updateTimes).iterator()::next); } diff --git a/java/system-test/src/main/java/sleeper/systemtest/ingest/batcher/InvokeIngestBatcher.java b/java/system-test/src/main/java/sleeper/systemtest/ingest/batcher/InvokeIngestBatcher.java index 8bf2fbb13..1dbca2e17 100644 --- a/java/system-test/src/main/java/sleeper/systemtest/ingest/batcher/InvokeIngestBatcher.java +++ b/java/system-test/src/main/java/sleeper/systemtest/ingest/batcher/InvokeIngestBatcher.java @@ -32,7 +32,7 @@ import sleeper.ingest.batcher.IngestBatcherStore; import sleeper.ingest.batcher.store.DynamoDBIngestBatcherStore; import sleeper.ingest.job.status.IngestJobStatus; import sleeper.ingest.job.status.IngestJobStatusStore; -import sleeper.ingest.status.store.job.DynamoDBIngestJobStatusStore; +import sleeper.ingest.status.store.job.IngestJobStatusStoreFactory; import sleeper.job.common.QueueMessageCount; import sleeper.systemtest.util.InvokeSystemTestLambda; import sleeper.systemtest.util.WaitForQueueEstimate; @@ -79,7 +79,7 @@ public class InvokeIngestBatcher { tablePropertiesUpdater(tableProperties, s3), new SendFilesToIngestBatcher(instanceProperties, tableProperties, sourceBucketName, batcherStore, sqs, lambda), - batcherStore, new DynamoDBIngestJobStatusStore(dynamoDB, instanceProperties), + batcherStore, IngestJobStatusStoreFactory.getStatusStore(dynamoDB, instanceProperties), InvokeSystemTestLambda.client(lambda, instanceProperties), QueueMessageCount.withSqsClient(sqs)); }
['java/system-test/src/main/java/sleeper/systemtest/ingest/batcher/InvokeIngestBatcher.java', 'java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/IngestJobStatusStoreFactory.java', 'java/bulk-import/bulk-import-starter/src/test/java/sleeper/bulkimport/starter/executor/BulkImportExecutorIT.java', 'java/bulk-import/bulk-import-starter/src/main/java/sleeper/bulkimport/starter/BulkImportStarterLambda.java', 'java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/job/DynamoDBIngestJobStatusStore.java', 'java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestJobStatusStoreTestBase.java']
{'.java': 6}
6
6
0
0
6
2,958,547
581,593
70,478
621
1,194
267
19
3
187
24
38
1
0
0
"1970-01-01T00:28:08"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,686
gchq/sleeper/817/816
gchq
sleeper
https://github.com/gchq/sleeper/issues/816
https://github.com/gchq/sleeper/pull/817
https://github.com/gchq/sleeper/pull/817
1
resolves
Ingest task reporting fails when task exits immediately
If an ingest task starts up and then immediately exits, it will try to report a task finished event with zero duration. This produces an ingest rate of NaN as it's divided by zero. This throws an exception when it tries to store the event like `AmazonDynamoDBException: The parameter cannot be converted to a numeric value: NaN`. There may also be an equivalent failure in the compaction reporting.
f68f779db1488428bfd1ad725c5e8dac36205981
b4e33ab50d0c24371b4d96faee0de6d7aeae1816
https://github.com/gchq/sleeper/compare/f68f779db1488428bfd1ad725c5e8dac36205981...b4e33ab50d0c24371b4d96faee0de6d7aeae1816
diff --git a/java/compaction/compaction-status-store/src/main/java/sleeper/compaction/status/store/task/DynamoDBCompactionTaskStatusFormat.java b/java/compaction/compaction-status-store/src/main/java/sleeper/compaction/status/store/task/DynamoDBCompactionTaskStatusFormat.java index dedfa526a..adb529d56 100644 --- a/java/compaction/compaction-status-store/src/main/java/sleeper/compaction/status/store/task/DynamoDBCompactionTaskStatusFormat.java +++ b/java/compaction/compaction-status-store/src/main/java/sleeper/compaction/status/store/task/DynamoDBCompactionTaskStatusFormat.java @@ -31,10 +31,10 @@ import java.util.Map; import java.util.function.Supplier; import java.util.stream.Stream; +import static sleeper.dynamodb.tools.DynamoDBAttributes.getDoubleAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getInstantAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getIntAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getLongAttribute; -import static sleeper.dynamodb.tools.DynamoDBAttributes.getNumberAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getStringAttribute; public class DynamoDBCompactionTaskStatusFormat { @@ -116,8 +116,8 @@ public class DynamoDBCompactionTaskStatusFormat { .totalJobRuns(getIntAttribute(item, NUMBER_OF_JOBS, 0)) .totalRecordsRead(getLongAttribute(item, LINES_READ, 0)) .totalRecordsWritten(getLongAttribute(item, LINES_WRITTEN, 0)) - .recordsReadPerSecond(Double.parseDouble(getNumberAttribute(item, READ_RATE))) - .recordsWrittenPerSecond(Double.parseDouble(getNumberAttribute(item, WRITE_RATE))) + .recordsReadPerSecond(getDoubleAttribute(item, READ_RATE, 0)) + .recordsWrittenPerSecond(getDoubleAttribute(item, WRITE_RATE, 0)) .build()); break; default: diff --git a/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBAttributes.java b/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBAttributes.java index 23f0a32d1..d15cc5c3f 100644 --- a/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBAttributes.java +++ b/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBAttributes.java @@ -45,7 +45,14 @@ public class DynamoDBAttributes { * @return the AttributeValue */ public static AttributeValue createNumberAttribute(Number number) { - return new AttributeValue().withN("" + number); + // To differentiate NaN and null: + // - An attribute which is set to the value of null will be treated as NaN + // - An attribute which is NOT set, will be treated as null + if (Double.valueOf(Double.NaN).equals(number)) { + return new AttributeValue().withNULL(true); + } else { + return new AttributeValue().withN(String.valueOf(number)); + } } public static AttributeValue createBinaryAttribute(byte[] bytes) { @@ -88,6 +95,18 @@ public class DynamoDBAttributes { return buildInstant.apply(Long.parseLong(string)); } + public static double getDoubleAttribute(Map<String, AttributeValue> item, String key, double defaultValue) { + if (!item.containsKey(key)) { + return defaultValue; + } + String attributeValue = getNumberAttribute(item, key); + if (attributeValue == null) { + return Double.NaN; + } else { + return Double.parseDouble(attributeValue); + } + } + private static <T> T getAttribute(Map<String, AttributeValue> item, String name, Function<AttributeValue, T> getter) { AttributeValue value = item.get(name); if (value == null) { @@ -96,5 +115,4 @@ public class DynamoDBAttributes { return getter.apply(value); } } - } diff --git a/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBRecordBuilder.java b/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBRecordBuilder.java index 65b83b361..e9106b9b8 100644 --- a/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBRecordBuilder.java +++ b/java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBRecordBuilder.java @@ -35,7 +35,11 @@ public class DynamoDBRecordBuilder { } public DynamoDBRecordBuilder number(String key, Number value) { - return add(new Attribute(key, createNumberAttribute(value))); + if (null == value) { + return remove(key); + } else { + return add(new Attribute(key, createNumberAttribute(value))); + } } public DynamoDBRecordBuilder apply(Consumer<DynamoDBRecordBuilder> config) { @@ -53,6 +57,11 @@ public class DynamoDBRecordBuilder { return this; } + private DynamoDBRecordBuilder remove(String key) { + attributes.removeIf(attribute -> attribute.key.equals(key)); + return this; + } + private static class Attribute { private final String key; private final AttributeValue value; diff --git a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBAttributesTest.java b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBAttributesTest.java index 757375f01..758c0136b 100644 --- a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBAttributesTest.java +++ b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBAttributesTest.java @@ -72,4 +72,36 @@ public class DynamoDBAttributesTest { // Then the Instant attribute should be read from the record assertThat(DynamoDBAttributes.getInstantAttribute(item, TEST_KEY)).isEqualTo(time); } + + @Test + void shouldGetDoubleAttribute() { + // Given + Map<String, AttributeValue> item = new HashMap<>(); + item.put(TEST_KEY, DynamoDBAttributes.createNumberAttribute(123.456)); + + // When/Then + assertThat(DynamoDBAttributes.getDoubleAttribute(item, TEST_KEY, 0)) + .isEqualTo(123.456); + } + + @Test + void shouldGetDoubleAttributeWhenAttributeSetToNull() { + // Given + Map<String, AttributeValue> item = new HashMap<>(); + item.put(TEST_KEY, null); + + // When/Then + assertThat(DynamoDBAttributes.getDoubleAttribute(item, TEST_KEY, 0)) + .isEqualTo(Double.valueOf(Double.NaN)); + } + + @Test + void shouldNotGetDoubleAttributeWhenAttributeNotSet() { + // Given + Map<String, AttributeValue> item = new HashMap<>(); + + // When/Then + assertThat(DynamoDBAttributes.getDoubleAttribute(item, TEST_KEY, 0)) + .isEqualTo(0); + } } diff --git a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBRecordBuilderIT.java b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBRecordBuilderIT.java index 2ff652660..2a0c8a72f 100644 --- a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBRecordBuilderIT.java +++ b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBRecordBuilderIT.java @@ -31,15 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; public class DynamoDBRecordBuilderIT extends DynamoDBTableTestBase { @Test public void shouldCreateRecordWithStringAttribute() { - // Given we have a table in dynamodb that accepts strings - createStringTable(); - // When we create a record with string attributes + // Given Map<String, AttributeValue> record = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .string(TEST_VALUE, "value").build(); - // And save that record to dynamodb + // When dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); - // Then we should be able to retrieve the record from dynamodb + // Then ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); assertThat(result.getItems()).containsExactly(record); } @@ -47,46 +45,84 @@ public class DynamoDBRecordBuilderIT extends DynamoDBTableTestBase { @Test public void shouldCreateRecordWithIntAttribute() { - // Given we have a table in dynamodb that accepts strings - createNumericTable(); - // When we create a record with string attributes + // Given Map<String, AttributeValue> record = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .number(TEST_VALUE, 123).build(); - // And save that record to dynamodb + // When dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); - // Then we should be able to retrieve the record from dynamodb + // Then ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); assertThat(result.getItems()).containsExactly(record); } @Test public void shouldCreateRecordWithLongAttribute() { - // Given we have a table in dynamodb that accepts strings - createNumericTable(); - // When we create a record with string attributes + // Given Map<String, AttributeValue> record = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .number(TEST_VALUE, 123L).build(); - // And save that record to dynamodb + // When dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); - // Then we should be able to retrieve the record from dynamodb + // Then ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); assertThat(result.getItems()).containsExactly(record); } @Test public void shouldCreateRecordWithInstantAttribute() { - // Given we have a table in dynamodb that accepts strings - createNumericTable(); - // When we create a record with string attributes + // Given Map<String, AttributeValue> record = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .number(TEST_VALUE, Instant.now().toEpochMilli()).build(); - // And save that record to dynamodb + // When dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); - // Then we should be able to retrieve the record from dynamodb + // Then ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); assertThat(result.getItems()).containsExactly(record); } + + @Test + void shouldCreateRecordWithNaN() { + // Given + String key = UUID.randomUUID().toString(); + Map<String, AttributeValue> record = new DynamoDBRecordBuilder() + .string(TEST_KEY, key) + .number(TEST_VALUE, Double.NaN).build(); + // When + dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); + // Then + ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); + assertThat(result.getItems()).containsExactly(record); + } + + @Test + void shouldCreateRecordWithNullNumber() { + // Given + String key = UUID.randomUUID().toString(); + Map<String, AttributeValue> record = new DynamoDBRecordBuilder() + .string(TEST_KEY, key) + .number(TEST_VALUE, null).build(); + // When + dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); + // Then + ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); + assertThat(result.getItems()).containsExactly(record); + } + + @Test + void shouldUnsetExistingNumberAttributeWhenProvidingNull() { + // Given + String key = UUID.randomUUID().toString(); + Map<String, AttributeValue> record = new DynamoDBRecordBuilder() + .string(TEST_KEY, key) + .number(TEST_VALUE, 123) + .number(TEST_VALUE, null).build(); + // When + dynamoDBClient.putItem(new PutItemRequest(TEST_TABLE_NAME, record)); + // Then + ScanResult result = dynamoDBClient.scan(new ScanRequest().withTableName(TEST_TABLE_NAME)); + assertThat(result.getItems()).containsExactly(new DynamoDBRecordBuilder() + .string(TEST_KEY, key).build()); + } } diff --git a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBTableTestBase.java b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBTableTestBase.java index 7d69f6fc9..30bc59a18 100644 --- a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBTableTestBase.java +++ b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBTableTestBase.java @@ -21,8 +21,9 @@ import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; -import java.util.Arrays; +import java.util.List; import static sleeper.dynamodb.tools.DynamoDBUtils.initialiseTable; @@ -31,26 +32,21 @@ public class DynamoDBTableTestBase extends DynamoDBTestBase { public static final String TEST_VALUE = "test-value"; public static final String TEST_TABLE_NAME = "dynamodb-tools-test-table"; + @BeforeEach + void setup() { + createTable(); + } + @AfterEach public void tearDown() { dynamoDBClient.deleteTable(TEST_TABLE_NAME); } - public static void createStringTable() { - createTable(ScalarAttributeType.S); - } - - public static void createNumericTable() { - createTable(ScalarAttributeType.N); - } - - public static void createTable(ScalarAttributeType valueType) { + public static void createTable() { initialiseTable(dynamoDBClient, TEST_TABLE_NAME, - Arrays.asList( - new AttributeDefinition(TEST_KEY, ScalarAttributeType.S), - new AttributeDefinition(TEST_VALUE, valueType)), - Arrays.asList( - new KeySchemaElement(TEST_KEY, KeyType.HASH), - new KeySchemaElement(TEST_VALUE, KeyType.RANGE))); + List.of( + new AttributeDefinition(TEST_KEY, ScalarAttributeType.S)), + List.of( + new KeySchemaElement(TEST_KEY, KeyType.HASH))); } } diff --git a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBUtilsPagingIT.java b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBUtilsPagingIT.java index 41d1c2c7a..f72249953 100644 --- a/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBUtilsPagingIT.java +++ b/java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBUtilsPagingIT.java @@ -31,8 +31,6 @@ public class DynamoDBUtilsPagingIT extends DynamoDBTableTestBase { @Test void shouldReturnPagedResultsWhenMoreRecordsThanScanLimit() { // Given - createStringTable(); - Map<String, AttributeValue> record1 = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .string(TEST_VALUE, "value1").build(); @@ -53,8 +51,6 @@ public class DynamoDBUtilsPagingIT extends DynamoDBTableTestBase { @Test void shouldReturnOnePageOfResultsWhenFewerRecordsThanScanLimit() { // Given - createStringTable(); - Map<String, AttributeValue> record1 = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .string(TEST_VALUE, "value1").build(); @@ -71,8 +67,6 @@ public class DynamoDBUtilsPagingIT extends DynamoDBTableTestBase { @Test void shouldReturnPagedResultsWhenRecordsEqualToScanLimit() { // Given - createStringTable(); - Map<String, AttributeValue> record1 = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .string(TEST_VALUE, "value1").build(); @@ -89,8 +83,6 @@ public class DynamoDBUtilsPagingIT extends DynamoDBTableTestBase { @Test void shouldReturnPagedResultsWhenLastPageHasFewerRecordsThanScanLimit() { // Given - createStringTable(); - Map<String, AttributeValue> record1 = new DynamoDBRecordBuilder() .string(TEST_KEY, UUID.randomUUID().toString()) .string(TEST_VALUE, "value1").build(); @@ -114,9 +106,6 @@ public class DynamoDBUtilsPagingIT extends DynamoDBTableTestBase { @Test void shouldReturnNoResultsWhenNoRecordsExist() { - // Given - createStringTable(); - // When/Then assertThat(streamPagedItems(dynamoDBClient, new ScanRequest() .withTableName(TEST_TABLE_NAME) diff --git a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/task/DynamoDBIngestTaskStatusFormat.java b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/task/DynamoDBIngestTaskStatusFormat.java index 12276842e..f2f1aecf8 100644 --- a/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/task/DynamoDBIngestTaskStatusFormat.java +++ b/java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/task/DynamoDBIngestTaskStatusFormat.java @@ -31,10 +31,10 @@ import java.util.Map; import java.util.function.Supplier; import java.util.stream.Stream; +import static sleeper.dynamodb.tools.DynamoDBAttributes.getDoubleAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getInstantAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getIntAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getLongAttribute; -import static sleeper.dynamodb.tools.DynamoDBAttributes.getNumberAttribute; import static sleeper.dynamodb.tools.DynamoDBAttributes.getStringAttribute; public class DynamoDBIngestTaskStatusFormat { @@ -113,8 +113,8 @@ public class DynamoDBIngestTaskStatusFormat { .totalJobRuns(getIntAttribute(item, NUMBER_OF_JOBS, 0)) .totalRecordsRead(getLongAttribute(item, LINES_READ, 0)) .totalRecordsWritten(getLongAttribute(item, LINES_WRITTEN, 0)) - .recordsReadPerSecond(Double.parseDouble(getNumberAttribute(item, READ_RATE))) - .recordsWrittenPerSecond(Double.parseDouble(getNumberAttribute(item, WRITE_RATE))) + .recordsReadPerSecond(getDoubleAttribute(item, READ_RATE, 0)) + .recordsWrittenPerSecond(getDoubleAttribute(item, WRITE_RATE, 0)) .build()); break; default: diff --git a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/task/StoreIngestTaskIT.java b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/task/StoreIngestTaskIT.java index 7b41a1edb..e8cc2d178 100644 --- a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/task/StoreIngestTaskIT.java +++ b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/task/StoreIngestTaskIT.java @@ -79,4 +79,19 @@ public class StoreIngestTaskIT extends DynamoDBIngestTaskStatusStoreTestBase { .isNull(); } + @Test + public void shouldReportIngestTaskFinishedWithZeroDuration() { + // Given + IngestTaskStatus taskStatus = finishedTaskWithNoJobsAndZeroDuration(); + + // When + store.taskStarted(taskStatus); + store.taskFinished(taskStatus); + + // Then + assertThat(store.getTask(taskStatus.getTaskId())) + .usingRecursiveComparison(IGNORE_EXPIRY_DATE) + .isEqualTo(taskStatus); + } + } diff --git a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestTaskStatusStoreTestBase.java b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestTaskStatusStoreTestBase.java index b5fa6e022..9032b7268 100644 --- a/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestTaskStatusStoreTestBase.java +++ b/java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestTaskStatusStoreTestBase.java @@ -33,6 +33,7 @@ import sleeper.ingest.task.IngestTaskStatusStore; import java.time.Duration; import java.time.Instant; import java.util.Arrays; +import java.util.Comparator; import java.util.UUID; import static sleeper.configuration.properties.UserDefinedInstanceProperty.ID; @@ -42,7 +43,11 @@ import static sleeper.ingest.status.store.task.DynamoDBIngestTaskStatusStore.tas public class DynamoDBIngestTaskStatusStoreTestBase extends DynamoDBTestBase { protected static final RecursiveComparisonConfiguration IGNORE_EXPIRY_DATE = RecursiveComparisonConfiguration.builder() - .withIgnoredFields("expiryDate").build(); + .withIgnoredFields("expiryDate") + // For some reason, default Double comparator compares NaNs as object references instead of their double values + .withComparatorForFields(Comparator.naturalOrder(), + "finishedStatus.recordsReadPerSecond", "finishedStatus.recordsWrittenPerSecond") + .build(); private final InstanceProperties instanceProperties = IngestStatusStoreTestUtils.createInstanceProperties(); private final String taskStatusTableName = taskStatusTableName(instanceProperties.get(ID)); protected final IngestTaskStatusStore store = IngestTaskStatusStoreFactory.getStatusStore(dynamoDBClient, instanceProperties); @@ -111,6 +116,12 @@ public class DynamoDBIngestTaskStatusStoreTestBase extends DynamoDBTestBase { ).build(); } + protected static IngestTaskStatus finishedTaskWithNoJobsAndZeroDuration() { + return startedTaskWithDefaultsBuilder().finished( + defaultTaskStartTime(), IngestTaskFinishedStatus.builder() + ).build(); + } + protected static IngestTaskStatus taskWithStartTime(Instant startTime) { return taskBuilder().startTime(startTime).build(); }
['java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBUtilsPagingIT.java', 'java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBAttributesTest.java', 'java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBAttributes.java', 'java/ingest/ingest-status-store/src/main/java/sleeper/ingest/status/store/task/DynamoDBIngestTaskStatusFormat.java', 'java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/task/StoreIngestTaskIT.java', 'java/dynamodb-tools/src/main/java/sleeper/dynamodb/tools/DynamoDBRecordBuilder.java', 'java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBRecordBuilderIT.java', 'java/compaction/compaction-status-store/src/main/java/sleeper/compaction/status/store/task/DynamoDBCompactionTaskStatusFormat.java', 'java/ingest/ingest-status-store/src/test/java/sleeper/ingest/status/store/testutils/DynamoDBIngestTaskStatusStoreTestBase.java', 'java/dynamodb-tools/src/test/java/sleeper/dynamodb/tools/DynamoDBTableTestBase.java']
{'.java': 10}
10
10
0
0
10
2,733,096
537,899
65,076
574
2,377
427
45
4
404
68
83
5
0
0
"1970-01-01T00:28:03"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,685
gchq/sleeper/880/874
gchq
sleeper
https://github.com/gchq/sleeper/issues/874
https://github.com/gchq/sleeper/pull/880
https://github.com/gchq/sleeper/pull/880
1
resolves
Admin client doesn't display default value of table property when editing
To reproduce, in the admin client, set a value for a table property which was previously taking its default value from an instance property. In the screen where it summarises the change, it does not show you the default value. It only tells you it was previously unset.
6fde7486dbe01bd53e6f91380c7b068536d8b737
bfa0845e8ac161152f81103852ea693e878e030b
https://github.com/gchq/sleeper/compare/6fde7486dbe01bd53e6f91380c7b068536d8b737...bfa0845e8ac161152f81103852ea693e878e030b
diff --git a/java/clients/src/test/java/sleeper/clients/admin/InstanceConfigurationTest.java b/java/clients/src/test/java/sleeper/clients/admin/InstanceConfigurationTest.java index b4624caa5..d50cbdef2 100644 --- a/java/clients/src/test/java/sleeper/clients/admin/InstanceConfigurationTest.java +++ b/java/clients/src/test/java/sleeper/clients/admin/InstanceConfigurationTest.java @@ -56,6 +56,7 @@ import static sleeper.configuration.properties.UserDefinedInstanceProperty.OPTIO import static sleeper.configuration.properties.UserDefinedInstanceProperty.VPC_ID; import static sleeper.configuration.properties.table.TableProperty.DATA_BUCKET; import static sleeper.configuration.properties.table.TableProperty.DYNAMODB_STRONGLY_CONSISTENT_READS; +import static sleeper.configuration.properties.table.TableProperty.ITERATOR_CONFIG; import static sleeper.configuration.properties.table.TableProperty.ROW_GROUP_SIZE; import static sleeper.configuration.properties.table.TableProperty.TABLE_NAME; @@ -530,7 +531,7 @@ class InstanceConfigurationTest extends AdminClientMockStoreBase { InstanceProperties properties = createValidInstanceProperties(); TableProperties before = createValidTableProperties(properties); TableProperties after = createValidTableProperties(properties); - after.set(ROW_GROUP_SIZE, "123"); + after.set(ITERATOR_CONFIG, "TestIterator"); // When String output = editTableConfiguration(properties, before, after) @@ -621,6 +622,30 @@ class InstanceConfigurationTest extends AdminClientMockStoreBase { "\\n" + PROPERTY_VALIDATION_SCREEN + DISPLAY_MAIN_SCREEN); } + + @Test + void shouldEditAPropertyThatWasPreviouslyUnsetButHadADefaultProperty() throws Exception { + // Given + InstanceProperties properties = createValidInstanceProperties(); + TableProperties before = createValidTableProperties(properties); + TableProperties after = createValidTableProperties(properties); + after.set(ROW_GROUP_SIZE, "123"); + + // When + String output = editTableConfiguration(properties, before, after) + .enterPrompts(SaveChangesScreen.SAVE_CHANGES_OPTION, CONFIRM_PROMPT) + .exitGetOutput(); + + // Then + assertThat(output).startsWith(DISPLAY_MAIN_SCREEN + CLEAR_CONSOLE + TABLE_SELECT_SCREEN) + .contains("Found changes to properties:\\n" + + "\\n" + + "sleeper.table.rowgroup.size\\n" + + "The size of the row group in the Parquet files - defaults to the value in the instance properties.\\n" + + "Unset before, default value: 8388608\\n" + + "After: 123\\n") + .endsWith(PROPERTY_SAVE_CHANGES_SCREEN + PROMPT_SAVE_SUCCESSFUL_RETURN_TO_MAIN + DISPLAY_MAIN_SCREEN); + } } @DisplayName("Filter by group") diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/table/TablePropertyImpl.java b/java/configuration/src/main/java/sleeper/configuration/properties/table/TablePropertyImpl.java index 25a96752f..42a20901d 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/table/TablePropertyImpl.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/table/TablePropertyImpl.java @@ -139,6 +139,7 @@ class TablePropertyImpl implements TableProperty { public Builder defaultProperty(SleeperProperty defaultProperty) { this.defaultProperty = defaultProperty; + this.defaultValue = defaultProperty.getDefaultValue(); return validationPredicate(defaultProperty.validationPredicate()); } diff --git a/java/configuration/src/test/java/sleeper/configuration/properties/table/TablePropertiesTest.java b/java/configuration/src/test/java/sleeper/configuration/properties/table/TablePropertiesTest.java index 48c072536..2e4ef8671 100644 --- a/java/configuration/src/test/java/sleeper/configuration/properties/table/TablePropertiesTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/properties/table/TablePropertiesTest.java @@ -49,6 +49,21 @@ class TablePropertiesTest { assertThat(tableProperties.get(PAGE_SIZE)).isEqualTo("20"); } + @Test + void shouldGetDefaultValueFromDefaultProperty() { + // Given + InstanceProperties instanceProperties = new InstanceProperties(); + + // When + TableProperties tableProperties = new TableProperties(instanceProperties); + + // Then + assertThat(tableProperties.get(PAGE_SIZE)) + .isEqualTo("" + (128 * 1024)); + assertThat(PAGE_SIZE.getDefaultValue()) + .isEqualTo("" + (128 * 1024)); + } + @Test void shouldDefaultToAnotherTablePropertyIfConfigured() { // Given
['java/configuration/src/main/java/sleeper/configuration/properties/table/TablePropertyImpl.java', 'java/configuration/src/test/java/sleeper/configuration/properties/table/TablePropertiesTest.java', 'java/clients/src/test/java/sleeper/clients/admin/InstanceConfigurationTest.java']
{'.java': 3}
3
3
0
0
3
2,822,288
555,806
67,107
591
67
9
1
1
272
48
55
3
0
0
"1970-01-01T00:28:05"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,684
gchq/sleeper/947/946
gchq
sleeper
https://github.com/gchq/sleeper/issues/946
https://github.com/gchq/sleeper/pull/947
https://github.com/gchq/sleeper/pull/947
1
resolves
Cannot set a defaulted list property to an empty list
For some list properties that have a default value, there isn't a way to set the property to an empty list. ```properties sleeper.list.property= ``` does not work as `getList()` returns a list containing the empty string, instead of an empty list
7f6cab72f62338316693582a053ace3bb2ea5a19
42f4705339ded4c7dfa1ccb72261f5a19e261063
https://github.com/gchq/sleeper/compare/7f6cab72f62338316693582a053ace3bb2ea5a19...42f4705339ded4c7dfa1ccb72261f5a19e261063
diff --git a/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java b/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java index 993a4394c..ab7cdd170 100644 --- a/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java +++ b/java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java @@ -114,7 +114,13 @@ public abstract class SleeperProperties<T extends SleeperProperty> { } public static List<String> readList(String value) { - return value == null ? null : Lists.newArrayList(value.split(",")); + if (value == null) { + return null; + } else if ("".equals(value)) { + return List.of(); + } else { + return Lists.newArrayList(value.split(",")); + } } public void setNumber(T property, Number number) { diff --git a/java/configuration/src/test/java/sleeper/configuration/properties/SleeperPropertiesTest.java b/java/configuration/src/test/java/sleeper/configuration/properties/SleeperPropertiesTest.java index fd4a4efd2..3445b9db0 100644 --- a/java/configuration/src/test/java/sleeper/configuration/properties/SleeperPropertiesTest.java +++ b/java/configuration/src/test/java/sleeper/configuration/properties/SleeperPropertiesTest.java @@ -160,6 +160,19 @@ class SleeperPropertiesTest { assertThat(list).isNull(); } + @Test + void shouldReturnEmptyListIfListPropertyIsSetToEmptyString() { + // Given + TestSleeperProperties testSleeperProperties = new TestSleeperProperties(); + testSleeperProperties.set(OPTIONAL_STACKS, ""); + + // When + List<String> list = testSleeperProperties.getList(OPTIONAL_STACKS); + + // Then + assertThat(list).isEmpty(); + } + private static class TestSleeperProperties extends SleeperProperties<SleeperProperty> { private TestSleeperProperties() {
['java/configuration/src/main/java/sleeper/configuration/properties/SleeperProperties.java', 'java/configuration/src/test/java/sleeper/configuration/properties/SleeperPropertiesTest.java']
{'.java': 2}
2
2
0
0
2
2,931,764
576,573
69,783
612
290
55
8
1
250
41
56
5
0
1
"1970-01-01T00:28:08"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,683
gchq/sleeper/969/960
gchq
sleeper
https://github.com/gchq/sleeper/issues/960
https://github.com/gchq/sleeper/pull/969
https://github.com/gchq/sleeper/pull/969
1
resolves
Bulk import performance test fails as BulkImportStarterLambda times out processing all jobs
With the new validation changes, the BulkImportStarterLambda reaches the timeout of 20 seconds when trying to process all 5 jobs and record their validation status. We should increase this timeout so that jobs have enough time to be processed. This has failed the bulk import performance test as the same execution of the Lambda picked up 3 bulk import jobs from the queue all at once. It couldn't process all 3 within 20 seconds, although any one job would have completed on its own. It might good if we can set a timeout per message processed, rather than an absolute timeout. An alternative would be to prevent it processing multiple messages in one execution. The current timeout is configured in CommonEmrBulkImportHelper.createJobStarterFunction.
956330f12bcac73d22a51330af75918c4a7de46e
e970f44757ab66c8bbffac68a579349a66ed4b1f
https://github.com/gchq/sleeper/compare/956330f12bcac73d22a51330af75918c4a7de46e...e970f44757ab66c8bbffac68a579349a66ed4b1f
diff --git a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java index 7ba3d0a23..840e4d62d 100644 --- a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java +++ b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java @@ -123,12 +123,12 @@ public class CommonEmrBulkImportHelper { .functionName(functionName) .description("Function to start " + shortId + " bulk import jobs") .memorySize(1024) - .timeout(Duration.seconds(20)) + .timeout(Duration.minutes(2)) .environment(env) .runtime(software.amazon.awscdk.services.lambda.Runtime.JAVA_11) .handler("sleeper.bulkimport.starter.BulkImportStarterLambda") .logRetention(Utils.getRetentionDays(instanceProperties.getInt(LOG_RETENTION_IN_DAYS))) - .events(Lists.newArrayList(new SqsEventSource(jobQueue)))); + .events(Lists.newArrayList(SqsEventSource.Builder.create(jobQueue).batchSize(1).build()))); configBucket.grantRead(function); importBucket.grantReadWrite(function);
['java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java']
{'.java': 1}
1
1
0
0
1
2,936,487
577,180
69,895
614
280
53
4
1
755
121
151
7
0
0
"1970-01-01T00:28:08"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
9,682
gchq/sleeper/976/975
gchq
sleeper
https://github.com/gchq/sleeper/issues/975
https://github.com/gchq/sleeper/pull/976
https://github.com/gchq/sleeper/pull/976
1
resolves
Bulk import stack does not deploy because queue timeout is less than function timeout
When the bulk import performance test ran, we found this error trying to deploy to CloudFormation: Resource handler returned message: "Invalid request provided: Queue visibility timeout: 30 seconds is less than Function timeout: 120 seconds (Service: Lambda, Status Code: 400, Request ID: 123)" (RequestToken: abc, HandlerErrorCode: InvalidRequest) It looks like this was caused by the changes for issue #960, in PR https://github.com/gchq/sleeper/pull/969
3c99e3330153cbaacf2b9b767038c0dd3dbfd9d5
8a4db13a5dea7bb203562005f3c266fc9fc6964b
https://github.com/gchq/sleeper/compare/3c99e3330153cbaacf2b9b767038c0dd3dbfd9d5...8a4db13a5dea7bb203562005f3c266fc9fc6964b
diff --git a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java index 840e4d62d..3492e256d 100644 --- a/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java +++ b/java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java @@ -98,6 +98,7 @@ public class CommonEmrBulkImportHelper { Queue emrBulkImportJobQueue = Queue.Builder .create(scope, "BulkImport" + shortId + "JobQueue") .deadLetterQueue(deadLetterQueue) + .visibilityTimeout(Duration.minutes(3)) .queueName(instanceId + "-BulkImport" + shortId + "Q") .build();
['java/cdk/src/main/java/sleeper/cdk/stack/bulkimport/CommonEmrBulkImportHelper.java']
{'.java': 1}
1
1
0
0
1
2,936,518
577,188
69,895
614
56
9
1
1
462
62
104
5
1
0
"1970-01-01T00:28:08"
31
Java
{'Java': 6479577, 'Shell': 147907, 'Python': 36618, 'Dockerfile': 11264}
Apache License 2.0
971
wso2/testgrid/457/456
wso2
testgrid
https://github.com/wso2/testgrid/issues/456
https://github.com/wso2/testgrid/pull/457
https://github.com/wso2/testgrid/pull/457
1
resolves
Cannot run two cloudformation-based test plans in parallel
**Description:** Cannot run two cloudformation-based test plans in parallel. There will be a naming conflict if both cloudformation scripts tried to create stacks with same name. We need to randomize the strings in order to fix this. **Affected Product Version:** 0.9.0-m11 **Steps to reproduce:** See above. **Related Issues:** N/A
e7d8c1974c9b77c65537309706d47636aad69fdc
95437ba737b4748475fed2d9a9c9ce3ef45749b4
https://github.com/wso2/testgrid/compare/e7d8c1974c9b77c65537309706d47636aad69fdc...95437ba737b4748475fed2d9a9c9ce3ef45749b4
diff --git a/common/src/main/java/org/wso2/testgrid/common/util/StringUtil.java b/common/src/main/java/org/wso2/testgrid/common/util/StringUtil.java index 50d2fca8..6dc78269 100644 --- a/common/src/main/java/org/wso2/testgrid/common/util/StringUtil.java +++ b/common/src/main/java/org/wso2/testgrid/common/util/StringUtil.java @@ -17,6 +17,8 @@ */ package org.wso2.testgrid.common.util; +import java.util.Random; + /** * Utility class to handle {@link String} related operations. * @@ -47,4 +49,21 @@ public class StringUtil { } return stringBuilder.toString(); } + + /** + * Generates a random string with the given character count using the below charset as input: + * <i>ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890</i> + * @param characterCount number of characters + * @return a random string + */ + public static String generateRandomString(int characterCount) { + final String saltChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + StringBuilder salt = new StringBuilder(); + Random rnd = new Random(); + while (salt.length() < characterCount) { + int index = (int) (rnd.nextFloat() * saltChars.length()); + salt.append(saltChars.charAt(index)); + } + return salt.toString(); + } } diff --git a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java index 33519ee2..8615efce 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java @@ -22,6 +22,7 @@ import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.testgrid.common.Product; +import org.wso2.testgrid.common.Script; import org.wso2.testgrid.common.exception.CommandExecutionException; import org.wso2.testgrid.common.infrastructure.InfrastructureCombination; import org.wso2.testgrid.common.infrastructure.InfrastructureParameter; @@ -61,6 +62,7 @@ public class GenerateTestPlanCommand implements Command { private static final Logger logger = LoggerFactory.getLogger(GenerateTestPlanCommand.class); private static final String YAML_EXTENSION = ".yaml"; + private static final int RANDOMIZED_STR_LENGTH = 6; @Option(name = "--product", usage = "Product Name", @@ -164,6 +166,8 @@ public class GenerateTestPlanCommand implements Command { for (String deploymentPattern : deploymentPatterns) { for (InfrastructureCombination combination : combinations) { + setUniqueScriptName(inputTestConfig.getInfrastructure().getScripts()); + TestConfig testConfig = new TestConfig(); testConfig.setProductName(inputTestConfig.getProductName()); testConfig.setDeploymentPatterns(Collections.singletonList(deploymentPattern)); @@ -179,6 +183,18 @@ public class GenerateTestPlanCommand implements Command { return testConfigurations; } + /** + * We need unique script names because this is referenced as an id + * for cloudformation stack name etc. + * + * @param scripts list of Scripts in a given test-config. + */ + private void setUniqueScriptName(List<Script> scripts) { + for (Script script : scripts) { + script.setName(script.getName() + '-' + StringUtil.generateRandomString(RANDOMIZED_STR_LENGTH)); + } + } + private List<Map<String, Object>> toConfigAwareInfrastructureCombination(Set<InfrastructureParameter> parameters) { Map<String, Object> configAwareInfrastructureCombination = new HashMap<>(parameters.size()); for (InfrastructureParameter parameter : parameters) {
['core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java', 'common/src/main/java/org/wso2/testgrid/common/util/StringUtil.java']
{'.java': 2}
2
2
0
0
2
571,639
118,759
16,064
142
1,358
274
35
2
348
49
77
13
0
0
"1970-01-01T00:25:17"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
970
wso2/testgrid/470/469
wso2
testgrid
https://github.com/wso2/testgrid/issues/469
https://github.com/wso2/testgrid/pull/470
https://github.com/wso2/testgrid/pull/470
1
fixes
DescribeStacksRequest should use the CloudFormation stackId instead of its name.
**Description:** Using the stackId is the only guaranteed way to make sure we get the stack that actually belong to this particular test-run. **Affected Product Version:** 0.9.0-m12 **OS, DB, other environment details and versions:** N/A **Steps to reproduce:** See above **Related Issues:** N/A
9d6b37a38bf90d18c7630e0c67e34edcf06fd59c
9f2807b3b7882a8b74c2da6f03d900ae2c07ac9c
https://github.com/wso2/testgrid/compare/9d6b37a38bf90d18c7630e0c67e34edcf06fd59c...9f2807b3b7882a8b74c2da6f03d900ae2c07ac9c
diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/aws/AWSManager.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/aws/AWSManager.java index 3d396a18..6b1eab58 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/aws/AWSManager.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/aws/AWSManager.java @@ -21,6 +21,7 @@ import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.services.cloudformation.AmazonCloudFormation; import com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder; import com.amazonaws.services.cloudformation.model.CreateStackRequest; +import com.amazonaws.services.cloudformation.model.CreateStackResult; import com.amazonaws.services.cloudformation.model.DeleteStackRequest; import com.amazonaws.services.cloudformation.model.DescribeStacksRequest; import com.amazonaws.services.cloudformation.model.DescribeStacksResult; @@ -121,7 +122,10 @@ public class AWSManager { script.getFilePath())), StandardCharsets.UTF_8); stackRequest.setTemplateBody(file); stackRequest.setParameters(getParameters(script)); - stackbuilder.createStack(stackRequest); + + logger.info(StringUtil.concatStrings("Creating CloudFormation Stack '", cloudFormationName, + "' in region '", this.infra.getRegion(), "'. Script : ", script.getFilePath())); + CreateStackResult stack = stackbuilder.createStack(stackRequest); if (logger.isDebugEnabled()) { logger.info(StringUtil.concatStrings("Stack configuration created for name ", cloudFormationName)); } @@ -129,10 +133,11 @@ public class AWSManager { Waiter<DescribeStacksRequest> describeStacksRequestWaiter = new AmazonCloudFormationWaiters(stackbuilder) .stackCreateComplete(); describeStacksRequestWaiter.run(new WaiterParameters<>(new DescribeStacksRequest())); - logger.info(StringUtil.concatStrings("Stack : ", cloudFormationName, " creation completed !")); + logger.info(StringUtil.concatStrings("Stack : ", cloudFormationName, ", with ID : ", stack.getStackId(), + " creation completed !")); DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest(); - describeStacksRequest.setStackName(cloudFormationName); + describeStacksRequest.setStackName(stack.getStackId()); DescribeStacksResult describeStacksResult = stackbuilder .describeStacks(describeStacksRequest); List<Host> hosts = new ArrayList<>();
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/aws/AWSManager.java']
{'.java': 1}
1
1
0
0
1
596,560
123,915
16,660
147
824
145
11
1
902
43
88
13
0
0
"1970-01-01T00:25:18"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
969
wso2/testgrid/473/455
wso2
testgrid
https://github.com/wso2/testgrid/issues/455
https://github.com/wso2/testgrid/pull/473
https://github.com/wso2/testgrid/pull/473
1
resolves
Waiting for server startup in AWS logic does not work
**Description:** I'm seeing below error when running the `run-test-plan`. The cloudformation scripts need to properly present the serverURLs in order to wait for the server startup. ```log [2018-02-02 13:58:25,516] INFO {org.wso2.testgrid.infrastructure.aws.AWSManager} - Waiting for stack : wso2-is-public-branch-AZ63FR [2018-02-02 14:06:19,792] INFO {org.wso2.testgrid.infrastructure.aws.AWSManager} - Stack : wso2-is-public-branch-AZ63FR creation completed ! [2018-02-02 14:06:20,128] INFO {org.wso2.testgrid.infrastructure.aws.AWSManager} - Created a CloudFormation Stack with the name :wso2-is-public-branch-AZ63FR [2018-02-02 14:06:20,141] INFO {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Deploying the pattern.. : cloudformation-templates/pattern-2 [2018-02-02 14:06:20,142] INFO {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Waiting for server startup.. [2018-02-02 14:06:20,143] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : ec2-52-54-230-106.compute-1.amazonaws.com is Not a Valid URL, hence skipping to next value.. [2018-02-02 14:06:20,144] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : 8080 is Not a Valid URL, hence skipping to next value.. [2018-02-02 14:06:20,146] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : 10.0.1.213 is Not a Valid URL, hence skipping to next value.. [2018-02-02 14:06:20,153] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : 10.0.1.221 is Not a Valid URL, hence skipping to next value.. [2018-02-02 14:06:20,153] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : 3306 is Not a Valid URL, hence skipping to next value.. [2018-02-02 14:06:20,155] ERROR {org.wso2.testgrid.deployment.deployers.AWSDeployer} - Output Value : 35.168.246.85 is Not a Valid URL, hence skipping to next value.. ``` **Affected Product Version:** 0.9.0-m11 **Steps to reproduce:** Run cloudformation-is
022326aef4213e041327f8e09fb8d390943cd713
feecc8e868194d5b22c4575bdbb40d7037d6c32c
https://github.com/wso2/testgrid/compare/022326aef4213e041327f8e09fb8d390943cd713...feecc8e868194d5b22c4575bdbb40d7037d6c32c
diff --git a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/AWSDeployer.java b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/AWSDeployer.java index a9b1b739..f743dd34 100644 --- a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/AWSDeployer.java +++ b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/AWSDeployer.java @@ -56,12 +56,12 @@ public class AWSDeployer implements DeployerService { try { logger.info(StringUtil.concatStrings("Deploying the pattern.. : ", deployment.getName())); DeploymentValidator validator = new DeploymentValidator(); - logger.info("Waiting for server startup.."); for (Host host : deployment.getHosts()) { try { new URL(host.getIp()); + logger.info("Waiting for server startup on URL : " + host.getIp()); } catch (MalformedURLException e) { - logger.error(StringUtil.concatStrings("Output Value : ", host.getIp(), " is Not a Valid URL, " + + logger.debug(StringUtil.concatStrings("Output Value : ", host.getIp(), " is Not a Valid URL, " + "hence skipping to next value..")); continue; }
['deployment/src/main/java/org/wso2/testgrid/deployment/deployers/AWSDeployer.java']
{'.java': 1}
1
1
0
0
1
573,774
119,188
16,112
142
382
77
4
1
2,013
204
670
25
0
1
"1970-01-01T00:25:18"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
972
wso2/testgrid/444/427
wso2
testgrid
https://github.com/wso2/testgrid/issues/427
https://github.com/wso2/testgrid/pull/444
https://github.com/wso2/testgrid/pull/444
1
resolves
Code violation: incorrect closing of inputstream.
**Description:** Incorrect closing of inputstream: https://github.com/wso2/testgrid/blob/03d4ba54c56d2c06287a6f66f19951d1624a2f11/common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java#L43 **Affected Product Version:** 0.9.0-m10 **OS, DB, other environment details and versions:** N/A **Steps to reproduce:** See above **Related Issues:** N/A
a722a63936f08e7b7852ef517f68caff11504da1
e48660e049f88fd7035997ab3580e5db6607dea3
https://github.com/wso2/testgrid/compare/a722a63936f08e7b7852ef517f68caff11504da1...e48660e049f88fd7035997ab3580e5db6607dea3
diff --git a/automation/src/test/java/org/wso2/testgrid/automation/executor/JMeterExecutorTest.java b/automation/src/test/java/org/wso2/testgrid/automation/executor/JMeterExecutorTest.java index 8722946b..280ad260 100644 --- a/automation/src/test/java/org/wso2/testgrid/automation/executor/JMeterExecutorTest.java +++ b/automation/src/test/java/org/wso2/testgrid/automation/executor/JMeterExecutorTest.java @@ -65,9 +65,6 @@ public class JMeterExecutorTest { URL resource = classLoader.getResource("test-grid-is-resources"); Assert.assertNotNull(resource); - String testScript = Paths.get(resource.getPath(), "SolutionPattern22", "Tests", "jmeter", "mock.jmx") - .toAbsolutePath().toString(); - String testLocation = Paths.get(resource.getPath(), "SolutionPattern22", "Tests") .toAbsolutePath().toString(); TestExecutor testExecutor = new JMeterExecutor(); diff --git a/common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java b/common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java index b9fc76fa..373b8c5d 100644 --- a/common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java +++ b/common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java @@ -38,9 +38,8 @@ public class FileUtil { * @throws IOException thrown when no file is found in the given location or when error on closing file input stream */ public static <T> T readConfigurationFile(String location, Class<T> type) throws IOException { - FileInputStream fileInputStream = new FileInputStream(new File(location)); - T configuration = new Yaml().loadAs(fileInputStream, type); - fileInputStream.close(); - return configuration; + try (FileInputStream fileInputStream = new FileInputStream(new File(location))) { + return new Yaml().loadAs(fileInputStream, type); + } } }
['automation/src/test/java/org/wso2/testgrid/automation/executor/JMeterExecutorTest.java', 'common/src/main/java/org/wso2/testgrid/common/util/FileUtil.java']
{'.java': 2}
2
2
0
0
2
571,323
118,675
16,053
142
381
65
7
1
964
26
126
15
1
0
"1970-01-01T00:25:17"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
966
wso2/testgrid/541/537
wso2
testgrid
https://github.com/wso2/testgrid/issues/537
https://github.com/wso2/testgrid/pull/541
https://github.com/wso2/testgrid/pull/541
1
resolves
job-config.yaml cannot contain absolute paths
**Description:** When absolute paths are given for infra, deployment and scenario repo locations, generate-test-plan command fails when resolving the path. **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
af89ae19b0a16cc7f76a49845b8f7cacdb88ea6b
045fdc99d1e958850e505d8f71219d1677d9feda
https://github.com/wso2/testgrid/compare/af89ae19b0a16cc7f76a49845b8f7cacdb88ea6b...045fdc99d1e958850e505d8f71219d1677d9feda
diff --git a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java index 22495490..922b1e32 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java @@ -221,7 +221,7 @@ public class GenerateTestPlanCommand implements Command { */ private void resolvePaths(JobConfigFile jobConfigFile) { String parent = jobConfigFile.getWorkingDir(); - if (jobConfigFile.isRelativePaths() || parent != null) { + if (jobConfigFile.isRelativePaths() && parent != null) { //infra Path repoPath = Paths.get(parent, jobConfigFile.getInfrastructureRepository()); jobConfigFile.setInfrastructureRepository(resolvePath(repoPath, jobConfigFile));
['core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java']
{'.java': 1}
1
1
0
0
1
637,330
131,837
17,549
153
131
32
2
1
226
26
48
8
0
0
"1970-01-01T00:25:20"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
965
wso2/testgrid/564/558
wso2
testgrid
https://github.com/wso2/testgrid/issues/558
https://github.com/wso2/testgrid/pull/564
https://github.com/wso2/testgrid/pull/564
1
fixes
Multiple test-plan yaml files contain same infrastructure combination
**Description:** When there are multiple possible infrastructure combinations exists, Generate Test-Plan should create test-plan yaml files for each of these combinations. But ATM, although multiple test-plan yaml files are generated, the content of them are identical. <!-- Give a brief description of the issue --> **Suggested Labels:** Bug, Highest <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees--> **Steps to reproduce:** 1.Make it possible to exists multiple infrastructure combinations (Ex: add one more OS to infrastructure parameter table). 2.Run Generate-test-plan command. 3.Check yaml files generated.
0e66de32b96b854691f2da75be8d6fac0802e501
1edc47ec370a4e34d7cbb30dd8beb626df1b23ff
https://github.com/wso2/testgrid/compare/0e66de32b96b854691f2da75be8d6fac0802e501...1edc47ec370a4e34d7cbb30dd8beb626df1b23ff
diff --git a/common/src/main/java/org/wso2/testgrid/common/config/InfrastructureConfig.java b/common/src/main/java/org/wso2/testgrid/common/config/InfrastructureConfig.java index 046a0f48..02c8cffb 100644 --- a/common/src/main/java/org/wso2/testgrid/common/config/InfrastructureConfig.java +++ b/common/src/main/java/org/wso2/testgrid/common/config/InfrastructureConfig.java @@ -20,6 +20,7 @@ package org.wso2.testgrid.common.config; import org.apache.commons.collections4.ListUtils; +import org.wso2.testgrid.common.TestGridError; import java.io.Serializable; import java.util.List; @@ -32,7 +33,7 @@ import java.util.Properties; * * @since 1.0.0 */ -public class InfrastructureConfig implements Serializable { +public class InfrastructureConfig implements Serializable, Cloneable { private static final long serialVersionUID = -1660815137752094462L; @@ -169,4 +170,21 @@ public class InfrastructureConfig implements Serializable { public static class Provisioner extends DeploymentConfig.DeploymentPattern { private static final long serialVersionUID = -3937792864579403430L; } + + @Override + public InfrastructureConfig clone() { + try { + InfrastructureConfig infrastructureConfig = (InfrastructureConfig) super.clone(); + infrastructureConfig.setProvisioners(provisioners); + infrastructureConfig.setParameters(parameters); + infrastructureConfig.setContainerOrchestrationEngine(containerOrchestrationEngine); + infrastructureConfig.setIacProvider(iacProvider); + infrastructureConfig.setInfrastructureProvider(infrastructureProvider); + + return infrastructureConfig; + } catch (CloneNotSupportedException e) { + throw new TestGridError("Since the super class of this object is java.lang.Object that supports " + + "cloning this failure condition should never happen unless a serious system error occurred.", e); + } + } } diff --git a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java index c66b614e..449a3149 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java @@ -472,7 +472,7 @@ public class GenerateTestPlanCommand implements Command { setUniqueNamesFor(provisioner.getScripts()); TestPlan testPlan = new TestPlan(); - testPlan.setInfrastructureConfig(testgridYaml.getInfrastructureConfig()); + testPlan.setInfrastructureConfig(testgridYaml.getInfrastructureConfig().clone()); testPlan.getInfrastructureConfig().setProvisioners(Collections.singletonList(provisioner)); deploymentPattern.ifPresent(dp -> { setUniqueNamesFor(dp.getScripts()); @@ -482,7 +482,6 @@ public class GenerateTestPlanCommand implements Command { combination.getParameters()); testPlan.getInfrastructureConfig().setParameters(configAwareInfraCombination); testPlan.setScenarioConfig(testgridYaml.getScenarioConfig()); - testPlan.setInfrastructureConfig(testgridYaml.getInfrastructureConfig()); testPlan.setInfrastructureRepository(testgridYaml.getInfrastructureRepository()); testPlan.setDeploymentRepository(testgridYaml.getDeploymentRepository());
['core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java', 'common/src/main/java/org/wso2/testgrid/common/config/InfrastructureConfig.java']
{'.java': 2}
2
2
0
0
2
652,484
134,794
17,905
154
1,345
214
23
2
997
141
189
15
0
0
"1970-01-01T00:25:20"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
947
wso2/testgrid/1224/1127
wso2
testgrid
https://github.com/wso2/testgrid/issues/1127
https://github.com/wso2/testgrid/pull/1224
https://github.com/wso2/testgrid/pull/1224
1
resolves
Validate input for config name property
**Description:** eg: ```yaml deploymentConfig: deploymentPatterns: - name: 'scenario tests' description: 'dummy' remoteRepository: "https://github.com/ballerina-platform/ballerina-lang.git" remoteBranch: "ballerina-scenarios" dir: . scripts: - name: 'default' type: SHELL file: product-scenarios/deployment-data.sh ``` Above configuration causes the following ```bash [INFO] : 2019-01-05, 13:33:32 : Preparing workspace for testplan : data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1 [INFO] : 2019-01-05, 13:33:32 : Creating workspace and builds sub-directories [data-integration@2] Running shell script + rm -r -f /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/ + mkdir -p /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1 + mkdir -p /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/builds + mkdir -p /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/workspace + cd /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/workspace + echo Workspace directory content: Workspace directory content: + ls /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/ ls: cannot access 'tests_OracleJDK-8_MySQL-5.7_Ubuntu-18.04_run1/': No such file or directory /testgrid/testgrid-home/jobs/data-integration/data-integration_scenario: script returned exit code 2 ```
443baf4cbb8a6a0e88be3aff61e2647e8c6a89f2
88d98e938eada85f7598bdd7d114158965a41e5f
https://github.com/wso2/testgrid/compare/443baf4cbb8a6a0e88be3aff61e2647e8c6a89f2...88d98e938eada85f7598bdd7d114158965a41e5f
diff --git a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java index cf196217..08824cfa 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java @@ -324,6 +324,7 @@ public class GenerateTestPlanCommand implements Command { representer.getPropertyUtils().setSkipMissingProperties(true); // Skip missing properties in testgrid.yaml TestgridYaml testgridYaml = new Yaml(new Constructor(TestgridYaml.class), representer) .loadAs(testgridYamlContent, TestgridYaml.class); + validateDeploymentConfigName(testgridYaml); insertJobConfigFilePropertiesTo(testgridYaml, jobConfigFile); if (logger.isDebugEnabled()) { @@ -332,6 +333,18 @@ public class GenerateTestPlanCommand implements Command { return testgridYaml; } + /** + * Validate deploymentConfig name and replace invalid characters with '-'. + * + * @param testgridYaml testgridYaml + */ + private void validateDeploymentConfigName(TestgridYaml testgridYaml) { + for (DeploymentConfig.DeploymentPattern deploymentPattern : testgridYaml.getDeploymentConfig() + .getDeploymentPatterns()) { + deploymentPattern.setName(deploymentPattern.getName().replaceAll("[^a-zA-Z0-9:/]", "-")); + } + } + /** * Reads the @{@link JobConfigFile} and add its content into {@link TestgridYaml}. *
['core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java']
{'.java': 1}
1
1
0
0
1
1,442,685
292,340
37,601
276
547
112
13
1
1,783
111
524
35
1
2
"1970-01-01T00:26:02"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
973
wso2/testgrid/441/439
wso2
testgrid
https://github.com/wso2/testgrid/issues/439
https://github.com/wso2/testgrid/pull/441
https://github.com/wso2/testgrid/pull/441
1
fixes
Support DBEngine, DBEngineVersion as infrastructure parameters.
**Description:** Support DBEngine, DBEngineVersion as infrastructure parameters. **Affected Product Version:** 0.9.0-m10 **OS, DB, other environment details and versions:** N/A **Steps to reproduce:** See above **Related Issues:** N/A
0d0dda88fa7570815ce3bfb7a0de70b543f533d4
5d5238608619bc4886e74f86bb261c475e9ef8c3
https://github.com/wso2/testgrid/compare/0d0dda88fa7570815ce3bfb7a0de70b543f533d4...5d5238608619bc4886e74f86bb261c475e9ef8c3
diff --git a/common/src/main/java/org/wso2/testgrid/common/infrastructure/InfrastructureParameter.java b/common/src/main/java/org/wso2/testgrid/common/infrastructure/InfrastructureParameter.java index f313bee5..5ce13073 100644 --- a/common/src/main/java/org/wso2/testgrid/common/infrastructure/InfrastructureParameter.java +++ b/common/src/main/java/org/wso2/testgrid/common/infrastructure/InfrastructureParameter.java @@ -200,6 +200,7 @@ public class InfrastructureParameter extends AbstractUUIDEntity implements */ public enum Type { OPERATING_SYSTEM("operating_system"), + DATABASE("database"), DBEngine("DBEngine"), DBEngineVersion("DBEngineVersion"), JDK("JDK");
['common/src/main/java/org/wso2/testgrid/common/infrastructure/InfrastructureParameter.java']
{'.java': 1}
1
1
0
0
1
571,293
118,670
16,052
142
30
5
1
1
841
27
74
13
0
0
"1970-01-01T00:25:17"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
975
wso2/testgrid/418/415
wso2
testgrid
https://github.com/wso2/testgrid/issues/415
https://github.com/wso2/testgrid/pull/418
https://github.com/wso2/testgrid/pull/418
1
resolves
Absence of TESTGRID_HOME breaks shell execution
**Description:** In ShellDeployer we are retrieving the TESTGRID_HOME environment variable. If TG Home is not set this will break the execution. https://github.com/wso2/testgrid/blob/master/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java#L49 **Suggested Labels:** Bug
6da8eb0cef2a19943958253904f94759c2915f05
e86b2f1a05ad523f585711f6dbd27bb6327ec3ba
https://github.com/wso2/testgrid/compare/6da8eb0cef2a19943958253904f94759c2915f05...e86b2f1a05ad523f585711f6dbd27bb6327ec3ba
diff --git a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java index 0ab3557d..5ebdebf9 100644 --- a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java +++ b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java @@ -24,7 +24,9 @@ import org.wso2.testgrid.common.Deployment; import org.wso2.testgrid.common.ShellExecutor; import org.wso2.testgrid.common.exception.CommandExecutionException; import org.wso2.testgrid.common.exception.TestGridDeployerException; +import org.wso2.testgrid.common.util.TestGridUtil; +import java.io.IOException; import java.nio.file.Paths; /** @@ -46,14 +48,16 @@ public class ShellDeployer implements DeployerService { @Override public Deployment deploy(Deployment deployment) throws TestGridDeployerException { logger.info("Performing the Deployment " + deployment.getName()); - ShellExecutor shellExecutor = new ShellExecutor(Paths.get(System.getenv("TESTGRID_HOME"))); try { + ShellExecutor shellExecutor = new ShellExecutor(Paths.get(TestGridUtil.getTestGridHomePath())); if (!shellExecutor .executeCommand("bash " + Paths.get(deployment.getDeploymentScriptsDir(), DEPLOY_SCRIPT_NAME))) { throw new TestGridDeployerException("Error occurred while executing the deploy script"); } } catch (CommandExecutionException e) { throw new TestGridDeployerException(e); + } catch (IOException e) { + throw new TestGridDeployerException("Error occurred while retrieving the Testgrid_home ", e); } return new Deployment();
['deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java']
{'.java': 1}
1
1
0
0
1
535,970
111,457
15,069
132
428
86
6
1
312
25
74
8
1
0
"1970-01-01T00:25:17"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
976
wso2/testgrid/402/390
wso2
testgrid
https://github.com/wso2/testgrid/issues/390
https://github.com/wso2/testgrid/pull/402
https://github.com/wso2/testgrid/pull/402
1
resolves
The 'usage' help output is outdated
**Description:** The help output provided right now is quite outdated. We need to fix this for this milestone. ``` [2018-01-23 18:33:01,687] INFO {org.wso2.testgrid.core.command.HelpCommand} - usage: create-product-testplan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL usage: run-testplan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL -t TESTPLAN_PATH -ir INFRA_REPO_PATH -sr SCENARIO_REPO_PATH usage: generate-infrastructure-plan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL -i INFRASTRUCTURE_CONFIG_YAML_PATH usage: generate-report -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL usage: help example: sh testgrid.sh create-product-testplan -p wso2is -v 5.3.0 -c LTS example: sh testgrid.sh run-testplan -p wso2is -v 5.3.0 -c LTS -t ./my-testplan.yaml ``` https://github.com/wso2/testgrid/blob/master/core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java#L40 **Affected Product Version:** 0.9.0-m9 **OS, DB, other environment details and versions:** N/A **Steps to reproduce:** Run `java -Dlog4j.configurationFile=/home/kasun/log4j2.xml -jar org.wso2.testgrid.core-0.9.0-SNAPSHOT-jar-with-dependencies.jar` **Related Issues:** N/A
7833358e2fef8fda5795f1b4234758040d305d08
e74670217ac993467e9de436914f4569d5bee2bb
https://github.com/wso2/testgrid/compare/7833358e2fef8fda5795f1b4234758040d305d08...e74670217ac993467e9de436914f4569d5bee2bb
diff --git a/core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java index d9145575..cc26f473 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java @@ -37,15 +37,13 @@ public class HelpCommand implements Command { public void execute() throws CommandExecutionException { String ls = System.lineSeparator(); String usageBuilder = StringUtil.concatStrings(ls, - "usage: create-product-testplan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL", ls, - "usage: run-testplan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL -t TESTPLAN_PATH -ir " + - "INFRA_REPO_PATH -sr SCENARIO_REPO_PATH", ls, - "usage: generate-infrastructure-plan -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL -i " + - "INFRASTRUCTURE_CONFIG_YAML_PATH", ls, - "usage: generate-report -p PRODUCT_NAME -v PRODUCT_VERSION -c CHANNEL", ls, + "usage: generate-test-plan -p PRODUCT_NAME -tc TEST_CONFIG_FILE", ls, + "usage: run-testplan -p PRODUCT_NAME -ir " + + "INFRA_REPO_PATH -dr DEPLOYMENT_REPO_PATH -sr SCENARIO_REPO_PATH", ls, + "usage: generate-report -p PRODUCT_NAME --groupBy GROUPING_COLUMN", ls, "usage: help", ls, - "example: sh testgrid.sh create-product-testplan -p wso2is -v 5.3.0 -c LTS", ls, - "example: sh testgrid.sh run-testplan -p wso2is -v 5.3.0 -c LTS -t ./my-testplan.yaml", ls); + "example: /testgrid generate-test-plan -p wso2is-5.3.0-LTS -tc test-config.yaml", ls, + "example: ./testgrid run-testplan -p wso2is-5.3.0-LTS -ir ./Infrastructure -dr ./Deployment -sr ./Solutions", ls); logger.info(usageBuilder); }
['core/src/main/java/org/wso2/testgrid/core/command/HelpCommand.java']
{'.java': 1}
1
1
0
0
1
519,386
108,022
14,634
129
1,299
338
14
1
1,185
113
341
29
1
1
"1970-01-01T00:25:16"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
968
wso2/testgrid/485/362
wso2
testgrid
https://github.com/wso2/testgrid/issues/362
https://github.com/wso2/testgrid/pull/485
https://github.com/wso2/testgrid/pull/485
1
resolves
Report Displaying duplicate entries
**Description:** The final report is generated considering all the tests for all the deployments and infra parameters. However, the detailed report may list the same entry multiple times (actually different test cases). The distinct entries should be displayed instead.
4cf693abe8fbb582a1402e925b713ce0a39840dd
390ec694d728200d2a4383e57602126742a1765f
https://github.com/wso2/testgrid/compare/4cf693abe8fbb582a1402e925b713ce0a39840dd...390ec694d728200d2a4383e57602126742a1765f
diff --git a/reporting/src/main/java/org/wso2/testgrid/reporting/TestReportEngine.java b/reporting/src/main/java/org/wso2/testgrid/reporting/TestReportEngine.java index 23e0b779..c8f9adb6 100755 --- a/reporting/src/main/java/org/wso2/testgrid/reporting/TestReportEngine.java +++ b/reporting/src/main/java/org/wso2/testgrid/reporting/TestReportEngine.java @@ -26,6 +26,7 @@ import org.wso2.testgrid.common.TestPlan; import org.wso2.testgrid.common.TestScenario; import org.wso2.testgrid.common.util.StringUtil; import org.wso2.testgrid.common.util.TestGridUtil; +import org.wso2.testgrid.dao.uow.TestPlanUOW; import org.wso2.testgrid.reporting.model.GroupBy; import org.wso2.testgrid.reporting.model.PerAxisHeader; import org.wso2.testgrid.reporting.model.PerAxisSummary; @@ -556,18 +557,12 @@ public class TestReportEngine { */ private List<ReportElement> constructReportElements(Product product, AxisColumn groupByAxisColumn) { List<ReportElement> reportElements = new ArrayList<>(); - - // Deployment patterns - List<DeploymentPattern> deploymentPatterns = product.getDeploymentPatterns(); - for (DeploymentPattern deploymentPattern : deploymentPatterns) { - - // Test plans - List<TestPlan> testPlans = deploymentPattern.getTestPlans(); - for (TestPlan testPlan : testPlans) { - List<ReportElement> reportElementsForTestPlan = createReportElementsForTestPlan(testPlan, - deploymentPattern, groupByAxisColumn); - reportElements.addAll(reportElementsForTestPlan); - } + TestPlanUOW testPlanUOW = new TestPlanUOW(); + List<TestPlan> testPlans = testPlanUOW.getLatestTestPlans(product); + for (TestPlan testPlan : testPlans) { + List<ReportElement> reportElementsForTestPlan = createReportElementsForTestPlan(testPlan, + testPlan.getDeploymentPattern(), groupByAxisColumn); + reportElements.addAll(reportElementsForTestPlan); } return reportElements; }
['reporting/src/main/java/org/wso2/testgrid/reporting/TestReportEngine.java']
{'.java': 1}
1
1
0
0
1
598,439
124,311
16,696
148
1,066
208
19
1
270
39
47
2
0
0
"1970-01-01T00:25:18"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
962
wso2/testgrid/609/608
wso2
testgrid
https://github.com/wso2/testgrid/issues/608
https://github.com/wso2/testgrid/pull/609
https://github.com/wso2/testgrid/pull/609
1
resolves
Testcase persistence fails with "data too long for failure message"
**Description:** Response data in testcase failure message is too long for the failure_message field in the database. This causes in persistence failure. **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
2c9282dd46b850c7dddd86d077b8d61626ca471a
6d702df441189ee1d90326b1aed6f19c216504c4
https://github.com/wso2/testgrid/compare/2c9282dd46b850c7dddd86d077b8d61626ca471a...6d702df441189ee1d90326b1aed6f19c216504c4
diff --git a/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterResultCollector.java b/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterResultCollector.java index 10b746ae..5244d379 100644 --- a/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterResultCollector.java +++ b/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterResultCollector.java @@ -62,9 +62,7 @@ public class JMeterResultCollector extends ResultCollector { message = StringUtil.concatStrings("{ \\"Status code\\": \\"", result.getResponseCode().replaceAll("\\"", "\\\\\\""), "\\", \\"Response Message\\": \\"", - result.getResponseMessage().replaceAll("\\"", "\\\\\\""), - "\\", \\"Response Data\\": \\"", - result.getResponseDataAsString().replaceAll("\\"", "\\\\\\""), "\\"}"); + result.getResponseMessage().replaceAll("\\"", "\\\\\\""), "\\"}"); logMessage = StringUtil.concatStrings("{ \\"Status code\\": \\"", result.getResponseCode().replaceAll("\\"", "\\\\\\""),
['automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterResultCollector.java']
{'.java': 1}
1
1
0
0
1
678,728
139,748
18,583
158
311
46
4
1
226
28
48
9
0
0
"1970-01-01T00:25:21"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
963
wso2/testgrid/605/496
wso2
testgrid
https://github.com/wso2/testgrid/issues/496
https://github.com/wso2/testgrid/pull/605
https://github.com/wso2/testgrid/pull/605
1
fixes
AWS region can be configured via infrastructureConfig now.
**Description:** This can be done by setting the inputParameter 'region' under the `infrastructureConfig -> scripts`. However, this does not work ATM. We need to look at why this does not happen. **Affected Product Version:** 0.9.0-m14 **OS, DB, other environment details and versions:** **Steps to reproduce:** Run `cloudformation-is` with the following testgrid.yaml. ```yaml version: '0.9' infrastructureConfig: iacProvider: CLOUDFORMATION infrastructureProvider: AWS containerOrchestrationEngine: None parameters: - JDK : ORACLE_JDK8 provisioners: - name: 01-two-node-deployment description: Provision Infra for a two node IS cluster dir: cloudformation-templates/pattern-1 scripts: - name: infra-for-two-node-deployment description: Creates infrastructure for a IS two node deployment. type: CLOUDFORMATION file: pattern-1-with-puppet-cloudformation.template.yml inputParameters: parseInfrastructureScript: false region: us-east-2 DBPassword: "DB_Password" EC2KeyPair: "testgrid-key" ALBCertificateARN: "arn:aws:acm:us-east-1:809489900555:certificate/2ab5aded-5df1-4549-9f7e-91639ff6634e" scenarioConfig: scenarios: - "scenario02" - "scenario12" - "scenario21" ``` **Related Issues:** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. -->
2123250f7b59e13777bd2445a113f570d43e2b0c
3f0b6f141e39298cf85031737adae0f6981e7f30
https://github.com/wso2/testgrid/compare/2123250f7b59e13777bd2445a113f570d43e2b0c...3f0b6f141e39298cf85031737adae0f6981e7f30
diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java index c9b1bc10..3cc654b4 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java @@ -152,7 +152,9 @@ public class AWSProvider implements InfrastructureProvider { private InfrastructureProvisionResult doProvision(InfrastructureConfig infrastructureConfig, String stackName, String infraRepoDir) throws TestGridInfrastructureException { - String region = infrastructureConfig.getParameters().getProperty(AWS_REGION_PARAMETER); + String region = infrastructureConfig.getProvisioners().get(0) + .getScripts().get(0).getInputParameters().getProperty(AWS_REGION_PARAMETER); + Path configFilePath; try { configFilePath = TestGridUtil.getConfigFilePath(); @@ -258,7 +260,8 @@ public class AWSProvider implements InfrastructureProvider { } AmazonCloudFormation stackdestroy = AmazonCloudFormationClientBuilder.standard() .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString())) - .withRegion(infrastructureConfig.getParameters().getProperty(AWS_REGION_PARAMETER)) + .withRegion(infrastructureConfig.getProvisioners().get(0).getScripts().get(0) + .getInputParameters().getProperty(AWS_REGION_PARAMETER)) .build(); DeleteStackRequest deleteStackRequest = new DeleteStackRequest(); deleteStackRequest.setStackName(stackName);
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java']
{'.java': 1}
1
1
0
0
1
678,585
139,710
18,580
158
541
102
7
1
1,545
140
376
46
0
1
"1970-01-01T00:25:21"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
961
wso2/testgrid/613/612
wso2
testgrid
https://github.com/wso2/testgrid/issues/612
https://github.com/wso2/testgrid/pull/613
https://github.com/wso2/testgrid/pull/613
1
resolves
DB Instance Deletion Policy should be set to "Delete"
**Description:** The DBInstance deletion policy is preprocessed to take the default. This applies "Snapshot" to DeletionPolicy. Therefore, DeletionPolicy should be set to "Delete" by preprocessing the CF script **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
282fe8235a901f0b575a56d47706cacc8394a3df
22dc28f24f983fefb096eac4ad4ebd711e7b2c72
https://github.com/wso2/testgrid/compare/282fe8235a901f0b575a56d47706cacc8394a3df...22dc28f24f983fefb096eac4ad4ebd711e7b2c72
diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/CloudFormationScriptPreprocessor.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/CloudFormationScriptPreprocessor.java index 3bbd6082..83a4c2ad 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/CloudFormationScriptPreprocessor.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/CloudFormationScriptPreprocessor.java @@ -35,6 +35,7 @@ public class CloudFormationScriptPreprocessor { private static final String NAME_ELEMENT_KEY = "Name"; private static final String DB_INSTANCE_IDENTIFIER_KEY = "DBInstanceIdentifier"; private static final String DELETION_POLICY_KEY = "DeletionPolicy"; + private static final String DELETION_POLICY_VALUE = "Delete"; private static final String REGEX_LINE_SPLIT = "\\\\r?\\\\n"; /** @@ -46,7 +47,7 @@ public class CloudFormationScriptPreprocessor { public String process(String script) { script = appendRandomValue(NAME_ELEMENT_KEY, script); script = appendRandomValue(DB_INSTANCE_IDENTIFIER_KEY, script); - script = removeElement(DELETION_POLICY_KEY, script); + script = modifyElement(DELETION_POLICY_KEY, DELETION_POLICY_VALUE, script); return script; } @@ -76,14 +77,14 @@ public class CloudFormationScriptPreprocessor { } /** - * This method removes the elements which contains the key passed. + * This method modifies the elements which contains the key passed. * - * @param key Key of the element which should be removed. + * @param key Key of the element which should be modified. * @param script CF script - * @return New CF script after removing elements for the requested key (This can be multiple places if the + * @return New CF script after modifying elements for the requested key (This can be multiple places if the * element exists in multiple places in the script. */ - private static String removeElement(String key, String script) { + private static String modifyElement(String key, String value, String script) { StringBuilder newScript = new StringBuilder(); Pattern pattern = Pattern.compile("(\\\\s+)(" + key + ")\\\\s*:\\\\s*(.*)"); Matcher matcher; @@ -91,8 +92,8 @@ public class CloudFormationScriptPreprocessor { for (String line : script.split(REGEX_LINE_SPLIT)) { matcher = pattern.matcher(line); if (matcher.find()) { - logger.debug("Removing \\"" + line + "\\" element from CF-Script."); - continue; + logger.debug(StringUtil.concatStrings("Modifying CF-Script value of ", line, " to ", value)); + line = matcher.group(1) + matcher.group(2) + ": " + value; } newScript.append(line).append(System.lineSeparator()); }
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/CloudFormationScriptPreprocessor.java']
{'.java': 1}
1
1
0
0
1
679,228
139,835
18,596
158
1,138
237
15
1
281
34
65
8
0
0
"1970-01-01T00:25:21"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
960
wso2/testgrid/620/616
wso2
testgrid
https://github.com/wso2/testgrid/issues/616
https://github.com/wso2/testgrid/pull/620
https://github.com/wso2/testgrid/pull/620
1
resolves
Deployment.json is not parsed properly
**Description:** Deployment.json created by deploy.sh should be parsed in the format of tomcat host to be able to pass the correct values to replace in the jmeter scripts. **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
23932851f3a2c33f9f9b0370b647a79ae764ae77
a0f5e7e332148715a30689e7c81a3d7712da7efc
https://github.com/wso2/testgrid/compare/23932851f3a2c33f9f9b0370b647a79ae764ae77...a0f5e7e332148715a30689e7c81a3d7712da7efc
diff --git a/deployment/src/main/java/org/wso2/testgrid/deployment/DeploymentUtil.java b/deployment/src/main/java/org/wso2/testgrid/deployment/DeploymentUtil.java index 168a2537..6b1623f7 100755 --- a/deployment/src/main/java/org/wso2/testgrid/deployment/DeploymentUtil.java +++ b/deployment/src/main/java/org/wso2/testgrid/deployment/DeploymentUtil.java @@ -22,11 +22,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.testgrid.common.Deployment; import org.wso2.testgrid.common.DeploymentCreationResult; +import org.wso2.testgrid.common.Host; +import org.wso2.testgrid.common.Port; import org.wso2.testgrid.common.exception.TestGridDeployerException; +import org.wso2.testgrid.common.util.StringUtil; import java.io.File; import java.io.IOException; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; /** * This holds the utility methods used by the deployment component. @@ -38,21 +43,39 @@ public class DeploymentUtil { /** * Reads the deployment.json file and constructs the deployment object. * - * @param testPlanLocation location String of the test plan + * @param workspace location String of the test plan * @return the deployment information ObjectMapper * @throws TestGridDeployerException If reading the deployment.json file fails */ - public static DeploymentCreationResult getDeploymentCreationResult(String testPlanLocation) + public static DeploymentCreationResult getDeploymentCreationResult(String workspace) throws TestGridDeployerException { - + DeploymentCreationResult deploymentCreationResult = new DeploymentCreationResult(); + List<Host> hosts = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); - File file = new File(Paths.get(testPlanLocation, DeployerConstants.DEPLOYMENT_FILE).toString()); + File file = new File(Paths.get(workspace, DeployerConstants.DEPLOYMENT_FILE).toString()); try { - return mapper.readValue(file, DeploymentCreationResult.class); + List<Host> hostList = mapper.readValue(file, DeploymentCreationResult.class).getHosts(); + /* JMeter test files has the values for the host and ports as two properties. In order to replace + * the values, the serverHost and serverPort has to be set as two different hosts. + */ + for (Host host : hostList) { + Host serverHost = new Host(); + serverHost.setIp(host.getIp()); + serverHost.setLabel("serverHost"); + for (Port port : host.getPorts()) { + Host serverPort = new Host(); + serverPort.setIp(String.valueOf(port.getPortNumber())); + serverPort.setLabel("serverPort"); + hosts.add(serverPort); + } + hosts.add(serverHost); + } + deploymentCreationResult.setHosts(hosts); + return deploymentCreationResult; } catch (IOException e) { logger.error(e.getMessage()); - throw new TestGridDeployerException("Error occurred while reading the " - + DeployerConstants.DEPLOYMENT_FILE + " file", e); + throw new TestGridDeployerException(StringUtil.concatStrings( + "Error occurred while reading ", file.getAbsolutePath(), e)); } } } diff --git a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java index 9f4e4635..e1e98acf 100644 --- a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java +++ b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java @@ -66,13 +66,14 @@ public class ShellDeployer implements Deployer { DeploymentConfig.DeploymentPattern deploymentPatternConfig = testPlan.getDeploymentConfig() .getDeploymentPatterns().get(0); logger.info("Performing the Deployment " + deploymentPatternConfig.getName()); + final Properties inputParameters; try { Script deployment = getScriptToExecute(testPlan.getDeploymentConfig(), Script.Phase.CREATE); logger.info("Performing the Deployment " + deployment.getName()); String infraArtifact = StringUtil .concatStrings(infrastructureProvisionResult.getResultLocation(), File.separator, "k8s.properties"); - final Properties inputParameters = getInputParameters(testPlan, deployment); + inputParameters = getInputParameters(testPlan, deployment); String parameterString = TestGridUtil.getParameterString(infraArtifact, inputParameters); ShellExecutor shellExecutor = new ShellExecutor(Paths.get(TestGridUtil.getTestGridHomePath())); @@ -91,8 +92,8 @@ public class ShellDeployer implements Deployer { } catch (CommandExecutionException e) { throw new TestGridDeployerException(e); } - DeploymentCreationResult result = DeploymentUtil.getDeploymentCreationResult(infrastructureProvisionResult - .getDeploymentScriptsDir()); + DeploymentCreationResult result = DeploymentUtil + .getDeploymentCreationResult(inputParameters.getProperty(WORKSPACE)); result.setName(deploymentPatternConfig.getName()); List<Host> hosts = new ArrayList<>();
['deployment/src/main/java/org/wso2/testgrid/deployment/DeploymentUtil.java', 'deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java']
{'.java': 2}
2
2
0
0
2
679,410
139,882
18,597
158
2,712
483
44
2
242
34
56
8
0
0
"1970-01-01T00:25:21"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
959
wso2/testgrid/632/630
wso2
testgrid
https://github.com/wso2/testgrid/issues/630
https://github.com/wso2/testgrid/pull/632
https://github.com/wso2/testgrid/pull/632
1
resolves
Scenario tests execution hangs
**Description:** Scenario test execution hangs just after the server startup. **Affected Product Version:** 0.9.0-m18 **OS, DB, other environment details and versions:** N/A **Steps to reproduce:** - Generate test palns - Execute one test-plan
80d30411fe3ec9b365e1fc9b56b69cbc4f94699e
10935b85529ab1ceb124ecee2e0827c002b9901d
https://github.com/wso2/testgrid/compare/80d30411fe3ec9b365e1fc9b56b69cbc4f94699e...10935b85529ab1ceb124ecee2e0827c002b9901d
diff --git a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java index e1e98acf..1f995f53 100644 --- a/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java +++ b/deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java @@ -99,7 +99,7 @@ public class ShellDeployer implements Deployer { List<Host> hosts = new ArrayList<>(); Host tomcatHost = new Host(); tomcatHost.setLabel("tomcatHost"); - tomcatHost.setIp("ec2-52-54-230-106.compute-1.amazonaws.com"); + tomcatHost.setIp("ec2-34-204-80-18.compute-1.amazonaws.com"); Host tomcatPort = new Host(); tomcatPort.setLabel("tomcatPort"); tomcatPort.setIp("8080"); diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java index 4d78340a..7bd356fa 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java @@ -211,7 +211,7 @@ public class AWSProvider implements InfrastructureProvider { List<Host> hosts = new ArrayList<>(); Host tomcatHost = new Host(); tomcatHost.setLabel("tomcatHost"); - tomcatHost.setIp("ec2-52-54-230-106.compute-1.amazonaws.com"); + tomcatHost.setIp("ec2-34-204-80-18.compute-1.amazonaws.com"); Host tomcatPort = new Host(); tomcatPort.setLabel("tomcatPort"); tomcatPort.setIp("8080");
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java', 'deployment/src/main/java/org/wso2/testgrid/deployment/deployers/ShellDeployer.java']
{'.java': 2}
2
2
0
0
2
680,721
140,131
18,624
158
292
92
4
2
264
33
62
13
0
0
"1970-01-01T00:25:22"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
958
wso2/testgrid/648/647
wso2
testgrid
https://github.com/wso2/testgrid/issues/647
https://github.com/wso2/testgrid/pull/648
https://github.com/wso2/testgrid/pull/648
1
resolves
generate-test-plan command fails for incomplete testgrid.yaml
**Description:** When testgrid.yaml does not contain scenarioConfig, the file is not ignored. Also, TestGrid does not support config-change-sets yet. Therefore, this missing property in testgrid.yaml should be ignored which otherwise breaks the flow. **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
0a5b2673f0c239ff53d8962ca0101afc3df0643f
0155adcf704b4566d092c94da1bedd129a464fd7
https://github.com/wso2/testgrid/compare/0a5b2673f0c239ff53d8962ca0101afc3df0643f...0155adcf704b4566d092c94da1bedd129a464fd7
diff --git a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java index d1662a38..604f88df 100644 --- a/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java +++ b/core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java @@ -47,6 +47,7 @@ import org.wso2.testgrid.infrastructure.InfrastructureCombinationsProvider; import org.wso2.testgrid.logging.plugins.LogFilePathLookup; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.Tag; @@ -366,7 +367,7 @@ public class GenerateTestPlanCommand implements Command { TestGridConstants.TESTGRID_YAML, " is missing in ", deployRepositoryLocation)); } testgridYamlContent = testgridYamlBuilder.toString().trim(); - if (testgridYamlContent.isEmpty()) { + if (testgridYamlContent.isEmpty() || !testgridYamlContent.contains("scenarioConfig")) { testgridYamlContent = getTestgridYamlFor(Paths.get(testgridYamlLocation)).trim(); } @@ -378,7 +379,12 @@ public class GenerateTestPlanCommand implements Command { + "could not be resolved via the job-config.yaml at: " + this.jobConfigFile); } - TestgridYaml testgridYaml = new Yaml().loadAs(testgridYamlContent, TestgridYaml.class); + Representer representer = new Representer(); + + // Skip missing properties in testgrid.yaml + representer.getPropertyUtils().setSkipMissingProperties(true); + TestgridYaml testgridYaml = new Yaml(new Constructor(TestgridYaml.class), representer) + .loadAs(testgridYamlContent, TestgridYaml.class); testgridYaml.setInfrastructureRepository(jobConfigFile.getInfrastructureRepository()); testgridYaml.setDeploymentRepository(jobConfigFile.getDeploymentRepository()); testgridYaml.setScenarioTestsRepository(jobConfigFile.getScenarioTestsRepository());
['core/src/main/java/org/wso2/testgrid/core/command/GenerateTestPlanCommand.java']
{'.java': 1}
1
1
0
0
1
683,109
140,519
18,696
158
635
144
10
1
328
39
71
12
0
0
"1970-01-01T00:25:22"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
957
wso2/testgrid/656/655
wso2
testgrid
https://github.com/wso2/testgrid/issues/655
https://github.com/wso2/testgrid/pull/656
https://github.com/wso2/testgrid/pull/656
1
resolves
Test scenarios are duplicated
**Description:** Test scenarios are duplicated due to a bug in persistence logic in TestPlanExecutor#runScenarioTests. **Suggested Labels:** Type/Bug, Priority/Highest, Severity/Critical **Suggested Assignees:** AsmaJ
c20c171319026830d24d7af4e71f9bfb18aa35aa
137fde30d25c6ce518340d57321a82ee8ff8de71
https://github.com/wso2/testgrid/compare/c20c171319026830d24d7af4e71f9bfb18aa35aa...137fde30d25c6ce518340d57321a82ee8ff8de71
diff --git a/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java b/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java index 717f9fe5..0d102084 100644 --- a/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java +++ b/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java @@ -115,7 +115,16 @@ public class TestPlanExecutor { * @param deploymentCreationResult the result of the previous build step */ private void runScenarioTests(TestPlan testPlan, DeploymentCreationResult deploymentCreationResult) { + + /* Set dir for scenarios from values matched from test-plan yaml file */ for (TestScenario testScenario : testPlan.getScenarioConfig().getScenarios()) { + for (TestScenario testScenario1 : testPlan.getTestScenarios()) { + if (testScenario.getName().equals(testScenario1.getName())) { + testScenario1.setDir(testScenario.getDir()); + } + } + } + for (TestScenario testScenario : testPlan.getTestScenarios()) { try { scenarioExecutor.execute(testScenario, deploymentCreationResult, testPlan); } catch (Exception e) {
['core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java']
{'.java': 1}
1
1
0
0
1
683,514
140,597
18,703
158
424
80
9
1
232
22
52
11
0
0
"1970-01-01T00:25:22"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
956
wso2/testgrid/668/667
wso2
testgrid
https://github.com/wso2/testgrid/issues/667
https://github.com/wso2/testgrid/pull/668
https://github.com/wso2/testgrid/pull/668
1
resolve
Stack deletion does not get notified to the TestGrid
**Description:** TestGrid waits indefinitely for stack delete response from AWS waiters. This causes the build jobs to hang in stack deletion request forever. **Affected Product Version:** 0.9.0-m20 **Steps to reproduce:** 1. Run a job in TestGrid dev or prod environments 2. Check for stack delete request 3. TestGrid stucks in the same place even though the stack has deleted
c43d090816993eec8c07f7fa28901133a07ef4a7
3c080d603f7a40b90907c2017427816d6fad6918
https://github.com/wso2/testgrid/compare/c43d090816993eec8c07f7fa28901133a07ef4a7...3c080d603f7a40b90907c2017427816d6fad6918
diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java index 3f407582..5defdaba 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java @@ -271,7 +271,8 @@ public class AWSProvider implements InfrastructureProvider { Waiter<DescribeStacksRequest> describeStacksRequestWaiter = new AmazonCloudFormationWaiters(stackdestroy).stackDeleteComplete(); try { - describeStacksRequestWaiter.run(new WaiterParameters<>(new DescribeStacksRequest())); + describeStacksRequestWaiter.run(new WaiterParameters<>(new DescribeStacksRequest() + .withStackName(stackName))); } catch (WaiterUnrecoverableException e) { throw new TestGridInfrastructureException("Error occured while waiting for Stack :" + stackName + " deletion !");
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java']
{'.java': 1}
1
1
0
0
1
684,010
140,686
18,713
158
244
46
3
1
390
59
87
11
0
0
"1970-01-01T00:25:23"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
955
wso2/testgrid/717/716
wso2
testgrid
https://github.com/wso2/testgrid/issues/716
https://github.com/wso2/testgrid/pull/717
https://github.com/wso2/testgrid/pull/717
1
fix
[AWS] Test grid infrastructure creation failed when AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not in environment variables.
**Description:** Test grid infrastructure creation failed with following exception when AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not in environment variables. Ideally this values should take from config.properties file. ``` [10:25:59,137] Error on infrastructure creation for deployment pattern 'DeploymentPattern{id='1478f023-d8de-4af2-bab9-b9aff640106c', name='default', createdTimestamp='2018-04-24 09:25:52.0', modifiedTimestamp='2018-04-24 09:25:52.0', product='Product{id='5a5236f4-ab8b-4dad-9838-a1e02e2e876e', name='WSOIS-5.4.0', createdTimestamp='2018-04-24 09:25:52.0', modifiedTimestamp='2018-04-24 09:25:52.0'}'}', in TestPlan org.wso2.testgrid.common.exception.TestGridInfrastructureException: AWS Credentials must be set as environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY at org.wso2.testgrid.infrastructure.providers.AWSProvider.init(AWSProvider.java:110) at org.wso2.testgrid.core.TestPlanExecutor.provisionInfrastructure(TestPlanExecutor.java:213) at org.wso2.testgrid.core.TestPlanExecutor.execute(TestPlanExecutor.java:82) at org.wso2.testgrid.core.command.RunTestPlanCommand.executeTestPlan(RunTestPlanCommand.java:222) at org.wso2.testgrid.core.command.RunTestPlanCommand.execute(RunTestPlanCommand.java:118) at org.wso2.testgrid.core.command.CommandHandler.execute(CommandHandler.java:124) at org.wso2.testgrid.core.Main.main(Main.java:47) ``` **Suggested Labels:** Type/Bug **Suggested Assignees:** charithag **Affected Product Version:** 0.9.0-m22 **OS, DB, other environment details and versions:** Ubuntu x64 16.04.4 LTS, JDK 1.8.0_171-b11, MySQL 5.7.21 **Steps to reproduce:** Follow Quick Start Guide on newly created instance. https://github.com/wso2/testgrid/blob/master/docs/QuickStartGuide.md **Related Issues:** https://github.com/wso2/testgrid/issues/510
4533088b1b80c8c755ebafff47d13510e9a8997e
f97d764535bc9e273e345d14eb381995382274a7
https://github.com/wso2/testgrid/compare/4533088b1b80c8c755ebafff47d13510e9a8997e...f97d764535bc9e273e345d14eb381995382274a7
diff --git a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java index 56877875..af0a5e54 100644 --- a/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java +++ b/infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java @@ -74,8 +74,6 @@ import java.util.concurrent.TimeUnit; */ public class AWSProvider implements InfrastructureProvider { - public static final String AWS_ACCESS_KEY_ID = "AWS_ACCESS_KEY_ID"; - public static final String AWS_SECRET_ACCESS_KEY = "AWS_SECRET_ACCESS_KEY"; private static final String AWS_PROVIDER = "AWS"; private static final Logger logger = LoggerFactory.getLogger(AWSProvider.class); private static final String AWS_REGION_PARAMETER = "region"; @@ -103,13 +101,6 @@ public class AWSProvider implements InfrastructureProvider { @Override public void init() throws TestGridInfrastructureException { - String awsIdentity = System.getenv(AWS_ACCESS_KEY_ID); - String awsSecret = System.getenv(AWS_SECRET_ACCESS_KEY); - if (StringUtil.isStringNullOrEmpty(awsIdentity) || StringUtil.isStringNullOrEmpty(awsSecret)) { - throw new TestGridInfrastructureException(StringUtil - .concatStrings("AWS Credentials must be set as environment variables: ", AWS_ACCESS_KEY_ID, - ", ", AWS_SECRET_ACCESS_KEY)); - } cfScriptPreprocessor = new CloudFormationScriptPreprocessor(); amiMapper = new AMIMapper(); } diff --git a/infrastructure/src/test/java/org/wso2/testgrid/infrastructure/AWSProviderTest.java b/infrastructure/src/test/java/org/wso2/testgrid/infrastructure/AWSProviderTest.java index f472f69f..b0aa2b41 100644 --- a/infrastructure/src/test/java/org/wso2/testgrid/infrastructure/AWSProviderTest.java +++ b/infrastructure/src/test/java/org/wso2/testgrid/infrastructure/AWSProviderTest.java @@ -72,6 +72,8 @@ import java.util.Set; }) public class AWSProviderTest extends PowerMockTestCase { + private static final String AWS_ACCESS_KEY_ID = "AWS_ACCESS_KEY_ID"; + private static final String AWS_SECRET_ACCESS_KEY = "AWS_SECRET_ACCESS_KEY"; private static final String AWS_ACCESS_KEY_ID_VALUE = "aws_key_value"; private static final String AWS_SECRET_ACCESS_KEY_VALUE = "aws_secret_value"; @@ -83,8 +85,8 @@ public class AWSProviderTest extends PowerMockTestCase { public void testManagerCreation() throws Exception { //set environment variables for Map<String, String> map = new HashMap<>(); - map.put(AWSProvider.AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); - map.put(AWSProvider.AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); + map.put(AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); + map.put(AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); set(map); AMIMapper awsAMIMapper = Mockito.mock(AMIMapper.class); PowerMockito.whenNew(AMIMapper.class).withAnyArguments().thenReturn(awsAMIMapper); @@ -103,7 +105,7 @@ public class AWSProviderTest extends PowerMockTestCase { InterruptedException, NoSuchFieldException, IllegalAccessException { String secret2 = "AWS_SCERET2"; Map<String, String> map = new HashMap<>(); - map.put(AWSProvider.AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); + map.put(AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); set(map); //invoke without no secret key environment variable set. AWSProvider awsProvider = new AWSProvider(); @@ -120,8 +122,8 @@ public class AWSProviderTest extends PowerMockTestCase { String matchedAmi = "123464"; Map<String, String> map = new HashMap<>(); - map.put(AWSProvider.AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); - map.put(AWSProvider.AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); + map.put(AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); + map.put(AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); set(map); InfrastructureConfig infrastructureConfig = getDummyInfrastructureConfig(patternName); @@ -208,8 +210,8 @@ public class AWSProviderTest extends PowerMockTestCase { //set environment variables for Map<String, String> map = new HashMap<>(); - map.put(AWSProvider.AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); - map.put(AWSProvider.AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); + map.put(AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID_VALUE); + map.put(AWS_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY_VALUE); set(map); InfrastructureConfig dummyInfrastructureConfig = getDummyInfrastructureConfig(patternName); File resourcePath = new File("src/test/resources");
['infrastructure/src/main/java/org/wso2/testgrid/infrastructure/providers/AWSProvider.java', 'infrastructure/src/test/java/org/wso2/testgrid/infrastructure/AWSProviderTest.java']
{'.java': 2}
2
2
0
0
2
686,547
141,129
18,758
158
638
119
9
1
1,860
115
508
32
2
1
"1970-01-01T00:25:24"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
952
wso2/testgrid/868/867
wso2
testgrid
https://github.com/wso2/testgrid/issues/867
https://github.com/wso2/testgrid/pull/868
https://github.com/wso2/testgrid/pull/868
1
fixes
Change integration-test log file path as to refer from databucket
**Description:** With the introduction of data-buckets, the integration-test log file is downloaded to the data-bucket of the relevant build. So the report generator must refer the log from there. <!-- Give a brief description of the issue --> **Suggested Labels:** Bug <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees:** pasindujw <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees--> **Affected Product Version:** m34
cf1d8174dfb0d11522d98a04a43da8c7886b3241
78d94ea51c25fc089978292cb6fb58198d619623
https://github.com/wso2/testgrid/compare/cf1d8174dfb0d11522d98a04a43da8c7886b3241...78d94ea51c25fc089978292cb6fb58198d619623
diff --git a/common/src/main/java/org/wso2/testgrid/common/util/TestGridUtil.java b/common/src/main/java/org/wso2/testgrid/common/util/TestGridUtil.java index 59f676db..f44d1825 100755 --- a/common/src/main/java/org/wso2/testgrid/common/util/TestGridUtil.java +++ b/common/src/main/java/org/wso2/testgrid/common/util/TestGridUtil.java @@ -446,22 +446,14 @@ public final class TestGridUtil { } /** - * Returns the path of the integration test log file. + * Returns the absolute path of the integration test log file. * * @param testPlan test-plan - * @param relative Whether the path need to be returned relative to testgrid.home or not * @return log file path */ - public static String deriveTestIntegrationLogFilePath(TestPlan testPlan, Boolean relative) + public static String deriveTestIntegrationLogFilePath(TestPlan testPlan) throws TestGridException { - String productName = testPlan.getDeploymentPattern().getProduct().getName(); - String testPlanDirName = TestGridUtil.deriveTestPlanDirName(testPlan); - String dirPrefix = ""; - if (!relative) { - dirPrefix = getTestGridHomePath(); - } - return Paths.get(dirPrefix, TestGridConstants.TESTGRID_JOB_DIR, productName, - TestGridConstants.TESTGRID_BUILDS_DIR, testPlanDirName, + return Paths.get(DataBucketsHelper.getOutputLocation(testPlan).toString(), TestGridConstants.TEST_INTEGRATION_LOG_FILE_NAME).toString(); } diff --git a/reporting/src/main/java/org/wso2/testgrid/reporting/EmailReportProcessor.java b/reporting/src/main/java/org/wso2/testgrid/reporting/EmailReportProcessor.java index e57b4fb0..e4841fe3 100644 --- a/reporting/src/main/java/org/wso2/testgrid/reporting/EmailReportProcessor.java +++ b/reporting/src/main/java/org/wso2/testgrid/reporting/EmailReportProcessor.java @@ -109,7 +109,7 @@ public class EmailReportProcessor { StringBuilder stringBuilder = new StringBuilder(); Path filePath; try { - filePath = Paths.get(TestGridUtil.deriveTestIntegrationLogFilePath(testPlan, false)); + filePath = Paths.get(TestGridUtil.deriveTestIntegrationLogFilePath(testPlan)); } catch (TestGridException e) { throw new ReportingException("Error occurred while deriving integration-test log file path to get" + " integration test results for test-plan with id " + testPlan.getId() + "of the product " +
['common/src/main/java/org/wso2/testgrid/common/util/TestGridUtil.java', 'reporting/src/main/java/org/wso2/testgrid/reporting/EmailReportProcessor.java']
{'.java': 2}
2
2
0
0
2
977,938
199,833
26,243
221
1,110
219
16
2
775
113
159
16
0
0
"1970-01-01T00:25:31"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
977
wso2/testgrid/358/359
wso2
testgrid
https://github.com/wso2/testgrid/issues/359
https://github.com/wso2/testgrid/pull/358
https://github.com/wso2/testgrid/pull/358
1
resolves
Thread hangs when a shell command is executed
**Description:** Thread hangs when a shell command is executed. The shutdown method is not called in the ShellExecutor.
8ea5d2b2613dc60495420e7328c035a97596fb25
caaab90e28d7b145128a1ce6a581876549dd8f0e
https://github.com/wso2/testgrid/compare/8ea5d2b2613dc60495420e7328c035a97596fb25...caaab90e28d7b145128a1ce6a581876549dd8f0e
diff --git a/common/src/main/java/org/wso2/testgrid/common/ShellExecutor.java b/common/src/main/java/org/wso2/testgrid/common/ShellExecutor.java index d0be5ae9..e3acb5a6 100644 --- a/common/src/main/java/org/wso2/testgrid/common/ShellExecutor.java +++ b/common/src/main/java/org/wso2/testgrid/common/ShellExecutor.java @@ -30,6 +30,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; @@ -96,6 +97,8 @@ public class ShellExecutor { logger.debug("Running shell command : " + command + ", from directory : " + workingDirectory.toString()); } ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { if (workingDirectory != null) { File workDirectory = workingDirectory.toFile(); @@ -107,8 +110,9 @@ public class ShellExecutor { StreamGobbler outputStreamGobbler = new StreamGobbler(process.getInputStream(), logger::info); StreamGobbler errorStreamGobbler = new StreamGobbler(process.getErrorStream(), logger::error); - Executors.newSingleThreadExecutor().submit(outputStreamGobbler); - Executors.newSingleThreadExecutor().submit(errorStreamGobbler); + + executor.submit(outputStreamGobbler); + executor.submit(errorStreamGobbler); return process.waitFor() == 0; @@ -120,6 +124,8 @@ public class ShellExecutor { throw new CommandExecutionException( "InterruptedException occurred while executing the command '" + command + "', " + "from directory '" + workingDirectory.toString(), e); + } finally { + executor.shutdownNow(); } } }
['common/src/main/java/org/wso2/testgrid/common/ShellExecutor.java']
{'.java': 1}
1
1
0
0
1
464,989
96,066
13,103
111
432
74
10
1
123
18
25
3
0
0
"1970-01-01T00:25:16"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
964
wso2/testgrid/595/594
wso2
testgrid
https://github.com/wso2/testgrid/issues/594
https://github.com/wso2/testgrid/pull/595
https://github.com/wso2/testgrid/pull/595
1
resolves
Tests fail in testgrid-core
**Description:** Build in jenkins goes unstable due to failing tests in org.wso2.testgrid.core **Suggested Labels:** Type/Bug **Suggested Assignees:** AsmaJ
3e1232968b9af122c72475918646e24d5e3e95d7
173192e349ea28486992c4dfb56aaf96f430e109
https://github.com/wso2/testgrid/compare/3e1232968b9af122c72475918646e24d5e3e95d7...173192e349ea28486992c4dfb56aaf96f430e109
diff --git a/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java b/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java index a11f1d4f..1951d5c1 100644 --- a/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java +++ b/core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java @@ -90,7 +90,6 @@ public class TestPlanExecutor { for (TestScenario testScenario : testPlan.getTestScenarios()) { testScenario.setStatus(Status.DID_NOT_RUN); } - TestPlanUOW testPlanUOW = new TestPlanUOW(); testPlanUOW.persistTestPlan(testPlan); logger.error(StringUtil.concatStrings( "Error occurred while performing deployment for test plan", testPlan.getId(),
['core/src/main/java/org/wso2/testgrid/core/TestPlanExecutor.java']
{'.java': 1}
1
1
0
0
1
676,163
139,235
18,519
158
57
16
1
1
165
18
43
8
0
0
"1970-01-01T00:25:21"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
948
wso2/testgrid/1030/1029
wso2
testgrid
https://github.com/wso2/testgrid/issues/1029
https://github.com/wso2/testgrid/pull/1030
https://github.com/wso2/testgrid/pull/1030
1
resolves
Test results download in the dashboard fails
**Description:** Test results download in the dashboard fails though results exist in S3.
893b828a05d1459712d2c7161f703c66ce384a9e
e2a9caa04bfaafe86e944e658a3dad69e7366612
https://github.com/wso2/testgrid/compare/893b828a05d1459712d2c7161f703c66ce384a9e...e2a9caa04bfaafe86e944e658a3dad69e7366612
diff --git a/common/src/main/java/org/wso2/testgrid/common/plugins/AWSArtifactReader.java b/common/src/main/java/org/wso2/testgrid/common/plugins/AWSArtifactReader.java index 5eb25ee4..e9e2c698 100644 --- a/common/src/main/java/org/wso2/testgrid/common/plugins/AWSArtifactReader.java +++ b/common/src/main/java/org/wso2/testgrid/common/plugins/AWSArtifactReader.java @@ -104,6 +104,7 @@ public class AWSArtifactReader implements ArtifactReadable { @Override public Boolean isArtifactExist(String key) { - return amazonS3.doesObjectExist(bucketName, key); + return amazonS3.doesObjectExist(bucketName, key) || + amazonS3.listObjectsV2(bucketName, key).getKeyCount() > 0; } }
['common/src/main/java/org/wso2/testgrid/common/plugins/AWSArtifactReader.java']
{'.java': 1}
1
1
0
0
1
1,272,540
257,995
33,471
258
195
50
3
1
94
13
18
4
0
0
"1970-01-01T00:25:39"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0
981
wso2/testgrid/220/219
wso2
testgrid
https://github.com/wso2/testgrid/issues/219
https://github.com/wso2/testgrid/pull/220
https://github.com/wso2/testgrid/pull/220
1
resolves
Parameters have extra surrounding spaces
**Description:** Parameters that are replaced in the jmx files contain extra spaces.
6fb276850d70afaefbacd0a232f95c236ae5eb5c
55f818fe877849eaea285d733d52960cd2606735
https://github.com/wso2/testgrid/compare/6fb276850d70afaefbacd0a232f95c236ae5eb5c...55f818fe877849eaea285d733d52960cd2606735
diff --git a/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterExecutor.java b/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterExecutor.java index 27c6c685..d4a68cbd 100644 --- a/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterExecutor.java +++ b/automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterExecutor.java @@ -205,7 +205,7 @@ public class JMeterExecutor extends TestExecutor { Enumeration<?> enumeration = jMeterProperties.propertyNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); - jmx = jmx.replaceAll("\\\\$\\\\{__property\\\\(" + name + "\\\\)\\\\}", JMeterUtils.getProperty(name)); + jmx = jmx.replaceAll("\\\\$\\\\{__property\\\\(" + name + "\\\\)\\\\}", JMeterUtils.getProperty(name).trim()); } String[] split = script.split(File.separatorChar == '\\\\' ? "\\\\\\\\" : File.separator); StringBuilder buffer = new StringBuilder();
['automation/src/main/java/org/wso2/testgrid/automation/executor/JMeterExecutor.java']
{'.java': 1}
1
1
0
0
1
440,662
91,613
12,516
109
228
58
2
1
89
12
17
4
0
0
"1970-01-01T00:25:13"
29
Java
{'Java': 1684597, 'Shell': 197778, 'Python': 51092, 'Mustache': 50400, 'Groovy': 12493, 'Dockerfile': 11869, 'CSS': 2656, 'PowerShell': 2278, 'Batchfile': 806, 'HTML': 515}
Apache License 2.0