method2testcases
stringlengths
118
6.63k
### Question: TimeDuration { public static Duration ofMinutes(double min) { return Duration.ofNanos((long) (min * 60 * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }### Answer: @Test public void min1() { Duration duration = TimeDuration.ofMinutes(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(60L)); } @Test public void min2() { Duration duration = TimeDuration.ofMinutes(0.123456789); assertThat(duration.getNano(), equalTo(407407340)); assertThat(duration.getSeconds(), equalTo(7L)); } @Test public void min3() { Duration duration = TimeDuration.ofMinutes(-1.23456789); assertThat(duration.getNano(), equalTo(925926601)); assertThat(duration.getSeconds(), equalTo(-75L)); }
### Question: TimeDuration { public static Duration ofHours(double hour) { return Duration.ofNanos((long) (hour * 60 * 60 * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }### Answer: @Test public void hour1() { Duration duration = TimeDuration.ofHours(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(3600L)); } @Test public void hour2() { Duration duration = TimeDuration.ofHours(0.123456789); assertThat(duration.getNano(), equalTo(444440399)); assertThat(duration.getSeconds(), equalTo(444L)); } @Test public void hour3() { Duration duration = TimeDuration.ofHours(-1.23456789); assertThat(duration.getNano(), equalTo(555596001)); assertThat(duration.getSeconds(), equalTo(-4445L)); }
### Question: TimeDuration { public static Duration ofHertz(double hz) { if (hz <= 0.0) { throw new IllegalArgumentException("Frequency has to be greater than 0.0"); } return Duration.ofNanos((long) (1000000000.0 / hz)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }### Answer: @Test public void hz1() { Duration duration = TimeDuration.ofHertz(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(1L)); } @Test public void hz2() { Duration duration = TimeDuration.ofHertz(100.0); assertThat(duration.getNano(), equalTo(10000000)); assertThat(duration.getSeconds(), equalTo(0L)); } @Test public void hz3() { Duration duration = TimeDuration.ofHertz(0.123456789); assertThat(duration.getNano(), equalTo(100000073)); assertThat(duration.getSeconds(), equalTo(8L)); }
### Question: Services implements IServices { @Override @Transactional public Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs) { logger.info("Updating configuration unique id: {}", configToUpdate.getUniqueId()); return nodeDAO.updateConfiguration(configToUpdate, configPvs); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testUpdateConfiguration() { when(nodeDAO.updateConfiguration(config1, configPvList)).thenReturn(config1); assertNotNull(services.updateConfiguration(config1, configPvList)); }
### Question: Services implements IServices { @Override public List<SnapshotItem> getSnapshotItems(String snapshotUniqueId) { logger.info("Getting snapshot items for snapshot id {}", snapshotUniqueId); return nodeDAO.getSnapshotItems(snapshotUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetSnapshotItems() { when(nodeDAO.getSnapshotItems("a")).thenReturn(Collections.emptyList()); assertNotNull(services.getSnapshotItems("a")); }
### Question: TimeDuration { public static String toSecondString(Duration duration){ return duration.getSeconds() + "." + format.format(duration.getNano()); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }### Answer: @Test public void toString1() { Duration duration = Duration.ofMillis(10); assertThat(TimeDuration.toSecondString(duration), equalTo("0.010000000")); }
### Question: Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testgetParentNode() { Node parentNode = Node.builder().name("a").uniqueId("u").build(); when(nodeDAO.getParentNode("u")).thenReturn(parentNode); assertNotNull(services.getParentNode("u")); }
### Question: TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void equals1() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)); assertThat(interval, equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)))); } @Test public void equals2() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 1), Instant.ofEpochSecond(3600, 0)); assertThat(interval, not(equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0))))); } @Test public void equals3() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 1)); assertThat(interval, not(equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0))))); } @Test public void equals4() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), null); assertThat(interval, equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), null))); } @Test public void equals5() { TimeInterval interval = TimeInterval.between(null, Instant.ofEpochSecond(0, 0)); assertThat(interval, equalTo(TimeInterval.between(null, Instant.ofEpochSecond(0, 0)))); }
### Question: Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetChildNodes() { when(nodeDAO.getChildNodes("a")).thenReturn(Arrays.asList(Node.builder().build())); assertNotNull(services.getChildNodes("a")); }
### Question: TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }### Answer: @Test public void getNow() { Instant ts = TimeParser.getInstant("now"); assertTrue("Failed to obtain Timestamp corresponding to now ", ts != null && ts instanceof Instant); }
### Question: TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }### Answer: @Test public void getDuration() { Duration lastMin = TimeParser.parseDuration("1 min"); assertEquals("Failed to get Duration for last min", Duration.ofSeconds(60), lastMin); Duration lastHour = TimeParser.parseDuration("1 hour"); assertEquals("Failed to get Duration for last hour", Duration.ofHours(1), lastHour); TemporalAmount last5Min = TimeParser.parseDuration(" 5 mins"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofMinutes(5), last5Min); TemporalAmount last5Hour = TimeParser.parseDuration(" 5 hours"); assertEquals("Failed to get Duration for last 5 hours", Duration.ofHours(5), last5Hour); Duration last5Day = TimeParser.parseDuration(" 5 days"); assertEquals("Failed to get Duration for last 5 days", 60 * 60 * 24 * 5, last5Day.getSeconds()); } @Test public void parseCompositeTimeString() { TemporalAmount last5Mins30Secs = TimeParser.parseDuration("5 mins 30 secs"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofMinutes(5).plusSeconds(30), last5Mins30Secs); TemporalAmount last3Hours5Mins30Secs = TimeParser.parseDuration("3 hours 5 mins 30 secs"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofHours(3).plusMinutes(5).plusSeconds(30), last3Hours5Mins30Secs); } @Test public void testParseDuration() { TemporalAmount amount = TimeParser.parseDuration("3 days"); final long seconds = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC).plus(amount).toEpochSecond(ZoneOffset.UTC); assertEquals(3*24*60*60, seconds); }
### Question: Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetRootNode() { when(nodeDAO.getRootNode()).thenReturn(Node.builder().build()); assertNotNull(services.getRootNode()); }
### Question: TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }### Answer: @Test public void testFormatTemporalAmount() { String text = TimeParser.format(Duration.ofHours(2)); assertEquals("2 hours", text); text = TimeParser.format(Period.of(1, 2, 3)); assertEquals("1 year 2 months 3 days", text); text = TimeParser.format(Duration.ofSeconds(2*24*60*60 + 1*60*60 + 10, 123000000L)); assertEquals("2 days 1 hour 10 seconds 123 ms", text); text = TimeParser.format(Duration.ofSeconds(0)); assertEquals("now", text); text = TimeParser.format(Period.ZERO); assertEquals("now", text); }
### Question: CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }### Answer: @Test public void testCommandSplit() throws Exception { List<String> cmd = CommandExecutor.splitCmd("path/cmd"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd"))); cmd = CommandExecutor.splitCmd("path/cmd arg1"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "arg1"))); cmd = CommandExecutor.splitCmd("path/cmd arg1 arg2"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "arg1", "arg2"))); cmd = CommandExecutor.splitCmd("path/cmd \"one arg\""); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "one arg"))); cmd = CommandExecutor.splitCmd("path/cmd \"one arg\" arg2 arg3"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "one arg", "arg2", "arg3"))); }
### Question: CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }### Answer: @Test public void testShortCommand() throws Exception { if (is_windows) return; final String cmd = "./cmd_short.sh \"With one arg\" another_arg"; final Integer status = new CommandExecutor(cmd, examples_dir).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Example warning")); assertThat(log, containsString("2 arguments")); assertThat(log, containsString("Finished OK")); assertThat(status, equalTo(0)); } @Test public void testErrorCommand() throws Exception { if (is_windows) return; final Integer status = new CommandExecutor("cmds/cmd_short.sh", examples_dir.getParentFile()).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Wrong directory")); assertThat(log, containsString("exited with status 2")); assertThat(status, equalTo(2)); }
### Question: ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } static URI createResourceURI(final String resource); static File getFile(final URI resource); static URI getURI(final File file); static InputStream getContent(final URI resource); static List<String> parsePVs(final URI resource); static String getAppName(final URI resource); static String getTargetName(final URI resource); static Stream<Map.Entry<String, String>> getQueryItemStream(final URI resource); static Map<String, List<String>> parseQueryArgs(final URI resource); static String encode(final String text); static final String PV_SCHEMA; }### Answer: @Test public void checkWebToURI() throws Exception { URI uri = createResourceURI("http: System.out.println(uri); assertThat(uri.getScheme(), equalTo("http")); assertThat(uri.getHost(), equalTo("some.site")); assertThat(uri.getPath(), equalTo("/file/path")); }
### Question: SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testSimProposal() { Proposal proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sine"), equalTo("sim: assertThat(proposal.apply("sim: equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2)"), equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2"), equalTo("sim: proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sin(-10,10, 0.1, 2 )"), equalTo("sim: }
### Question: SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testMatch() { Proposal proposal = new SimProposal("sim: List<MatchSegment> match = proposal.getMatch("sine"); assertThat(match, equalTo(List.of(MatchSegment.normal("sim: MatchSegment.match("sine"), MatchSegment.comment("(min, max, update_seconds)")))); match = proposal.getMatch("sim: assertThat(match, equalTo(List.of(MatchSegment.match("sim: MatchSegment.comment("(min, max, update_seconds)")))); match = proposal.getMatch("sine(2, 4,"); System.out.println("sine(2, 4,"); for (MatchSegment m : match) System.out.println(m); assertThat(match, equalTo(List.of(MatchSegment.normal("sim: MatchSegment.match("sine"), MatchSegment.match("(2,", "(min,"), MatchSegment.match(" 4,", "max,"), MatchSegment.comment("update_seconds)")))); match = proposal.getMatch("sim: System.out.println("sim: for (MatchSegment m : match) System.out.println(m); assertThat(match, equalTo(List.of(MatchSegment.match("sim: MatchSegment.match("(-10,", "(min,"), MatchSegment.match(" 10,", "max,"), MatchSegment.match(" 2)", "update_seconds)")))); }
### Question: History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); @Override String getName(); synchronized void add(final Proposal proposal); @Override synchronized List<Proposal> lookup(String text); }### Answer: @Test public void testHistory() { final History history = new History(); List<Proposal> proposals = history.lookup("test"); assertThat(proposals.size(), equalTo(0)); history.add(new Proposal("Test1")); history.add(new Proposal("Other")); history.add(new Proposal("Test2")); proposals = history.lookup("test"); assertThat(getValues(proposals), hasItems("Test1", "Test2")); assertThat(getValues(proposals), equalTo(List.of("Test2", "Test1"))); proposals = history.lookup("ther"); assertThat(getValues(proposals), equalTo(List.of("Other"))); assertThat(proposals.get(0).apply("ther"), equalTo("Other")); }
### Question: FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testMatch() { Proposal proposal = new FormulaFunctionProposal(new Sin()); List<MatchSegment> match = proposal.getMatch("=sin("); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.comment("", "angle")))); match = proposal.getMatch("=sin(2)"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.match("2", "angle"), MatchSegment.match(")")))); match = proposal.getMatch("=2 + sin(1-1) + 3"); assertThat(match, equalTo(List.of(MatchSegment.normal("=2 + "), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.match("1-1", "angle"), MatchSegment.match(")"), MatchSegment.normal(" + 3")))); } @Test public void testVarArg() { Proposal proposal = new FormulaFunctionProposal(new StringFunction()); List<MatchSegment> match = proposal.getMatch("=concat(a, b) + 2"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("concat"), MatchSegment.match("(a, b)"), MatchSegment.normal(" + 2")))); match = proposal.getMatch("=concat(a, b + 2"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("concat"), MatchSegment.match("(a, b + 2"), MatchSegment.comment(")")))); }
### Question: Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetConfigPvs() { when(nodeDAO.getConfigPvs("a")).thenReturn(Arrays.asList(ConfigPv.builder().build())); assertNotNull(services.getConfigPvs("a")); }
### Question: ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } @SuppressWarnings("unchecked") static ScanCommandImpl<C> implement(final C command, final JythonSupport jython); static List<ScanCommandImpl<?>> implement(final List<ScanCommand> commands, final JythonSupport jython); }### Answer: @Test public void testImplementation() throws Exception { final ScanCommand cmd = new CommentCommand("Test"); final ScanCommandImpl<ScanCommand> impl = ScanCommandImplTool.implement(cmd, null); System.out.println(impl); assertThat(impl, instanceOf(CommentCommandImpl.class)); }
### Question: Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }### Answer: @Test public void testPlainProposal() { Proposal proposal = new Proposal("Test1"); assertThat(proposal.apply("est"), equalTo("Test1")); assertThat(proposal.apply("anything"), equalTo("Test1")); }
### Question: Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }### Answer: @Test public void testMatch() { Proposal proposal = new Proposal("Test1"); List<MatchSegment> match = proposal.getMatch("es"); assertThat(match, equalTo(List.of(MatchSegment.normal("T"), MatchSegment.match("es"), MatchSegment.normal("t1")))); match = proposal.getMatch("Tes"); assertThat(match, equalTo(List.of(MatchSegment.match("Tes"), MatchSegment.normal("t1")))); }
### Question: LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testArguments() { List<String> split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: }
### Question: LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testLocProposal() { Proposal proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: }
### Question: LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer: @Test public void testMatch() { Proposal proposal = new LocProposal("loc: List<MatchSegment> match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.comment("<VType>"), MatchSegment.comment("(initial value)")))); match = proposal.getMatch(""); assertThat(match, equalTo(List.of( MatchSegment.normal("loc: match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.normal("<Type>"), MatchSegment.comment("(initial value)")))); match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.comment("<VType>"), MatchSegment.match("(42)", "(initial value)")))); }
### Question: PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } PreferencesReader(final Class<?> package_class, final String preferences_properties_filename); Set<String> getKeys(final String regex); String get(final String key); boolean getBoolean(final String key); int getInt(final String key); double getDouble(final String key); }### Answer: @Test public void testProperties() { System.out.println(PreferencesReader.replaceProperties("Running on Java $(java.version) in $(java.home)")); System.out.println("Expect warning about undefined property"); assertThat(PreferencesReader.replaceProperties("$(VeryUnlikelyToExist)"), equalTo("$(VeryUnlikelyToExist)")); System.setProperty("test", "OK"); assertThat(PreferencesReader.replaceProperties("$(test)"), equalTo("OK")); assertThat(PreferencesReader.replaceProperties("This is $(test)"), equalTo("This is OK")); }
### Question: UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update, final ScheduledExecutorService timer); void setDormantTime(final long dormant_time, final TimeUnit unit); void trigger(); void dispose(); static final ScheduledExecutorService TIMER; }### Answer: @Test(timeout=5000) public void testUpdateThrottle() throws Exception { final Runnable update = new Runnable() { @Override public void run() { System.out.println("<- Update!"); updates.incrementAndGet(); synchronized (this) { notifyAll(); } } }; final UpdateThrottle throttle = new UpdateThrottle(1L, TimeUnit.SECONDS, update); assertThat(updates.get(), equalTo(0)); System.out.println("-> Trigger.."); throttle.trigger(); Thread.sleep(100); assertThat(updates.get(), equalTo(1)); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); assertThat(updates.get(), equalTo(1)); TimeUnit.SECONDS.sleep(2); assertThat(updates.get(), equalTo(2)); throttle.setDormantTime(500, TimeUnit.MILLISECONDS); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); TimeUnit.MILLISECONDS.sleep(500); assertThat(updates.get(), equalTo(4)); }
### Question: Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testSaveSnapshot() { when(nodeDAO.saveSnapshot("a", Collections.emptyList(), "b", "c", "d")).thenReturn(Node.builder().nodeType(NodeType.SNAPSHOT).build()); assertNotNull(services.saveSnapshot("a", Collections.emptyList(), "b", "d", "c")); }
### Question: Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetFromPath(){ Node node = Node.builder().name("SomeFolder").build(); when(nodeDAO.getFromPath("path")).thenReturn(Arrays.asList(node)); assertEquals("SomeFolder", services.getFromPath("path").get(0).getName()); }
### Question: ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute(){ ArrayScalarDivisionFunction arrayScalarDivisionFunction = new ArrayScalarDivisionFunction(); assertEquals("arrayDivScalar", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(array, factor); assertEquals(3, result.getData().size()); assertEquals(1, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(15, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
### Question: ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayMinFunction arrayMinFunction = new ArrayMinFunction(); assertEquals("arrayMin", arrayMinFunction.getName()); assertEquals("array", arrayMinFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(-1.0, 0, 1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble min = (VDouble) arrayMinFunction.compute(doubleArray); assertEquals("arrayMin Failed to calculate min for double array", Double.valueOf(-1.0), min.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(-1, 0, 1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); min = (VDouble) arrayMinFunction.compute(intArray); assertEquals("arrayMin Failed to calculate min for int array", Double.valueOf(-1), min.getValue()); }
### Question: ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void computeString() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VStringArray.of(List.of("a", "b", "c")); VString vString = (VString) elementAtNumberFunction.compute(array, index); assertEquals("c", vString.getValue()); vString = (VString)elementAtNumberFunction.compute(array, array); assertEquals("", vString.getValue()); } @Test(expected = Exception.class) public void invalidArguments1() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(8.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); elementAtNumberFunction.compute(array, index); } @Test(expected = Exception.class) public void invalidArguments2() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(-1.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); elementAtNumberFunction.compute(array, index); }
### Question: ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayOfFunction arrayOfFunction = new ArrayOfFunction(); assertEquals("arrayOf", arrayOfFunction.getName()); assertEquals("array", arrayOfFunction.getCategory()); VString a = VString.of("a", Alarm.none(), Time.now()); VString b = VString.of("b", Alarm.none(), Time.now()); VString c = VString.of("c", Alarm.none(), Time.now()); VStringArray vStringArray = (VStringArray)arrayOfFunction.compute(a, b, c); assertEquals(3, vStringArray.getData().size()); assertEquals("a", vStringArray.getData().get(0)); assertEquals("b", vStringArray.getData().get(1)); assertEquals("c", vStringArray.getData().get(2)); VInt d0 = VInt.of(1, Alarm.none(), Time.now(), Display.none()); VInt d1 = VInt.of(2, Alarm.none(), Time.now(), Display.none()); VInt d2 = VInt.of(3, Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)arrayOfFunction.compute(d0, d1, d2); assertEquals(3, vNumberArray.getData().size()); assertEquals(1, vNumberArray.getData().getInt(0)); assertEquals(2, vNumberArray.getData().getInt(1)); assertEquals(3, vNumberArray.getData().getInt(2)); VEnum vEnum = VEnum.of(0, EnumDisplay.of(), Alarm.none(), Time.now()); vNumberArray = (VNumberArray)arrayOfFunction.compute(vEnum); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
### Question: ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); assertEquals("arrayDiv", arrayDivisionFunction.getName()); assertEquals("array", arrayDivisionFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.none(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 5.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayDivisionFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(6, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayDivisionFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.none(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.none(), Time.now(), Display.none()); arrayDivisionFunction.compute(array1, array2); }
### Question: Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetFullPath(){ when(nodeDAO.getFullPath("nodeId")).thenReturn("/a/b/c"); assertEquals("/a/b/c", nodeDAO.getFullPath("nodeId")); }
### Question: ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayMaxFunction arrayMaxFunction = new ArrayMaxFunction(); assertEquals("arrayMax", arrayMaxFunction.getName()); assertEquals("array", arrayMaxFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble max = (VDouble) arrayMaxFunction.compute(doubleArray); assertEquals("arrayMax Failed to calculate max for double array", Double.valueOf(5), max.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); max = (VDouble) arrayMaxFunction.compute(intArray); assertEquals("arrayMax Failed to calculate max for int array", Double.valueOf(5), max.getValue()); }
### Question: ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); assertEquals("arrayMult", arrayMultiplicationFunction.getName()); assertEquals("array", arrayMultiplicationFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayMultiplicationFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(21, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayMultiplicationFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); arrayMultiplicationFunction.compute(array1, array2); }
### Question: ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayRangeOfFunction arrayRangeOfFunction = new ArrayRangeOfFunction(); assertEquals("arrayRangeOf", arrayRangeOfFunction.getName()); assertEquals("array", arrayRangeOfFunction.getCategory()); Display display = Display.of(Range.of(1d, 10d), Range.of(10d, 20d), Range.of(20d, 30d), Range.of(30d, 40d), "N", new DecimalFormat("")); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), display); VNumberArray range = (VNumberArray)arrayRangeOfFunction.compute(numberArray); assertEquals(1, range.getData().getInt(0)); assertEquals(10, range.getData().getInt(1)); }
### Question: ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }### Answer: @Test public void compute() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); assertEquals("scale", scaleArray.getName()); assertEquals("array", scaleArray.getCategory()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArray.compute(array, factor, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 5); assertTrue(result.getData().getDouble(2) == 7); result = (VNumberArray)scaleArray.compute(array, factor); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); result = (VNumberArray)scaleArray.compute(factor, factor, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongNnumberOfArgumenst1() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array, factor, offset, offset); } @Test(expected = Exception.class) public void testWrongNnumberOfArgumenst2() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array); }
### Question: ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayStatsFunction arrayStatsFunction = new ArrayStatsFunction(); assertEquals("arrayStats", arrayStatsFunction.getName()); assertEquals("array", arrayStatsFunction.getCategory()); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), Display.none()); VStatistics stats = (VStatistics) arrayStatsFunction.compute(numberArray); assertEquals("arrayStats Failed to calculate min", Double.valueOf(1), stats.getMin()); assertEquals("arrayStats Failed to calculate max", Double.valueOf(2), stats.getMax()); }
### Question: ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArraySumFunction scaleArrayFunction = new ArraySumFunction(); assertEquals("arraySum", scaleArrayFunction.getName()); assertEquals("array", scaleArrayFunction.getCategory()); VType offset = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArrayFunction.compute(array, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 5); result = (VNumberArray)scaleArrayFunction.compute(offset, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)scaleArrayFunction.compute(offset, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
### Question: ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayInverseScalarDivisionFunction arrayScalarDivisionFunction = new ArrayInverseScalarDivisionFunction(); assertEquals("arrayDivScalarInv", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 20.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(100.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(factor, array); assertEquals(3, result.getData().size()); assertEquals(50, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(5, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
### Question: ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { ArrayPowFunction arrayPowFunction = new ArrayPowFunction(); assertEquals("arrayPow", arrayPowFunction.getName()); assertEquals("array", arrayPowFunction.getCategory()); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayPowFunction.compute(array, exponent); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 1); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 9); result = (VNumberArray)arrayPowFunction.compute(exponent, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)arrayPowFunction.compute(exponent, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
### Question: HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }### Answer: @Test public void compute() { HistogramOfFunction function = new HistogramOfFunction(); assertEquals("histogramOf", function.getName()); assertEquals("array", function.getCategory()); double[] data = new double[1000]; for(int i = 0; i < 1000; i++){ data[i] = 1.0 * i; } VDoubleArray vDoubleArray = VDoubleArray.of(ArrayDouble.of(data), Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)function.compute(vDoubleArray); assertEquals(100, vNumberArray.getData().size()); assertEquals(10, vNumberArray.getData().getInt(0)); assertEquals(10, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); VNumber vNumber = VInt.of(200, Alarm.none(), Time.now(), Display.none()); vNumberArray = (VNumberArray)function.compute(vDoubleArray, vNumber); assertEquals(200, vNumberArray.getData().size()); assertEquals(5, vNumberArray.getData().getInt(0)); assertEquals(5, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); vNumberArray = (VNumberArray)function.compute(vNumber); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
### Question: SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer: @Test public void compute() throws Exception{ SubArrayFunction subArrayFunction = new SubArrayFunction(); assertEquals("subArray", subArrayFunction.getName()); assertEquals("array", subArrayFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5.0), Alarm.none(), Time.now(), Display.none()); VType from = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VType to = VDouble.of(3.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)subArrayFunction.compute(array, from, to); assertEquals(2, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(3, result.getData().getInt(1)); result = (VNumberArray)subArrayFunction.compute(from, from, to); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); VStringArray stringArray = VStringArray.of(List.of("a", "b", "c", "d", "e")); VStringArray stringResult = (VStringArray) subArrayFunction.compute(stringArray, from, to); assertEquals(2, stringResult.getData().size()); assertEquals("b", stringResult.getData().get(0)); assertEquals("c", stringResult.getData().get(1)); }
### Question: FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }### Answer: @Test public void testEmpty() throws Exception { FieldRequest request = new FieldRequest(""); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); } @Test public void testPlainFields() throws Exception { FieldRequest request = new FieldRequest("field(proton_charge,pixel)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); } @Test public void testSubFields() throws Exception { FieldRequest request = new FieldRequest("field(value, timeStamp.userTag)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); request = new FieldRequest("field(proton_charge,pixel,timeStamp.userTag)"); System.out.println(request); buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); PVATypeRegistry registry = new PVATypeRegistry(); final PVAData decoded = registry.decodeType("", buffer); System.out.println(decoded.formatType()); } @Test public void testPipeline() throws Exception { FieldRequest request = new FieldRequest(10, "field(value)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
### Question: SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test(expected = RuntimeException.class) public void testUnsupportedType() { VEnumArray vEnumArray = VEnumArray.of(ArrayInteger.of(1, 2, 3), EnumDisplay.of("a", "b", "c"), Alarm.none(), Time.now()); SnapshotDataConverter.fromVType(vEnumArray); }
### Question: VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testToDoubles(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double[] result = VTypeHelper.toDoubles(doubleArray); assertEquals(2, result.length); assertEquals(7.7, result[0], 0); assertEquals(8.8, result[1], 0); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDoubles(doubleValue); assertEquals(0, result.length); }
### Question: VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testGetString(){ assertEquals("null", VTypeHelper.toString(null)); VTable table = VTable.of(Arrays.asList(VDouble.class), Arrays.asList("name"), Arrays.asList(ArrayDouble.of(7.7))); assertNotNull(VTypeHelper.toString(table)); VDouble vDouble = VDouble.of(7.7, Alarm.disconnected(), Time.now(), Display.none()); assertNull(VTypeHelper.toString(vDouble)); vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); assertEquals("7.7", VTypeHelper.toString(vDouble)); VEnum enumValue = VEnum.of(0, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertEquals("a", VTypeHelper.toString(enumValue)); assertEquals("b", VTypeHelper.toString(VString.of("b", Alarm.none(), Time.now()))); }
### Question: VTypeHelper { public static boolean isNumericArray(final VType value) { return value instanceof VNumberArray || value instanceof VEnumArray; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testIsNumericArray(){ VDouble vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); assertFalse(VTypeHelper.isNumericArray(vDouble)); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); assertTrue(VTypeHelper.isNumericArray(doubleArray)); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertTrue(VTypeHelper.isNumericArray(enumArray)); }
### Question: VTypeHelper { public static int getArraySize(final VType value) { final ListInteger sizes; if (value instanceof VNumberArray) { sizes = ((VNumberArray) value).getSizes(); } else if (value instanceof VEnumArray) { sizes = ((VEnumArray) value).getSizes(); } else if (value instanceof VStringArray) { sizes = ((VStringArray) value).getSizes(); } else { return 0; } return sizes.size() > 0 ? sizes.getInt(0) : 0; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testGetArraySize(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); assertEquals(2, VTypeHelper.getArraySize(doubleArray)); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertEquals(2, VTypeHelper.getArraySize(enumArray)); VStringArray stringArray = VStringArray.of(Arrays.asList("a","b"), Alarm.none(), Time.now()); assertEquals(2, VTypeHelper.getArraySize(stringArray)); }
### Question: VTypeHelper { public static Time lastestTimeOf(final VType a, final VType b) { final Time ta = Time.timeOf(a); final Time tb = Time.timeOf(b); if (ta.getTimestamp().isAfter(tb.getTimestamp())) { return ta; } return tb; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testGetLatestTimeOf(){ Instant now = Instant.now(); Time t1 = Time.of(Instant.EPOCH); Time t2 = Time.of(now); VInt i1 = VInt.of(1, Alarm.none(), t1, Display.none()); VInt i2 = VInt.of(2, Alarm.none(), t2, Display.none()); assertEquals(t2, VTypeHelper.lastestTimeOf(i1, i2)); assertEquals(t2, VTypeHelper.lastestTimeOf(i2, i1)); }
### Question: VTypeHelper { final public static Instant getTimestamp(final VType value) { final Time time = Time.timeOf(value); if (time != null && time.isValid()) { return time.getTimestamp(); } return Instant.now(); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testGetTimestamp() throws Exception{ Instant epoch = Instant.EPOCH; Time t = Time.of(epoch); VInt i1 = VInt.of(1, Alarm.none(), t, Display.none()); assertEquals(epoch, VTypeHelper.getTimestamp(i1)); t = Time.nowInvalid(); i1 = VInt.of(1, Alarm.none(), t, Display.none()); Instant now = Instant.now(); Thread.sleep(2); assertTrue(VTypeHelper.getTimestamp(i1).isAfter(now)); }
### Question: VTypeHelper { public static VType transformTimestamp(final VType value, final Instant time) { if (value instanceof VDouble) { final VDouble number = (VDouble) value; return VDouble.of(number.getValue().doubleValue(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VNumber) { final VNumber number = (VNumber) value; return VInt.of(number.getValue().intValue(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VString) { final VString string = (VString) value; return VString.of(string.getValue(), string.getAlarm(), Time.of(time)); } if (value instanceof VDoubleArray) { final VDoubleArray number = (VDoubleArray) value; return VDoubleArray.of(number.getData(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VEnum) { final VEnum labelled = (VEnum) value; return VEnum.of(labelled.getIndex(), labelled.getDisplay(), labelled.getAlarm(), Time.of(time)); } return null; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void testTransformTimestamp(){ Instant instant = Instant.now(); VInt intValue = VInt.of(7, Alarm.none(), Time.of(Instant.EPOCH), Display.none()); intValue = (VInt)VTypeHelper.transformTimestamp(intValue, instant); assertEquals(instant, intValue.getTime().getTimestamp()); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.of(Instant.EPOCH), Display.none()); doubleValue = (VDouble)VTypeHelper.transformTimestamp(doubleValue, instant); assertEquals(instant, doubleValue.getTime().getTimestamp()); VString stringValue = VString.of("test", Alarm.none(), Time.of(Instant.EPOCH)); stringValue = (VString)VTypeHelper.transformTimestamp(stringValue, instant); assertEquals(instant, stringValue.getTime().getTimestamp()); VEnum enumValue = VEnum.of(7, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); enumValue = (VEnum)VTypeHelper.transformTimestamp(enumValue, instant); assertEquals(instant, enumValue.getTime().getTimestamp()); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); doubleArray = (VDoubleArray)VTypeHelper.transformTimestamp(doubleArray, instant); assertEquals(instant, doubleArray.getTime().getTimestamp()); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertNull(VTypeHelper.transformTimestamp(enumArray, instant)); }
### Question: SnapshotDataConverter { protected static String getScalarValueString(Object value) { ObjectMapper objectMapper = new ObjectMapper(); Object[] valueArray = {value}; try { return objectMapper.writeValueAsString(valueArray); } catch (JsonProcessingException e) { throw new PVConversionException(String.format("Unable to write scalar value \"%s\" as JSON string", value.toString())); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test public void testGetScalarValueString() { assertEquals("[1]", SnapshotDataConverter.getScalarValueString(Integer.valueOf(1))); assertEquals("[1.1]", SnapshotDataConverter.getScalarValueString(Double.valueOf(1.1))); String string = SnapshotDataConverter.getScalarValueString("string"); assertEquals("[\"string\"]", string); }
### Question: VTypeHelper { public static Alarm highestAlarmOf(final VType a, VType b) { return Alarm.highestAlarmOf(java.util.List.of(a, b), false); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer: @Test public void highestAlarmOf() { VType arg1 = VInt.of(0, Alarm.none(), Time.now(), Display.none()); VType arg2 = VInt.of(0, Alarm.lolo(), Time.now(), Display.none()); Alarm alarm = VTypeHelper.highestAlarmOf(arg1, arg2); assertTrue("Failed to correctly calculate highest alarm expected LOLO, got : " + alarm, Alarm.lolo().equals(alarm)); }
### Question: SnapshotDataConverter { protected static String getNumberArrayValueString(VNumberArray vNumberArray) { List<Object> valueList = new ArrayList<>(); if(vNumberArray instanceof VByteArray || vNumberArray instanceof VUByteArray || vNumberArray instanceof VShortArray || vNumberArray instanceof VUShortArray || vNumberArray instanceof VIntArray || vNumberArray instanceof VUIntArray || vNumberArray instanceof VLongArray || vNumberArray instanceof VULongArray) { IteratorNumber iterator = vNumberArray.getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextLong()); } } else if(vNumberArray instanceof VFloatArray) { IteratorFloat iterator = ((VFloatArray)vNumberArray).getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextFloat()); } } else if(vNumberArray instanceof VDoubleArray) { IteratorDouble iterator = ((VDoubleArray)vNumberArray).getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextDouble()); } } else { throw new PVConversionException(String.format("Unable to create JSON string for array type %s", vNumberArray.getClass().getCanonicalName())); } ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(valueList); } catch (JsonProcessingException e) { throw new PVConversionException("Unable to write array values as JSON string"); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test public void testGetArrayValueString() { VNumberArray vNumberArray = VByteArray.of(CollectionNumbers.toListByte((byte) 1, (byte) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUByteArray.of(CollectionNumbers.toListUByte((byte) 1, (byte) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VShortArray.of(CollectionNumbers.toListShort((short) -1, (short) 2), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUShortArray.of(CollectionNumbers.toListUShort((short) 1, (short) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(-1, 2), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUIntArray.of(CollectionNumbers.toListUInt(1, 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VLongArray.of(CollectionNumbers.toListLong(-1L, 2L), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VULongArray.of(CollectionNumbers.toListULong(1L, 2L), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VFloatArray.of(CollectionNumbers.toListFloat(1.2f, 2.1f), alarm, time, display); assertEquals("[1.2,2.1]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VDoubleArray.of(CollectionNumbers.toListDouble(1.2, 2.1), alarm, time, display); assertEquals("[1.2,2.1]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); }
### Question: SnapshotDataConverter { protected static String getDimensionString(VNumberArray vNumberArray) { ListInteger sizes = vNumberArray.getSizes(); List<Integer> sizesAsIntList = new ArrayList<>(); for(int i = 0; i < sizes.size(); i++) { sizesAsIntList.add(sizes.getInt(i)); } ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(sizesAsIntList); } catch (JsonProcessingException e) { throw new PVConversionException("Unable to write sizes of number array as JSON string"); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test public void testGetDimensionString() { VNumberArray vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1, 2, 3, 4, 5, 6), CollectionNumbers.toListInt(1, 2, 3), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1,2,3]", SnapshotDataConverter.getDimensionString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1, 2, 3), CollectionNumbers.toListInt(1, 2), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1,2]", SnapshotDataConverter.getDimensionString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1), CollectionNumbers.toListInt(1), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1]", SnapshotDataConverter.getDimensionString(vNumberArray)); }
### Question: SnapshotDataConverter { protected static ListInteger toSizes(SnapshotPv snapshotPv) { ObjectMapper objectMapper = new ObjectMapper(); try { int[] sizes = objectMapper.readValue(snapshotPv.getSizes(), int[].class); return CollectionNumbers.toListInt(sizes); } catch (Exception e) { throw new PVConversionException(String.format("Unable to convert string %s to int array", snapshotPv.getSizes())); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test public void testDesrializeSizes() { ListInteger sizes = SnapshotDataConverter.toSizes(SnapshotPv.builder().sizes("[1,2]").build()); assertEquals(2, sizes.size()); assertEquals(1, sizes.getInt(0)); } @Test(expected = PVConversionException.class) public void testDeserializeBadSizes() { SnapshotDataConverter.toSizes(SnapshotPv.builder().sizes("[1,2").build()); }
### Question: Services implements IServices { @Override public Node createNode(String parentsUniqueId, Node node) { Node parentFolder = nodeDAO.getNode(parentsUniqueId); if (parentFolder == null || !parentFolder.getNodeType().equals(NodeType.FOLDER)) { String message = String.format("Cannot create new folder as parent folder with id=%s does not exist.", parentsUniqueId); logger.error(message); throw new IllegalArgumentException(message); } node = nodeDAO.createNode(parentsUniqueId, node); logger.info("Created new node: {}", node); return node; } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test(expected = IllegalArgumentException.class) public void testCreateConfigurationNoParent() { services.createNode("x", configFromClient); } @Test(expected = IllegalArgumentException.class) public void createNewFolderNoParentSpecified() { Node folderFromClient = Node.builder().name("SomeFolder").build(); services.createNode(null, folderFromClient); }
### Question: SnapshotDataConverter { public static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback) { if(snapshotPv == null) { return null; } SnapshotItem snapshotItem = SnapshotItem.builder() .configPv(snapshotPv.getConfigPv()) .snapshotId(snapshotPv.getSnapshotId()) .build(); if(snapshotPv.getValue() != null) { snapshotItem.setValue(toVType(snapshotPv)); } if(readback != null) { snapshotItem.setReadbackValue(toVType(readback)); } return snapshotItem; } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer: @Test public void testFromSnapshotPv() { SnapshotPv snapshotPv = SnapshotPv.builder().alarmName("name").alarmSeverity(AlarmSeverity.NONE).alarmStatus(AlarmStatus.NONE) .snapshotId(2).dataType(SnapshotPvDataType.LONG).time(1000L).timens(7000).value("[1]").sizes("[1]").configPv(ConfigPv.builder().id(1).build()).build(); SnapshotPv readback = SnapshotPv.builder().alarmName("name").alarmSeverity(AlarmSeverity.NONE).alarmStatus(AlarmStatus.NONE) .snapshotId(2).dataType(SnapshotPvDataType.LONG).time(1000L).timens(7000).value("[1]").sizes("[1]").configPv(ConfigPv.builder().id(1).build()).build(); SnapshotItem snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, readback); assertEquals(2, snapshotItem.getSnapshotId()); assertEquals(1, snapshotItem.getConfigPv().getId()); assertNotNull(snapshotItem.getReadbackValue()); snapshotPv = SnapshotPv.builder().snapshotId(1).configPv(ConfigPv.builder().id(1).build()).build(); snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, readback); assertNull(snapshotItem.getValue()); snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, null); assertNull(snapshotItem.getReadbackValue()); }
### Question: NodeRowMapper implements RowMapper<Node> { @Override public Node mapRow(ResultSet resultSet, int rowIndex) throws SQLException { return Node.builder() .id(resultSet.getInt("id")) .nodeType(NodeType.valueOf(resultSet.getString("type"))) .created(resultSet.getTimestamp("created")) .lastModified(resultSet.getTimestamp("last_modified")) .name(resultSet.getString("name")) .userName(resultSet.getString("username")) .uniqueId(resultSet.getString("unique_id")) .build(); } @Override Node mapRow(ResultSet resultSet, int rowIndex); }### Answer: @Test public void testRowMapper() throws Exception { ResultSet resultSet = Mockito.mock(ResultSet.class); when(resultSet.getInt("id")).thenReturn(1); when(resultSet.getString("name")).thenReturn("name"); when(resultSet.getTimestamp("created")).thenReturn(new Timestamp(System.currentTimeMillis())); when(resultSet.getTimestamp("last_modified")).thenReturn(new Timestamp(System.currentTimeMillis())); when(resultSet.getString("username")).thenReturn("username"); when(resultSet.getString("type")).thenReturn(NodeType.FOLDER.toString()); assertTrue(new NodeRowMapper().mapRow(resultSet, 0) instanceof Node); }
### Question: SnapshotPvRowMapper implements RowMapper<SnapshotPv> { @Override public SnapshotPv mapRow(ResultSet resultSet, int rowIndex) throws SQLException { ConfigPv configPv = new ConfigPvRowMapper().mapRow(resultSet, rowIndex); return SnapshotPv.builder() .configPv(configPv) .snapshotId(resultSet.getInt("snapshot_node_id")) .alarmSeverity(resultSet.getString("severity") == null ? null : AlarmSeverity.valueOf(resultSet.getString("severity"))) .alarmStatus(resultSet.getString("status") == null ? null : AlarmStatus.valueOf(resultSet.getString("status"))) .time(resultSet.getLong("time")) .timens(resultSet.getInt("timens")) .value(resultSet.getString("value")) .sizes(resultSet.getString("sizes")) .dataType(resultSet.getString("data_type") == null ? null : SnapshotPvDataType.valueOf(resultSet.getString("data_type"))) .build(); } @Override SnapshotPv mapRow(ResultSet resultSet, int rowIndex); }### Answer: @Test public void testSnapshotPvRowMapperNullReadback() throws Exception{ ResultSet resultSet = Mockito.mock(ResultSet.class); when(resultSet.getInt("snapshot_node_id")).thenReturn(1); when(resultSet.getBoolean("fetch_status")).thenReturn(true); when(resultSet.getString("severity")).thenReturn("NONE"); when(resultSet.getString("status")).thenReturn("NONE"); when(resultSet.getLong("time")).thenReturn(777L); when(resultSet.getInt("timens")).thenReturn(1); when(resultSet.getString("value")).thenReturn("[7]"); when(resultSet.getString("sizes")).thenReturn("[1]"); when(resultSet.getString("data_type")).thenReturn("INTEGER"); when(resultSet.getString("name")).thenReturn("pvname"); when(resultSet.getString("readback_name")).thenReturn("pvname"); when(resultSet.getString("provider")).thenReturn("ca"); assertTrue(new SnapshotPvRowMapper().mapRow(resultSet, 0) instanceof SnapshotPv); }
### Question: SnapshotController extends BaseController { @GetMapping("/snapshot/{uniqueNodeId}") public Node getSnapshot(@PathVariable String uniqueNodeId) { return services.getSnapshot(uniqueNodeId); } @GetMapping("/snapshot/{uniqueNodeId}") Node getSnapshot(@PathVariable String uniqueNodeId); @GetMapping("/snapshot/{uniqueNodeId}/items") List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId); @PutMapping("/snapshot/{configUniqueId}") Node saveSnapshot(@PathVariable String configUniqueId, @RequestParam(required = true) String snapshotName, @RequestParam(required = true) String userName, @RequestParam(required = true) String comment, @RequestBody(required = true) List<SnapshotItem> snapshotItems); }### Answer: @Test public void testGetSnapshot() throws Exception{ Mockito.reset(services); when(services.getSnapshot("b")).thenReturn(snapshot); MockHttpServletRequestBuilder request = get("/snapshot/b"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testGetNonExistingSnapshot() throws Exception{ when(services.getSnapshot("c")).thenThrow(new SnapshotNotFoundException("askdmdsf")); MockHttpServletRequestBuilder request = get("/snapshot/c"); mockMvc.perform(request).andExpect(status().isNotFound()); } @Test public void testNonExistingSnapshot() throws Exception{ when(services.getSnapshot("x")).thenThrow(new SnapshotNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/snapshot/x").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); }
### Question: SnapshotController extends BaseController { @GetMapping("/snapshot/{uniqueNodeId}/items") public List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId) { return services.getSnapshotItems(uniqueNodeId); } @GetMapping("/snapshot/{uniqueNodeId}") Node getSnapshot(@PathVariable String uniqueNodeId); @GetMapping("/snapshot/{uniqueNodeId}/items") List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId); @PutMapping("/snapshot/{configUniqueId}") Node saveSnapshot(@PathVariable String configUniqueId, @RequestParam(required = true) String snapshotName, @RequestParam(required = true) String userName, @RequestParam(required = true) String comment, @RequestBody(required = true) List<SnapshotItem> snapshotItems); }### Answer: @Test public void testGetSnapshotItems() throws Exception{ SnapshotItem si = SnapshotItem.builder() .configPv(ConfigPv.builder().id(1).pvName("pvName").build()) .snapshotId(2) .build(); when(services.getSnapshotItems("si")).thenReturn(Arrays.asList(si)); MockHttpServletRequestBuilder request = get("/snapshot/si/items"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<SnapshotItem>>() { }); }
### Question: SnapshotController extends BaseController { @PutMapping("/snapshot/{configUniqueId}") public Node saveSnapshot(@PathVariable String configUniqueId, @RequestParam(required = true) String snapshotName, @RequestParam(required = true) String userName, @RequestParam(required = true) String comment, @RequestBody(required = true) List<SnapshotItem> snapshotItems) { if(snapshotName.length() == 0 || userName.length() == 0 || comment.length() == 0) { throw new IllegalArgumentException("Snapshot name, user name and comment must be of non-zero length"); } return services.saveSnapshot(configUniqueId, snapshotItems, snapshotName, userName, comment); } @GetMapping("/snapshot/{uniqueNodeId}") Node getSnapshot(@PathVariable String uniqueNodeId); @GetMapping("/snapshot/{uniqueNodeId}/items") List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId); @PutMapping("/snapshot/{configUniqueId}") Node saveSnapshot(@PathVariable String configUniqueId, @RequestParam(required = true) String snapshotName, @RequestParam(required = true) String userName, @RequestParam(required = true) String comment, @RequestBody(required = true) List<SnapshotItem> snapshotItems); }### Answer: @Test public void testSaveSnapshot() throws Exception{ Mockito.reset(services); List<SnapshotItem> snapshotItems = Arrays.asList(SnapshotItem.builder().build()); when(services.saveSnapshot(Mockito.anyString(), Mockito.argThat(new ArgumentMatcher<List<SnapshotItem>>() { @Override public boolean matches(List<SnapshotItem> o) { return true; } }), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(Node.builder().build()); MockHttpServletRequestBuilder request = put("/snapshot/configid").param("snapshotName", "a").param("comment", "c").param("userName", "u"); mockMvc.perform(request).andExpect(status().isBadRequest()); request = put("/snapshot/configid") .contentType(JSON) .content(objectMapper.writeValueAsString(snapshotItems)) .param("snapshotName", "a").param("comment", "c").param("userName", "u"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
### Question: Services implements IServices { @Override public Node getNode(String nodeId) { logger.info("Getting node {}", nodeId); return nodeDAO.getNode(nodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetConfigNotNull() { when(nodeDAO.getNode("a")).thenReturn(configFromClient); Node config = services.getNode("a"); assertEquals(1, config.getId()); } @Test public void testGetFolder() { when(nodeDAO.getNode("a")).thenReturn(Node.builder().id(77).uniqueId("a").build()); assertNotNull(services.getNode("a")); } @Test public void testGetNonExsitingFolder() { when(nodeDAO.getNode("a")).thenReturn(null); assertNull(services.getNode("a")); reset(nodeDAO); }
### Question: ConfigurationController extends BaseController { @GetMapping("/root") public Node getRootNode() { return services.getRootNode(); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetRootNode() throws Exception { when(services.getRootNode()).thenReturn(rootNode); MockHttpServletRequestBuilder request = get("/root").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); String s = result.getResponse().getContentAsString(); objectMapper.readValue(s, Node.class); }
### Question: ConfigurationController extends BaseController { @PutMapping("/node/{parentsUniqueId}") public Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node) { if(node.getUserName() == null || node.getUserName().isEmpty()) { throw new IllegalArgumentException("User name must be non-null and of non-zero length"); } if(node.getName() == null || node.getName().isEmpty()) { throw new IllegalArgumentException("Node name must be non-null and of non-zero length"); } return services.createNode(parentsUniqueId, node); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testCreateFolder() throws Exception { when(services.createNode("p", folderFromClient)).thenReturn(folderFromClient); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON) .content(objectMapper.writeValueAsString(folderFromClient)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); String s = result.getResponse().getContentAsString(); objectMapper.readValue(s, Node.class); } @Test public void testCreateFolderParentIdDoesNotExist() throws Exception { when(services.createNode("p", folderFromClient)) .thenThrow(new IllegalArgumentException("Parent folder does not exist")); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON) .content(objectMapper.writeValueAsString(folderFromClient)); mockMvc.perform(request).andExpect(status().isBadRequest()); } @Test public void testCreateConfig() throws Exception { reset(services); Node config = Node.builder().nodeType(NodeType.CONFIGURATION).name("config").uniqueId("hhh") .userName("user").build(); when(services.createNode("p", config)).thenAnswer(new Answer<Node>() { public Node answer(InvocationOnMock invocation) throws Throwable { return config1; } }); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON).content(objectMapper.writeValueAsString(config)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
### Question: ConfigurationController extends BaseController { @GetMapping("/node/{uniqueNodeId}/children") public List<Node> getChildNodes(@PathVariable final String uniqueNodeId) { return services.getChildNodes(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetChildNodes() throws Exception{ reset(services); when(services.getChildNodes("p")).thenAnswer(new Answer<List<Node>>() { public List<Node> answer(InvocationOnMock invocation) throws Throwable { return Arrays.asList(config1); } }); MockHttpServletRequestBuilder request = get("/node/p/children").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); List<Node> childNodes = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); assertEquals(1, childNodes.size()); } @Test public void testGetChildNodesNonExistingNode() throws Exception{ reset(services); when(services.getChildNodes("non-existing")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/non-existing/children").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); }
### Question: ConfigurationController extends BaseController { @GetMapping("/node/{uniqueNodeId}") public Node getNode(@PathVariable final String uniqueNodeId) { return services.getNode(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetNonExistingConfig() throws Exception { when(services.getNode("x")).thenThrow(new NodeNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/node/x").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); } @Test public void testGetFolder() throws Exception { when(services.getNode("q")).thenReturn(Node.builder().id(1).uniqueId("q").build()); MockHttpServletRequestBuilder request = get("/node/q"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testGetConfiguration() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenReturn(Node.builder().build()); MockHttpServletRequestBuilder request = get("/node/a"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testGetNonExistingConfiguration() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isNotFound()); } @Test public void testGetNonExistingFolder() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isNotFound()); when(services.getNode("b")).thenThrow(IllegalArgumentException.class); request = get("/node/b"); mockMvc.perform(request).andExpect(status().isBadRequest()); } @Test public void testGetFolderIllegalArgument() throws Exception { when(services.getNode("a")).thenThrow(IllegalArgumentException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isBadRequest()); }
### Question: ConfigurationController extends BaseController { @GetMapping("/config/{uniqueNodeId}/snapshots") public List<Node> getSnapshots(@PathVariable String uniqueNodeId) { return services.getSnapshots(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetSnapshots() throws Exception { when(services.getSnapshots("s")).thenReturn(Arrays.asList(snapshot)); MockHttpServletRequestBuilder request = get("/config/s/snapshots").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); reset(services); } @Test public void testGetSnapshotsForNonExistingConfig() throws Exception { when(services.getSnapshots("x")).thenThrow(new NodeNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/config/x/snapshots").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); }
### Question: ConfigurationController extends BaseController { @DeleteMapping("/node/{uniqueNodeId}") public void deleteNode(@PathVariable final String uniqueNodeId) { services.deleteNode(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testDeleteFolder() throws Exception { MockHttpServletRequestBuilder request = delete("/node/a"); mockMvc.perform(request).andExpect(status().isOk()); doThrow(new IllegalArgumentException()).when(services).deleteNode("a"); request = delete("/node/a"); mockMvc.perform(request).andExpect(status().isBadRequest()); }
### Question: Services implements IServices { @Override public List<Node> getSnapshots(String configUniqueId) { logger.info("Obtaining snapshot for config id={}", configUniqueId); return nodeDAO.getSnapshots(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetSnapshots() { services.getSnapshots(anyString()); verify(nodeDAO, times(1)).getSnapshots(anyString()); reset(nodeDAO); }
### Question: ConfigurationController extends BaseController { @PostMapping("/node/{uniqueNodeId}") public Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName) { return services.moveNode(uniqueNodeId, to, userName); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testMoveNode() throws Exception { when(services.moveNode("a", "b", "username")).thenReturn(Node.builder().id(2).uniqueId("a").build()); MockHttpServletRequestBuilder request = post("/node/a").param("to", "b").param("username", "username"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
### Question: ConfigurationController extends BaseController { @PostMapping("/node/{uniqueNodeId}/update") public Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate) { return services.updateNode(nodeToUpdate, Boolean.valueOf(customTimeForMigration)); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testUpdateNode() throws Exception { Node node = Node.builder().name("foo").uniqueId("a").build(); when(services.updateNode(node, false)).thenReturn(node); MockHttpServletRequestBuilder request = post("/node/a/update") .param("customTimeForMigration", "false") .contentType(JSON) .content(objectMapper.writeValueAsString(node)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
### Question: ConfigurationController extends BaseController { @GetMapping("/config/{uniqueNodeId}/items") public List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId) { return services.getConfigPvs(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetConfigPvs() throws Exception{ ConfigPv configPv = ConfigPv.builder() .id(1) .pvName("pvname") .build(); when(services.getConfigPvs("cpv")).thenReturn(Arrays.asList(configPv)); MockHttpServletRequestBuilder request = get("/config/cpv/items"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<ConfigPv>>() { }); }
### Question: Services implements IServices { @Override public Node getSnapshot(String snapshotUniqueId) { Node snapshot = nodeDAO.getSnapshot(snapshotUniqueId); if (snapshot == null) { String message = String.format("Snapshot with id=%s not found", snapshotUniqueId); logger.error(message); throw new SnapshotNotFoundException(message); } logger.info("Retrieved snapshot id={}", snapshotUniqueId); return snapshot; } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer: @Test public void testGetSnapshotNotFound() { when(nodeDAO.getSnapshot("s")).thenReturn(null); try { services.getSnapshot("s"); fail("Exception expected here"); } catch (Exception e) { } reset(nodeDAO); } @Test public void testGetSnapshot() { when(nodeDAO.getSnapshot("s")).thenReturn(mock(Node.class)); Node snapshot = services.getSnapshot("s"); assertNotNull(snapshot); reset(nodeDAO); }
### Question: ConfigurationController extends BaseController { @GetMapping("/path") public List<Node> getFromPath(@RequestParam(value = "path") String path){ List<Node> nodes = services.getFromPath(path); if(nodes == null){ throw new ResponseStatusException(HttpStatus.NOT_FOUND); } return nodes; } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetFromPath() throws Exception{ when(services.getFromPath("/a/b/c")).thenReturn(null); MockHttpServletRequestBuilder request = get("/path?path=/a/b/c"); mockMvc.perform(request).andExpect(status().isNotFound()); request = get("/path"); mockMvc.perform(request).andExpect(status().isBadRequest()); Node node = Node.builder().name("name").uniqueId("uniqueId").build(); when(services.getFromPath("/a/b/c")).thenReturn(Arrays.asList(node)); request = get("/path?path=/a/b/c"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andReturn(); List<Node> nodes = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); assertEquals(1, nodes.size()); }
### Question: ConfigurationController extends BaseController { @GetMapping("/path/{uniqueNodeId}") public String getFullPath(@PathVariable String uniqueNodeId){ String fullPath = services.getFullPath(uniqueNodeId); if(fullPath == null){ throw new ResponseStatusException(HttpStatus.NOT_FOUND); } return fullPath; } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }### Answer: @Test public void testGetFullPath() throws Exception{ when(services.getFullPath("nonexisting")).thenReturn(null); MockHttpServletRequestBuilder request = get("/path/nonexsiting"); mockMvc.perform(request).andExpect(status().isNotFound()); when(services.getFullPath("existing")).thenReturn("/a/b/c"); request = get("/path/existing"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andReturn(); assertEquals("/a/b/c", result.getResponse().getContentAsString()); }
### Question: SeverityLevelHelper { final public static SeverityLevel decodeSeverity(final VType value) { final Alarm alarm = Alarm.alarmOf(value); if (alarm == null) return SeverityLevel.OK; switch (alarm.getSeverity()) { case NONE: return SeverityLevel.OK; case MINOR: return SeverityLevel.MINOR; case MAJOR: return SeverityLevel.MAJOR; case INVALID: return SeverityLevel.INVALID; default: return SeverityLevel.UNDEFINED; } } final static SeverityLevel decodeSeverity(final VType value); final static String getStatusMessage(final VType value); }### Answer: @Test public void decodeSeverity() { assertEquals(SeverityLevel.INVALID, SeverityLevelHelper.decodeSeverity(null)); VInt intValue = VInt.of(7, Alarm.disconnected(), Time.now(), Display.none()); SeverityLevel severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.INVALID, severityLevel); intValue = VInt.of(7, Alarm.none(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.OK, severityLevel); intValue = VInt.of(7, Alarm.lolo(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MAJOR, severityLevel); intValue = VInt.of(7, Alarm.hihi(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MAJOR, severityLevel); intValue = VInt.of(7, Alarm.low(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MINOR, severityLevel); intValue = VInt.of(7, Alarm.high(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MINOR, severityLevel); }
### Question: SeverityLevelHelper { final public static String getStatusMessage(final VType value) { final Alarm alarm = Alarm.alarmOf(value); if (alarm != null) return alarm.getName(); return SeverityLevel.OK.toString(); } final static SeverityLevel decodeSeverity(final VType value); final static String getStatusMessage(final VType value); }### Answer: @Test public void getStatusMessage() { VInt intValue = VInt.of(7, Alarm.disconnected(), Time.now(), Display.none()); String statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("Disconnected", statusMessage); intValue = VInt.of(7, Alarm.none(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("None", statusMessage); intValue = VInt.of(7, Alarm.lolo(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("LOLO", statusMessage); intValue = VInt.of(7, Alarm.hihi(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("HIHI", statusMessage); intValue = VInt.of(7, Alarm.low(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("LOW", statusMessage); intValue = VInt.of(7, Alarm.high(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("HIGH", statusMessage); }
### Question: PlotSample implements PlotDataItem<Instant> { @Override public double getValue() { return org.phoebus.core.vtypes.VTypeHelper.toDouble(value, waveform_index.get()); } PlotSample(final AtomicInteger waveform_index, final String source, final VType value, final String info); PlotSample(final AtomicInteger waveform_index, final String source, final VType value); PlotSample(final String source, final VType value); PlotSample(final String source, final String info); PlotSample(final double x, final double y); String getSource(); VType getVType(); @Override Instant getPosition(); @Override double getValue(); @Override double getStdDev(); @Override double getMin(); @Override double getMax(); @Override String getInfo(); @Override String toString(); }### Answer: @Test public void getValue() { VDouble vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); PlotSample plotSample = new PlotSample(new AtomicInteger(0), "source", vDouble, "info"); double result = plotSample.getValue(); assertEquals(7.7, result, 0); VDoubleArray vDoubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8, 9.9), Alarm.none(), Time.now(), Display.none()); plotSample = new PlotSample(new AtomicInteger(1), "source", vDoubleArray, "info"); result = plotSample.getValue(); assertEquals(8.8, result, 0); }
### Question: TimestampHelper { public static Instant roundUp(final Instant time, final Duration duration) { return roundUp(time, duration.getSeconds()); } static Instant roundUp(final Instant time, final Duration duration); static Instant roundUp(final Instant time, final long seconds); static Timestamp toSQLTimestamp(Instant start); static Instant fromSQLTimestamp(Timestamp timestamp); final static long SECS_PER_HOUR; final static long SECS_PER_MINUTE; final static long SECS_PER_DAY; }### Answer: @Test public void testRoundUp() throws Exception { final Instant orig = Instant.from(TimestampFormats.SECONDS_FORMAT.parse("2012-01-19 12:23:14")); String text = TimestampFormats.SECONDS_FORMAT.format(orig); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:14")); Instant time; time = TimestampHelper.roundUp(orig, 10); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:20")); time = TimestampHelper.roundUp(orig, TimeDuration.ofSeconds(30)); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:30")); time = TimestampHelper.roundUp(orig, 60); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:24:00")); time = TimestampHelper.roundUp(orig, TimeDuration.ofHours(1.0)); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 13:00:00")); time = TimestampHelper.roundUp(orig, 2L*60*60); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 14:00:00")); assertThat(24L*60*60, equalTo(TimestampHelper.SECS_PER_DAY)); time = TimestampHelper.roundUp(orig, TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-20 00:00:00")); time = TimestampHelper.roundUp(orig, 3*TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-22 00:00:00")); time = TimestampHelper.roundUp(orig, 13*TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-02-01 00:00:00")); assertThat(24L*60*60, equalTo(TimestampHelper.SECS_PER_DAY)); time = TimestampHelper.roundUp(orig, (3*TimestampHelper.SECS_PER_DAY)/2); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-20 12:00:00")); }
### Question: EdmConverter { public DisplayModel getDisplayModel() { return model; } EdmConverter(final File input, final AssetLocator asset_locator); DisplayModel getDisplayModel(); void write(final File output); int nextGroup(); void downloadAsset(final String asset); Collection<String> getIncludedDisplays(); Collection<String> getLinkedDisplays(); void addPositionOffset(final int x, final int y); int getOffsetX(); int getOffsetY(); void convertWidget(final Widget parent, final EdmEntity edm); void correctChildWidgets(final Widget parent); void addIncludedDisplay(final String included_display); void addLinkedDisplay(final String linked_display); }### Answer: @Test public void testConverter() throws Exception { EdmModel.reloadEdmColorFile("colors.list", getClass().getResourceAsStream("/colors.list")); final File edl = new File(getClass().getResource("/Maintenance_12hr.edl").getFile()); final EdmConverter converter = new EdmConverter(edl, null); final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final ModelWriter writer = new ModelWriter(buf); writer.writeModel(converter.getDisplayModel()); writer.close(); System.out.println(buf.toString()); }
### Question: Cache { public Cache(final Duration timeout) { this.timeout = timeout; } Cache(final Duration timeout); T getCachedOrNew(final String key, final CreateEntry<String, T> creator); Collection<String> getKeys(); void clear(); }### Answer: @Test public void testCache() throws Exception { final Cache<String> cache = new Cache<>(Duration.ofSeconds(2)); final CountDownLatch set_A = new CountDownLatch(1); final AtomicReference<String> A = new AtomicReference<>(); final ExecutorService pool = Executors.newCachedThreadPool(); pool.submit(() -> { final String key = "A"; logger.fine("> Requesting " + key + " for 1st time ..."); A.set(cache.getCachedOrNew(key, this::createEntry)); set_A.countDown(); logger.fine("< Got initial" + key); return null; }); pool.submit(() -> { final String key = "B"; logger.fine("> Requesting " + key + "..."); cache.getCachedOrNew(key, this::createEntry); logger.fine("< Got " + key); return null; }); pool.submit(() -> { final String key = "A"; logger.fine("> Requesting " + key + " again (cached)..."); cache.getCachedOrNew(key, this::createEntry); logger.fine("< Got cached " + key); return null; }); String A2 = cache.getCachedOrNew("A", this::createEntry); assertThat(A2, equalTo("Entry for A")); set_A.await(); assertThat(A2, sameInstance(A.get())); logger.fine("Allowing to expire"); TimeUnit.SECONDS.sleep(3); A2 = cache.getCachedOrNew("A", this::createEntry); assertThat(A2, not(sameInstance(A.get()))); logger.fine("Waiting for cache cleanup"); TimeUnit.SECONDS.sleep(6); final Collection<String> keys = cache.getKeys(); logger.fine("Remaining entries: " + keys); assertThat(keys.size(), equalTo(0)); }
### Question: Version implements Comparable<Version> { public static Version parse(final String version) { Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) return new Version(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); matcher = SHORT_VERSION_PATTERN.matcher(version); if (matcher.matches()) return new Version(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), 0); throw new IllegalArgumentException("Invalid version string '" + version + "'"); } Version(final int major, final int minor, final int patch); static Version parse(final String version); int getMajor(); int getMinor(); int getPatch(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(final Version other); @Override String toString(); }### Answer: @Test public void testParse() { assertThat(Version.parse("2.0.1").getMajor(), equalTo(2)); assertThat(Version.parse("2.0.1").getMinor(), equalTo(0)); assertThat(Version.parse("2.0.1").getPatch(), equalTo(1)); } @Test public void testError() { try { Version.parse("2"); fail("Didn't detect invalid version"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(), containsString("Invalid version string")); } try { Version.parse("2.1.2.3"); fail("Didn't detect invalid version"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(), containsString("Invalid version string")); } }
### Question: Converter { public Converter(final File input, final File output) throws Exception { logger.log(Level.INFO, "Convert " + input + " -> " + output); final ADLWidget root = ParserADL.getNextElement(input); colorMap = getColorMap(root); logger.log(Level.FINE, "Color map: " + Arrays.toString(colorMap)); initializeDisplayModel(input.getName(), root); logger.log(Level.FINE, "Display '" + display.getName() + "' size " + display.propWidth().getValue() + " x " + display.propHeight().getValue()); convertChildren(root.getObjects(), display, colorMap); logger.log(Level.FINE, "Writing " + output); final ModelWriter writer = new ModelWriter(new FileOutputStream(output)); writer.writeModel(display); writer.close(); } Converter(final File input, final File output); static void convertChildren(final List<ADLWidget> childWidgets, final Widget parentModel, final WidgetColor[] colorMap); static void main(final String[] original_args); static final Logger logger; }### Answer: @Test public void testConverter() throws Exception { final String filename = ConverterTest.class.getResource("/Main_XXXX.adl").getFile(); if (filename.isEmpty()) throw new Exception("Cannot obtain test file"); final File output = File.createTempFile("Main_XXX", ".bob"); output.deleteOnExit(); new Converter(new File(filename), output); final BufferedReader dump = new BufferedReader(new FileReader(output)); dump.lines().forEach(System.out::println); dump.close(); final ModelReader reader = new ModelReader(new FileInputStream(output)); final DisplayModel model = reader.readModel(); testCalcRule(model); }
### Question: JFXUtil extends org.phoebus.ui.javafx.JFXUtil { public static String webRGB(final WidgetColor color) { return webRGBCache.computeIfAbsent(color, col -> { if (col.getAlpha() < 255) return "rgba(" + col.getRed() + ',' + col.getGreen() + ',' + col.getBlue() + ',' + col.getAlpha()/255f + ')'; else return String.format((Locale) null, "#%02X%02X%02X", col.getRed(), col.getGreen(), col.getBlue()); }); } static Color convert(final WidgetColor color); static String webRGB(final WidgetColor color); static StringBuilder appendWebRGB(final StringBuilder buf, final WidgetColor color); static String shadedStyle(final WidgetColor color); static WidgetColor convert(final Color color); static Font convert(final WidgetFont font); static String cssFont(final String prefix, final Font font); static ImageView getIcon(final String name); static Pos computePos(final HorizontalAlignment horiz, final VerticalAlignment vert); }### Answer: @Test public void testRGB() { assertThat(JFXUtil.webRGB(new WidgetColor(15, 255, 0)), equalTo("#0FFF00")); assertThat(JFXUtil.webRGB(new WidgetColor(0, 16, 255)), equalTo("#0010FF")); }
### Question: SVGHelper { public static Image loadSVG(String imageFileName, double width, double height){ String cachedSVGFileName = imageFileName + "_" + width + "_" + height; return ImageCache.cache(cachedSVGFileName, () -> { try(InputStream inputStream = ModelResourceUtil.openResourceStream(imageFileName)){ return loadSVG(inputStream, width, height); } catch ( Exception ex ) { logger.log(Level.WARNING, String.format("Failure loading image: %s", imageFileName), ex); } return null; }); } static Image loadSVG(String imageFileName, double width, double height); static Image loadSVG(InputStream fileStream, double width, double height); }### Answer: @Test public void testSVGHelper(){ try { Image image = SVGHelper.loadSVG(getPath("interlock.svg"), 400d, 400d); assertTrue(image.getHeight() > 0); assertTrue(image.getWidth() > 0); } catch (Exception e) { fail(e.getMessage()); } } @Test public void testSVGHelperPngFile(){ String path = null; try { path = getPath("interlock.png"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperJpgFile(){ String path = null; try { path = getPath("interlock.jpg"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperGifFile() throws Exception{ String path = null; try { path = getPath("interlock.gif"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperTiffFile() throws Exception{ String path = null; try { path = getPath("interlock.tiff"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); }
### Question: ResettableTimeout { public void reset() { final ScheduledFuture<?> previous = timeout.getAndSet(timer.schedule(signal_no_more_messages, timeout_secs, TimeUnit.SECONDS)); if (previous != null) previous.cancel(false); } ResettableTimeout(final long timeout_secs); void reset(); boolean awaitTimeout(final long seconds); void shutdown(); }### Answer: @Test public void testReset() throws Exception { System.out.println("Timeout in 4 secs?"); final ResettableTimeout timer = new ResettableTimeout(4); final ScheduledExecutorService resetter = Executors.newSingleThreadScheduledExecutor(); resetter.scheduleAtFixedRate(() -> { System.out.println("Reset.."); timer.reset(); }, 1, 1, TimeUnit.SECONDS); assertThat(timer.awaitTimeout(8), equalTo(false)); resetter.shutdown(); System.out.println("Stopped the resets. Should now time out in 4 secs"); assertThat(timer.awaitTimeout(6), equalTo(true)); timer.shutdown(); }
### Question: AlarmContext { static String encodedURLPath(String path) { return String.valueOf(path).replace(": } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer: @Test public void testURLEncoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim%3A%2F%2Ftest"; String encodedPathWithColon = "OPR/TEST/SR%3Atest%3Apv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim%3A%2F%2FSR%3Atest%3Apv"; assertEquals("Failed to encode pv name the delimiter", encodedPathWithDelimiter, AlarmContext.encodedURLPath(pathWithDelimiter)); assertEquals("Failed to encode pv name with colon", encodedPathWithColon, AlarmContext.encodedURLPath(pathWithColon)); assertEquals("Failed to encode pv name with delimiter and colon", encodedPathWithDelimiterAndColon, AlarmContext.encodedURLPath(pathWithDelimiterAndColon)); }
### Question: AlarmContext { static String decodedURLPath(String path) { return String.valueOf(path).replace(encodecDelimiter, ": } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer: @Test public void testURLDecoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim%3A%2F%2Ftest"; String encodedPathWithColon = "OPR/TEST/SR%3Atest%3Apv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim%3A%2F%2FSR%3Atest%3Apv"; assertEquals("Failed to decode pv name the delimiter", pathWithDelimiter, AlarmContext.decodedURLPath(encodedPathWithDelimiter)); assertEquals("Failed to decode pv name with colon", pathWithColon, AlarmContext.decodedURLPath(encodedPathWithColon)); assertEquals("Failed to decode pv name with delimiter and colon", pathWithDelimiterAndColon, AlarmContext.decodedURLPath(encodedPathWithDelimiterAndColon)); }
### Question: AlarmContext { static String decodedKafaPath(String path) { return path.replace("\\/","/"); } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer: @Test public void testKafkaPathDecoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim:\\/\\/test"; String encodedPathWithColon = "OPR/TEST/SR:test:pv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim:\\/\\/SR:test:pv"; assertEquals("Failed to decode pv kafka path the delimiter", pathWithDelimiter, AlarmContext.decodedKafaPath(encodedPathWithDelimiter)); assertEquals("Failed to decode pv kafka path with colon", pathWithColon, AlarmContext.decodedKafaPath(encodedPathWithColon)); assertEquals("Failed to decode pv kafka path with delimiter and colon", pathWithDelimiterAndColon, AlarmContext.decodedKafaPath(encodedPathWithDelimiterAndColon)); }
### Question: FormulaTreeRootNode extends TreeItem<FormulaTreeByCategoryNode> { public void addChild(FormulaFunction child) { for (FormulaTreeCategoryNode category : categories) { if (category.getValue().getSignature().equals(child.getCategory())) { category.addChild(child); return; } } FormulaTreeCategoryNode newCategory = new FormulaTreeCategoryNode(child); categories.add(newCategory); this.getChildren().add(newCategory); } FormulaTreeRootNode(); void addChild(FormulaFunction child); }### Answer: @Test public void testGivenNoExistingCategoryAddingChildFormulaToRootNodeCreatesCategory() { String categoryName = "CATEGORY"; String formula1Name = "TEST_NAME"; FormulaFunction func = createFormula(formula1Name, "TEST_DESC", categoryName); FormulaTreeRootNode rootNode = new FormulaTreeRootNode(); rootNode.addChild(func); assertThat(rootNode.getChildren().size(), equalTo(1)); TreeItem<FormulaTreeByCategoryNode> category = rootNode.getChildren().get(0); assertThat(category.getValue().getSignature(), equalTo(categoryName)); assertThat(category.getValue().getDescription(), equalTo("")); assertThat(category.getChildren().size(), equalTo(1)); List<String> formulaSignatures = getFormulaSignaturesFromCategory(category); assertTrue(formulaSignatures.contains(formula1Name + "()")); } @Test public void testGivenExistingCategoryAddingChildFormulaToRootNodeDoesNotCreateCategory() { String categoryName = "CATEGORY"; String formula1Name = "TEST_NAME"; String formula2Name = "TEST_NAME2"; FormulaFunction firstFunc = createFormula(formula1Name, "TEST_DESC", categoryName); FormulaFunction secondFunc = createFormula(formula2Name, "TEST_DESC2", categoryName); FormulaTreeRootNode rootNode = new FormulaTreeRootNode(); rootNode.addChild(firstFunc); assertThat(rootNode.getChildren().size(), equalTo(1)); rootNode.addChild(secondFunc); assertThat(rootNode.getChildren().size(), equalTo(1)); TreeItem<FormulaTreeByCategoryNode> category = rootNode.getChildren().get(0); assertThat(category.getChildren().size(), equalTo(2)); List<String> formulaSignatures = getFormulaSignaturesFromCategory(category); assertTrue(formulaSignatures.contains(formula1Name + "()")); assertTrue(formulaSignatures.contains(formula2Name + "()")); }
### Question: Node implements Comparable<Node> { @Override public int compareTo(Node other) { if(nodeType.equals(NodeType.FOLDER) && other.getNodeType().equals(NodeType.CONFIGURATION)){ return -1; } else if(getNodeType().equals(NodeType.CONFIGURATION) && other.getNodeType().equals(NodeType.FOLDER)){ return 1; } else{ return getName().compareTo(other.getName()); } } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer: @Test public void testCompareTo() { Node folder1 = Node.builder().name("a").build(); Node folder2 = Node.builder().name("b").build(); Node folder3 = Node.builder().name("a").build(); Node config = Node.builder().nodeType(NodeType.CONFIGURATION).name("c1").build(); Node config2 = Node.builder().nodeType(NodeType.CONFIGURATION).name("c2").build(); assertTrue(folder3.compareTo(folder1) == 0); assertTrue(folder2.compareTo(folder1) > 0); assertTrue(folder1.compareTo(folder2) < 0); assertTrue(folder1.compareTo(config) < 0); assertTrue(config.compareTo(folder1) > 0); assertTrue(config.compareTo(config2) < 0); }
### Question: Node implements Comparable<Node> { @Override public int hashCode() { return Objects.hash(nodeType, uniqueId); } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer: @Test public void testHashCode() { Node node1 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); Node node2 = Node.builder().uniqueId("unique").nodeType(NodeType.CONFIGURATION).build(); assertNotEquals(node1.hashCode(), node2.hashCode()); }
### Question: Node implements Comparable<Node> { @Override public boolean equals(Object other) { if(other == null) { return false; } if(other instanceof Node) { Node otherNode = (Node)other; return nodeType.equals(otherNode.getNodeType()) && uniqueId.equals(otherNode.getUniqueId()); } return false; } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer: @Test public void testEquals() { Node node1 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); Node node2 = Node.builder().uniqueId("unique").nodeType(NodeType.CONFIGURATION).build(); Node node3 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); assertFalse(node1.equals(null)); assertFalse(node1.equals(node2)); assertTrue(node1.equals(node3)); assertFalse(node1.equals(new Object())); }