method2testcases
stringlengths
118
6.63k
### Question: IP { public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); } static boolean isValid(String ip); }### Answer: @Test public void testIsValid() { Map<String, Boolean> mapIO = new HashMap<String, Boolean>() {{ put("000.12.12.034", true); put("121.234.12.12", true); put("23.45.12.56", true); put("000.12.234.23.23", false); put("666.666.23.23", false); put(".213.123.23.32", false); put("23.45.22.32.", false); put("I.Am.not.an.ip", false); put("00.12.123.123123.123", false); put("122.23", false); put("Hello.IP", false); put("259.259.259.259", false); put("266.266.266.266", false); put("255.255.255.255", true); put("555.555.555.555", false); put("666.666.666.666", false); put("249.249.249.249", true); put("249.2", false); }}; for (Map.Entry<String, Boolean> io : mapIO.entrySet()) { boolean ret = IP.isValid(io.getKey()); if (io.getValue() != ret) { System.out.println(io.getKey()); } Assert.assertEquals(io.getValue(), ret); } }
### Question: PermutationEquation { public static int[] permutationEquation(final int[] p) { if (p == null || p.length <= 0) { return null; } Map<Integer, Integer> equationMap = new HashMap<Integer, Integer>(){{ for (int i = 0; i < p.length; i++) { put(p[i], i + 1); } }}; int[] arr = new int[p.length]; for (int i = 0; i < arr.length; i++) { arr[i] = equationMap.get(equationMap.get(i + 1)); } return arr; } static int[] permutationEquation(final int[] p); }### Answer: @Test public void testPermutationEquation() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{2, 3, 1}, new int[] {2, 3, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = PermutationEquation.permutationEquation(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } }
### Question: MaxMin { public static long[] maxMin(String[] operations, int[] values) { if (operations == null || values == null || operations.length > values.length) { return null; } long[] products = new long[operations.length]; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int[] arr = new int[operations.length]; int index = 0; for (int i = 0; i < operations.length; i++) { String op = operations[i]; int v = values[i]; if ("push".equalsIgnoreCase(op)) { arr[index++] = v; if (max < v) { max = v; } if (min > v) { min = v; } } else if ("pop".equalsIgnoreCase(op)) { for (int j = 0; j < index; j++) { if (arr[j] == v) { for (int k = j + 1; k < index; k++) { arr[k - 1] = arr[k]; } arr[index--] = 0; break; } } if (max == v || min == v) { max = Integer.MIN_VALUE; min = Integer.MAX_VALUE; for (int j = 0; j <= index; j++) { v = arr[j]; if (max < v) { max = v; } if (min > v) { min = v; } } } } products[i] = max * min; } return products; } static long[] maxMin(String[] operations, int[] values); }### Answer: @Test public void testMaxMin() { Map<Object[], long[]> pairIO = new HashMap<Object[], long[]>() {{ put(new Object[] {new String[]{"push", "push", "push", "pop"}, new int[]{1, 2, 3, 1}}, new long[]{1, 2, 3, 6}); put(new Object[] {new String[]{"push", "push"}, new int[] {3, 2}}, new long[]{9, 6}); }}; for (Map.Entry<Object[], long[]> io : pairIO.entrySet()) { long[] ret = MaxMin.maxMin((String[])io.getKey()[0], (int[])io.getKey()[1]); Assert.assertArrayEquals(io.getValue(), ret); } }
### Question: WinOrLose2 { public static int winOrLose(long first, long second) { if (first > second) return 1; else if (first < second) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int calculateLoop(List<Long> ar); static int winOrLose(long first, long second); }### Answer: @Test public void testWinOrLose() { Map<Integer, int[]> mapIO = new HashMap<Integer, int[]>() {{ put(0, new int[] {2, 3}); put(1, new int[] {5, 3}); }}; for (Map.Entry<Integer, int[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose2.winOrLose(io.getValue()[0], io.getValue()[1]) ); } }
### Question: CutSticks { public static int[] cutSticks(int[] lengths) { if (lengths == null || lengths.length <= 0) { return null; } Arrays.sort(lengths); int index = 0, count = lengths.length; List<Integer> countList = new ArrayList<Integer>(); while (index < count) { countList.add(count - index); if (index == count - 1) { break; } int value = lengths[index]; for (int i = index + 1; i < count; i++) { if (lengths[i] != value || i == count - 1) { index = i; for (int j = i; j < count; j++) { lengths[j] -= value; } break; } } } int[] arr = new int[countList.size()]; for (int i = 0; i < countList.size(); i++) { arr[i] = countList.get(i); } return arr; } static int[] cutSticks(int[] lengths); }### Answer: @Test public void testCutSticks() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>() {{ put(new int[]{1, 1, 2, 3}, new int[]{4, 2, 1}); put(new int[]{5, 4, 4, 2, 2, 8}, new int[]{6, 4, 2, 1}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = CutSticks.cutSticks(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } }
### Question: BinarySubString { public static int counting(String s) { if (s == null || s.trim().length() <= 1) { return 0; } char[] arr = s.trim().toCharArray(); int len = arr.length; int count = 0; for (int i = 0; i < len - 1; i++) { if (arr[i] != arr[i + 1]) { count++; int m = i - 1; int n = i + 1 + 1; while (m >= 0 && n < len && arr[i] == arr[m] && arr[i + 1] == arr[n]) { count++; m--; n++; } } } return count; } static int counting(String s); }### Answer: @Test public void testCounting() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("10001", 2); put("10101", 4); put("00110", 3); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = BinarySubString.counting(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
### Question: Portfolio { public static long findMax(int n, String tree) { if (n <= 0 || tree == null || tree.trim().length() <= 0) { return 0; } String[] nodes = tree.trim().split(" "); if (nodes.length < n) { return 0; } List<Long> sumList = new ArrayList<Long>(); int countExpected = 1; int count = 0; int index = 0; long sum = 0; for (int i = 0; i < nodes.length; i++) { String node = nodes[i]; if (!node.equals("#")) { count++; sum += Long.valueOf(node); } index++; if (index >= countExpected) { sumList.add(sum); countExpected = (int)Math.pow(2, count); count = 0; index = 0; sum = 0; } } Long[] sumArr = new Long[sumList.size()]; sumList.toArray(sumArr); return findMax(sumArr, 0); } static long findMax(int n, String tree); }### Answer: @Test public void testFindMax() { Map<String, int[]> mapIO = new HashMap<String, int[]>() {{ put("3 4 5 1 3 # 1", new int[]{6, 9}); put("3 2 3 # 3 # 1", new int[]{5, 7}); }}; for (Map.Entry<String, int[]> io : mapIO.entrySet()) { long ret = Portfolio.findMax(io.getValue()[0], io.getKey()); Assert.assertEquals((long)(io.getValue()[1]), ret); } }
### Question: BestTrio { static int bestTrio(int friends_nodes, int[] friends_from, int[] friends_to) { if (friends_nodes < 0 || friends_from == null || friends_to == null || friends_from.length > friends_to.length) { return -1; } List<HashSet<Integer>> friends = new ArrayList<HashSet<Integer>>(friends_nodes); for (int i = 0; i < friends_nodes; i++) { friends.add(new HashSet<Integer>()); } for (int i = 0; i < friends_from.length; i++) { int from = friends_from[i] - 1; int to = friends_to[i] - 1; friends.get(from).add(to); friends.get(to).add(from); } int min = Integer.MAX_VALUE; for (int i = 0; i < friends.size(); i++) { final HashSet<Integer> edges = friends.get(i); for (int j : edges) { final HashSet<Integer> edgesB = friends.get(j); for (int k : edgesB) { final HashSet<Integer> edgesC = friends.get(k); if (edgesC.contains(i)) { List<HashSet> arr = new ArrayList<HashSet>() {{ add(edges); add(edgesB); add(edgesC); }}; int score = 0; for (HashSet<Integer> u : arr) { HashSet<Integer> trio = new HashSet<Integer>(u); trio.remove(i); trio.remove(j); trio.remove(k); score += trio.size(); } if (min > score) { min = score; } } } } } if (min == Integer.MAX_VALUE) { min = -1; } return min; } }### Answer: @Test public void testBestTrio() { Map<Object[], Integer> mapIO = new HashMap<Object[], Integer>() {{ put(new Object[]{5, new int[]{1, 1, 2, 2, 3, 4}, new int[]{2, 3, 3, 4, 4, 5}}, 2); put(new Object[]{7, new int[]{2, 3, 5, 1}, new int[]{1, 6, 1, 7}}, -1); }}; for (Map.Entry<Object[], Integer> io : mapIO.entrySet()) { int ret = BestTrio.bestTrio((Integer) io.getKey()[0], (int[]) io.getKey()[1], (int[]) io.getKey()[2]); Assert.assertEquals(io.getValue().intValue(), ret); } }
### Question: MovieTitles { public static String[] getMovieTitles(String substr) { if (substr == null || substr.trim().length() <= 0) { return null; } int page = 1; final String url = "https: Gson gson = new Gson(); List<String> movies = new ArrayList<String>(); while (true) { String response = null; try { response = httpGet(String.format(url, substr, page)); } catch (Exception e) { e.printStackTrace(); } if (response == null || response.trim().length() <= 0) { break; } MoviePage moviePage = gson.fromJson(response, MoviePage.class); if (moviePage == null || moviePage.data == null || moviePage.data.size() <= 0) { break; } for (Movie movie : moviePage.data) { movies.add(movie.Title); } if (page < moviePage.total_pages) { page++; } else { break; } } String[] titles = new String[movies.size()]; movies.toArray(titles); Arrays.sort(titles); return titles; } static String[] getMovieTitles(String substr); static String httpGet(String url); }### Answer: @Test public void testMovieTitles() { final String[] ret = MovieTitles.getMovieTitles("spiderman"); System.out.println(Arrays.asList(ret).toString()); Assert.assertArrayEquals(new String[]{ "Amazing Spiderman Syndrome", "Fighting, Flying and Driving: The Stunts of Spiderman 3", "Hollywood's Master Storytellers: Spiderman Live", "Italian Spiderman", "Spiderman", "Spiderman", "Spiderman 5", "Spiderman and Grandma", "Spiderman in Cannes", "Superman, Spiderman or Batman", "The Amazing Spiderman T4 Premiere Special", "The Death of Spiderman", "They Call Me Spiderman", }, ret); }
### Question: ReductionCost { public static int reductionCost(int[] numArr) { if (numArr == null || numArr.length <= 0) { return 0; } int cost = 0; for (int i = 0; i < numArr.length - 1; i++) { Arrays.sort(numArr); int sum = numArr[i] + numArr[i + 1]; numArr[i] = 0; numArr[i + 1] = sum; cost += sum; } return cost; } static int reductionCost(int[] numArr); }### Answer: @Test public void testReductionCost() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[] {1, 2, 3}, 9); put(new int[] {1, 2, 3, 4}, 19); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int ret = ReductionCost.reductionCost(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
### Question: Arbitrage { public static int[] arbitrage(String[] quotes) { if (quotes == null || quotes.length <= 0) { return null; } int[] profits = new int[quotes.length]; for (int i = 0; i < quotes.length; i++) { double[] prices = parseQuote(quotes[i]); int profit = 0; if (prices != null) { double dollar = 100000; for (int j = 0; j < prices.length; j++) { dollar /= prices[j]; } profit = (int) dollar - 100000; if (profit < 0) { profit = 0; } } profits[i] = profit; } return profits; } static int[] arbitrage(String[] quotes); }### Answer: @Test public void testArbitrage() { int[] ret = Arbitrage.arbitrage(new String[]{"1.1837 1.3829 0.6102", "1.1234 1.2134 1.2311"}); Assert.assertArrayEquals(new int[]{114, 0}, ret); }
### Question: SubStr { public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; } static String[] splitTokens(String str); static String getSmallestAndLargest(String str, int k); }### Answer: @Test public void testSplitTokens() { Map<String, Integer> mapIO = new HashMap<String, Integer>() {{ put("He is a very very good boy, isn't he?", 10); put(" YES leading spaces are valid, problemsetters are evillllll", 8); put("", 0); put(null, 0); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { String[] ret = SubStr.splitTokens(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret == null ? 0 : ret.length); } }
### Question: SubStr { public static String getSmallestAndLargest(String str, int k) { if (str == null || str.length() < k || k <= 0) { return "\n"; } String smallest = str.substring(0, k); String largest = smallest; for (int i = 1; i < str.length() - k + 1; i++) { String sub = str.substring(i, i + k); if (smallest.compareTo(sub) > 0) { smallest = sub; } if (largest.compareTo(sub) < 0) { largest = sub; } } return smallest + "\n" + largest; } static String[] splitTokens(String str); static String getSmallestAndLargest(String str, int k); }### Answer: @Test public void testGetSmallestAndLargest() { Map<String, String> mapIO = new HashMap<String, String>() {{ put("welcometojava", "ava\nwel"); }}; for (Map.Entry<String, String> io : mapIO.entrySet()) { String ret = SubStr.getSmallestAndLargest(io.getKey(), 3); Assert.assertEquals(io.getValue(), ret); } }
### Question: NumberOfPairs { static int numberOfPairs(int[] a, long k) { if (a == null || a.length <= 1) { return 0; } Arrays.sort(a); Map<Integer, Integer> pairMap = new HashMap<Integer, Integer>(); for (int i = 0; i < a.length; i++) { int m = a[i]; for (int j = a.length - 1; j > i; j--) { int n = a[j]; if (m + n < k) { break; } else if (m + n == k) { if (m < n) { pairMap.put(m, n); } else { pairMap.put(n, m); } } } } return pairMap.size(); } }### Answer: @Test public void testBraces() { Map<int[], Integer[]> mapIO = new HashMap<int[], Integer[]>() {{ put(new int[] {6, 6, 3, 9, 3, 5, 1}, new Integer[]{12, 2}); }}; for (Map.Entry<int[], Integer[]> io : mapIO.entrySet()) { Integer ret = NumberOfPairs.numberOfPairs(io.getKey(), io.getValue()[0]); Assert.assertEquals(io.getValue()[1], ret); } }
### Question: WinOrLose2 { public static int calculateLoop(List<Long> ar) { int n = ar.size(); if (n <= 1 || (n & (n - 1)) != 0) { return 0; } Iterator<Long> iterator = ar.iterator(); long score = iterator.next(); long index = 0; long mark = 1; int loop = 0; while (iterator.hasNext()) { if (winOrLose(score, iterator.next()) == 1) { index++; if (index >= mark) { mark *= 2; loop++; } } else { break; } } if (loop <= 0 && ((double)score / ar.get(1) > 0)) { loop++; } return loop; } static void main(String[] args); static int calculateLoop(List<Long> ar); static int winOrLose(long first, long second); }### Answer: @Test public void testCalculateLoop() { Map<long[], Integer> mapIO = new HashMap<long[], Integer>() {{ put(new long[] {7, 1, 2, 3, 1, 3, 1, 2, 5, 6, 1, 6, 2, 5}, 0); put(new long[] {4, 1}, 1); put(new long[] {1000000, 1, 2, -1000000}, 2); put(new long[] {4, 1, 2, 3, 1, 3, 1, 2}, 3); put(new long[] {7, 1, 2, 3, 1, 3, 1, 2, 5, 6, 1, 6, 2, 5, 3, 6}, 4); put(new long[] {4, 1, 2, 3}, 2); put(new long[] {-5, -3, 1, 0, 2, -6, -4, -6}, 1); put(new long[] {-10, 6, -6, -2}, 0); }}; for (Map.Entry<long[], Integer> io : mapIO.entrySet()) { long[] ar = io.getKey(); ArrayList<Long> list = new ArrayList<Long>(ar.length); for (long item : ar) { list.add(item); } Assert.assertEquals( io.getValue().intValue(), WinOrLose2.calculateLoop(list) ); } }
### Question: Palindrome { static int getScore(String s) { if (s == null || s.trim().length() <= 1) { return 0; } if (s.length() == 2) { return 1; } int score = 0; for (int i = 1; i < s.length(); i++) { String p1 = getMaxPalindrome(s.substring(0, i)); String p2 = getMaxPalindrome(s.substring(i, s.length())); int tmp = (p1 == null ? 0 : p1.length()) * (p2 == null ? 0 : p2.length()); if (score < tmp) { score = tmp; } } return score; } static boolean isPalindrome(String str); }### Answer: @Test public void testGetScore() { Map<String, Integer> mapIO = new HashMap<String, Integer>(){{ put("acdapmpomp", 15); put("axbawbaseksqke", 25); put("aa", 1); put("ab", 1); put("abb", 2); put("aab", 2); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { int ret = Palindrome.getScore(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
### Question: PickNumbers { public static int pickNumbers(int[] ar) { if (ar == null || ar.length <= 0) { return 0; } Arrays.sort(ar); int n = ar.length; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int count = 0; int diff = 0; for (int j = i - 1; j >= 0; j--) { int tmp = Math.abs(ar[i] - ar[j]); if (tmp <= 1) { count++; if (diff < tmp) { diff = tmp; } } else { break; } } for (int j = i + 1; j < n; j++) { int tmp = Math.abs(ar[i] - ar[j]); if (diff + tmp <= 1) { count++; } else { break; } } if (max < count) { max = count; } } return max + 1; } static int pickNumbers(int[] ar); }### Answer: @Test public void testPickNumbers() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(null, 0); put(new int[]{4, 6, 5, 3, 3, 1}, 3); put(new int[]{1, 2, 2, 3, 1, 2}, 5); put(new int[]{ 4, 2, 3, 4, 4, 9, 98, 98, 3, 3, 3, 4, 2, 98, 1, 98, 98, 1, 1, 4, 98, 2, 98, 3, 9, 9, 3, 1, 4, 1, 98, 9, 9, 2, 9, 4, 2, 2, 9, 98, 4, 98, 1, 3, 4, 9, 1, 98, 98, 4, 2, 3, 98, 98, 1, 99, 9, 98, 98, 3, 98, 98, 4, 98, 2, 98, 4, 2, 1, 1, 9, 2, 4}, 22); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int ret = PickNumbers.pickNumbers(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
### Question: Braces { static String[] braces(String[] values) { if (values == null || values.length <= 0) { return null; } Map<Integer, Integer> braceMap = new HashMap<Integer, Integer>() {{ put((int)')', (int)'('); put((int)']', (int)'['); put((int)'}', (int)'{'); }}; String[] ret = new String[values.length]; for (int i = 0; i < values.length; i++) { String value = values[i]; char[] braceArr = new char[value.length() / 2 + 1]; int j = -1; boolean closed = true; for (char c : value.toCharArray()) { if (braceMap.keySet().contains((int)c)) { if (j >= 0 && braceArr[j] == braceMap.get((int)c)) { j--; } else { closed = false; break; } } else { if (j < braceArr.length) { ++j; braceArr[j] = c; } else { closed = false; break; } } } ret[i] = j < 0 && closed ? "YES" : "NO"; } return ret; } }### Answer: @Test public void testBraces() { Map<String[], String[]> mapIO = new HashMap<String[], String[]>() {{ put(new String[] {"{}[]()", "{[}]}"}, new String[] {"YES", "NO"}); put(new String[] {"}][}}(}][))]"}, new String[] {"NO"}); }}; for (Map.Entry<String[], String[]> io : mapIO.entrySet()) { String[] ret = Braces.braces(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } }
### Question: AopInstrumenter implements MethodInterceptor { public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } Object getInstrumentedClass(Class clz); Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy); }### Answer: @Test public void testGetInstrumentedObject() { AopInstrumenter instrumenter = new AopInstrumenter(); AopService service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instrumenter from test"); }
### Question: App { public static void main(String[] args) { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from app.main"); AopInstrumenter instrumenter = new AopInstrumenter(); service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instumenter from app.main"); } static void main(String[] args); }### Answer: @Test public void testApp() { App.main(null); }
### Question: AopFactory { public static Object getAopProxyedObject(String clzName) { Object proxy = null; AopHandler handler = new AopHandler(); Object obj = getClassInst(clzName); if (obj != null) { proxy = handler.bind(obj); } else { System.out.println("Can't get the proxyObj"); } return proxy; } static Object getAopProxyedObject(String clzName); }### Answer: @Test public void testGetAopProxyedObject() { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from test"); }
### Question: RedisService { public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; } long incr(String key); boolean expire(String key, long seconds); }### Answer: @Test public void testIncr() { String key = "RedisServiceTest.testStr"; long ret = redisService.incr(key); Assertions.assertTrue(ret > 0); System.out.println(ret); redisService.expire(key, 1); }
### Question: HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }### Answer: @Test void testServletHook() throws ClassNotFoundException, IOException { String expected = ServletTestHook.class.getName() + " instruments [javax.servlet.Filter, javax.servlet.Servlet]:\n" + " * doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)\n" + " * service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(ServletTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); } @Test void testPrimitiveTypes() throws ClassNotFoundException, IOException { String expected = PrimitiveTypesTestHook.class.getName() + " instruments [com.example.Some]:\n" + " * arrayArgs(java.lang.Object[], int[], java.lang.String[])\n" + " * boxedArgs(java.lang.Boolean, java.lang.Character, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, java.lang.Long, java.lang.Double)\n" + " * noArgs()\n" + " * primitiveArgs(boolean, char, byte, short, int, float, long, double)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(PrimitiveTypesTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); } @Test void testReturnedAndThrown() throws IOException, ClassNotFoundException { String expected = ReturnedAndThrownTestHook.class.getName() + " instruments [com.example.ReturnThrown]:\n" + " * div(int, int)"; SortedSet<HookMetadata> result = parser.parse(className -> className.equals(ReturnedAndThrownTestHook.class.getName())); Assertions.assertEquals(1, result.size()); Assertions.assertEquals(expected, result.first().toString()); } @Test void testNoHook() throws ClassNotFoundException, IOException { SortedSet<HookMetadata> result = parser.parse(className -> className.equals(HookMetadataParserTest.class.getName())); Assertions.assertTrue(result.isEmpty()); }
### Question: JarFiles { static Path findAgentJarFromCmdline(List<String> cmdlineArgs) { Pattern p = Pattern.compile("^-javaagent:(.*promagent([^/]*).jar)(=.*)?$"); for (String arg : cmdlineArgs) { Matcher m = p.matcher(arg); if (m.matches()) { return Paths.get(m.group(1)); } } throw new RuntimeException("Failed to locate promagent.jar file."); } private JarFiles(List<Path> perDeploymentJars, List<Path> sharedJars); }### Answer: @Test void testCmdlineParserWildfly() { String[] cmdlineArgs = new String[]{ "-D[Standalone]", "-Xbootclasspath/p:/tmp/wildfly-10.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.4.Final.jar", "-Djboss.modules.system.pkgs=org.jboss.logmanager,io.promagent.agent", "-Djava.util.logging.manager=org.jboss.logmanager.LogManager", "-javaagent:../promagent/promagent-dist/target/promagent.jar=port=9300", "-Dorg.jboss.boot.log.file=/tmp/wildfly-10.1.0.Final/standalone/log/server.log", "-Dlogging.configuration=file:/tmp/wildfly-10.1.0.Final/standalone/configuration/logging.properties" }; assertEquals("../promagent/promagent-dist/target/promagent.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString()); } @Test void testCmdlineParserVersioned() { String[] cmdlineArgs = new String[] { "-javaagent:promagent-1.0-SNAPSHOT.jar" }; assertEquals("promagent-1.0-SNAPSHOT.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString()); } @Test() void testCmdlineParserFailed() { String[] cmdlineArgs = new String[] { "-javaagent:/some/other/agent.jar", "-jar", "promagent.jar" }; Exception e = assertThrows(Exception.class, () -> findAgentJarFromCmdline(asList(cmdlineArgs))); assertTrue(e.getMessage().contains("promagent.jar")); }
### Question: SyncMetadataService extends BaseService implements IMetadataService { @Override public SalientAttributes getAttributes() throws RemotePeerException, IOException { SalientAttributes originAttributes = new SalientAttributes(); originAttributes.setApplication(context.getApplication()); originAttributes.setVersion(context.getVersion()); originAttributes.setPeerId(context.getHost().getPeerID()); Block lastBlock = blockchain.getLastBlock(); originAttributes.setNetworkID(fork.getGenesisBlockID().toString()); originAttributes.setFork(fork.getNumber(lastBlock.getTimestamp())); originAttributes.setHistoryFromHeight(storage.metadata().getHistoryFromHeight()); if (context.getHost().getAddress() != null && context.getHost().getAddress().length() > 0) { originAttributes.setAnnouncedAddress(context.getHost().getAddress()); } return originAttributes; } SyncMetadataService(IFork fork, ExecutionContext context, IBlockchainProvider blockchain, Storage storage); @Override SalientAttributes getAttributes(); @Override String[] getWellKnownNodes(); @Override boolean addPeer(long peerID, String address); }### Answer: @Test public void getAttributes() throws Exception { long peerId = 100500L; String hostAddress = "testAddress.com"; String app = "testApp"; String version = "testVersion"; ExecutionContext ctx = mock(ExecutionContext.class); ExecutionContext.Host host = mock(ExecutionContext.Host.class); fork = mock(IFork.class); when(fork.isPassed(anyInt())).thenReturn(false); when(fork.getGenesisBlockID()).thenReturn(new BlockID(12345L)); when(ctx.getHost()).thenReturn(host); when(host.getPeerID()).thenReturn(peerId); when(host.getAddress()).thenReturn(hostAddress); when(ctx.getApplication()).thenReturn(app); when(ctx.getVersion()).thenReturn(version); Block block = mock(Block.class); blockchain = mock(IBlockchainProvider.class); when(blockchain.getLastBlock()).thenReturn(block); storage = mock(Storage.class); when(storage.metadata()).thenReturn(mock(Storage.Metadata.class)); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); SalientAttributes attrs = sms.getAttributes(); assertEquals(peerId, attrs.getPeerId()); assertEquals(hostAddress, attrs.getAnnouncedAddress()); assertEquals(app, attrs.getApplication()); assertEquals(version, attrs.getVersion()); when(host.getAddress()).thenReturn(null); attrs = sms.getAttributes(); assertEquals(peerId, attrs.getPeerId()); assertEquals(null, attrs.getAnnouncedAddress()); assertEquals(app, attrs.getApplication()); assertEquals(version, attrs.getVersion()); }
### Question: NoteValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getNote() == null) { return ValidationResult.success; } int length = tx.getNote().length(); if (length > 0 && length <= maxLength) { Matcher m = notePattern.matcher(tx.getNote()); if (m.matches()) { return ValidationResult.success; } } return ValidationResult.error("Invalid note"); } NoteValidationRule(); NoteValidationRule(Pattern notePattern, int maxLength); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success_without_note() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void empty_note() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Transaction tx = Builder.newTransaction(timeProvider).note("").build(networkID, sender); validate(tx); } @Test public void invalid_note_length() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Random random = new Random(); char[] symbols = alphabet.toCharArray(); char[] buffer = new char[Constant.TRANSACTION_NOTE_MAX_LENGTH_V2 + 1]; for (int i = 0; i < buffer.length; i++) { buffer[i] = symbols[random.nextInt(symbols.length)]; } Transaction tx = Builder.newTransaction(timeProvider).note(new String(buffer)).build(networkID, sender); validate(tx); } @Test public void illegal_symbol() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Transaction tx = Builder.newTransaction(timeProvider).note("|note|").build(networkID, sender); validate(tx); } @Test public void check_alphabet() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).note(alphabet).build(networkID, sender); validate(tx); } @Test public void forbidden_note_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).note("Note").build(networkID, sender); validate(tx); }
### Question: LengthValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); if (length > Constant.TRANSACTION_MAX_PAYLOAD_LENGTH) { return ValidationResult.error("Invalid transaction length."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void length_exceeds_limit() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction length."); Transaction tx = spy(Builder.newTransaction(timeProvider).build(networkID, sender)); when(tx.getLength()).thenReturn(Constant.TRANSACTION_MAX_PAYLOAD_LENGTH + 1); validate(tx); }
### Question: SyncTransactionService extends BaseService implements ITransactionSynchronizationService { @Override public Transaction[] getTransactions(String lastBlockId, String[] ignoreList) throws RemotePeerException, IOException { List<TransactionID> ignoreIDs = new ArrayList<>(); try { if (!blockchain.getLastBlock().getID().equals(new BlockID(lastBlockId)) && !fork.isPassed(timeProvider.get())) { return new Transaction[0]; } for (String encodedID : ignoreList) { ignoreIDs.add(new TransactionID(encodedID)); } } catch (IllegalArgumentException e) { throw new RemotePeerException("Unsupported request. Invalid transaction ID format.", e); } try { List<Transaction> list = new ArrayList<>(); int blockSize = Constant.BLOCK_TRANSACTION_LIMIT; final Iterator<TransactionID> indexes = backlog.iterator(); while (indexes.hasNext() && list.size() < TRANSACTION_LIMIT && blockSize > 0) { TransactionID id = indexes.next(); if (!ignoreIDs.contains(id)) { Transaction tx = backlog.get(id); if (tx != null) { list.add(tx); } } blockSize--; } return list.toArray(new Transaction[0]); } catch (Exception e) { throw new IOException("Failed to get the transaction list.", e); } } SyncTransactionService(IFork fork, ITimeProvider timeProvider, IBacklog backlog, IBlockchainProvider blockchain); @Override Transaction[] getTransactions(String lastBlockId, String[] ignoreList); }### Answer: @Test public void getTransactions_shouldnt_return_ignore_trs() throws Exception { Transaction[] trs = sts.getTransactions(lastBlockIdStr, new String[] {ignoreTrIdStr}); assertEquals(2, trs.length); assertEquals(unconfTr1, trs[0]); assertEquals(unconfTr2, trs[1]); } @Test(expected = RemotePeerException.class) public void getTransactions_with_wrong_lastblockid_should_throw() throws Exception { sts.getTransactions("xxx", new String[0]); } @Test(expected = RemotePeerException.class) public void getTransactions_with_bad_ignorelist_should_throw() throws Exception { sts.getTransactions(lastBlockIdStr, new String[] {"bad_tr_id"}); } @Test public void getTransactions_with_notlast_lastblockid_should_return_no_trs() throws Exception { Transaction[] trs = sts.getTransactions("EON-B-NA7Z7-YSK86-7BWKU", new String[0]); assertEquals(0, trs.length); } @Test public void getTransactions_should_return_unconfirmed_trs() throws Exception { Transaction[] trs = sts.getTransactions(lastBlockIdStr, new String[0]); assertEquals(3, trs.length); assertEquals(unconfTr1, trs[0]); assertEquals(unconfTr2, trs[1]); assertEquals(ignoreTr, trs[2]); }
### Question: AccountBotService { public State getState(String id) throws RemotePeerException, IOException { Account account = getAccount(id); if (account != null) { return State.OK; } IBacklog backlog = this.backlog; for (TransactionID item : backlog) { Transaction transaction = backlog.get(item); if (transaction != null && transaction.getType() == TransactionType.Registration) { if (transaction.getData().keySet().contains(id)) { return State.Processing; } } } return State.NotFound; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }### Answer: @Test public void getState_for_existing_account_should_return_OK() throws Exception { AccountID id = new AccountID(12345L); ledger = ledger.putAccount(new Account(id)); assertEquals(AccountBotService.State.OK, service.getState(id.toString())); } @Test public void getState_for_processing_account() throws Exception { ISigner sender = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); ISigner newAccount = new TestSigner("112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"); Transaction tx = RegistrationBuilder.createNew(newAccount.getPublicKey()).build(new BlockID(0L), sender); backlog.put(tx); AccountID id = new AccountID(newAccount.getPublicKey()); assertEquals(AccountBotService.State.Processing, service.getState(id.toString())); } @Test public void getState_for_notexisting_account() throws Exception { assertEquals(AccountBotService.State.NotFound, service.getState(new AccountID(12345L).toString())); }
### Question: AccountBotService { public EONBalance getBalance(String id) throws RemotePeerException, IOException { Account account = getAccount(id); EONBalance balance = new EONBalance(); if (account == null) { balance.state = State.Unauthorized; } else { balance.state = State.OK; BalanceProperty b = AccountProperties.getBalance(account); balance.amount = b.getValue(); ColoredBalanceProperty coloredBalance = AccountProperties.getColoredBalance(account); if (coloredBalance != null) { Map<String, Long> cMap = new HashMap<>(); for (ColoredCoinID coinID : coloredBalance) { cMap.put(coinID.toString(), coloredBalance.getBalance(coinID)); } if (!cMap.isEmpty()) { balance.coloredCoins = cMap; } } } return balance; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }### Answer: @Test public void getBalance_for_existing_account() throws Exception { AccountID id = new AccountID(12345L); Account account = new Account(id); account = AccountProperties.setProperty(account, new BalanceProperty(100L)); ledger = ledger.putAccount(account); AccountBotService.EONBalance balance = service.getBalance(id.toString()); assertEquals(AccountBotService.State.OK, balance.state); assertEquals(100L, balance.amount); assertNull(balance.coloredCoins); } @Test public void getBalance_for_notexisting_account() throws Exception { AccountBotService.EONBalance balance = service.getBalance(new AccountID(12345L).toString()); assertEquals(AccountBotService.State.Unauthorized, balance.state); assertEquals(0, balance.amount); assertNull(balance.coloredCoins); } @Test public void getBalance_for_existing_account_with_colored_coins() throws Exception { AccountID id = new AccountID(12345L); Account account = new Account(id); account = AccountProperties.setProperty(account, new BalanceProperty(100L)); ColoredBalanceProperty coloredBalance = new ColoredBalanceProperty(); coloredBalance.setBalance(100L, new ColoredCoinID(1L)); coloredBalance.setBalance(200L, new ColoredCoinID(2L)); account = AccountProperties.setProperty(account, coloredBalance); ledger = ledger.putAccount(account); AccountBotService.EONBalance balance = service.getBalance(id.toString()); assertEquals(AccountBotService.State.OK, balance.state); assertEquals(100L, balance.amount); assertNotNull(balance.coloredCoins); assertTrue(balance.coloredCoins.size() == 2); assertEquals(balance.coloredCoins.get(new ColoredCoinID(1L).toString()), Long.valueOf(100L)); assertEquals(balance.coloredCoins.get(new ColoredCoinID(2L).toString()), Long.valueOf(200L)); }
### Question: SyncMetadataService extends BaseService implements IMetadataService { @Override public String[] getWellKnownNodes() throws RemotePeerException, IOException { Collection<String> wellKnownPeers = new ArrayList<>(); String[] addresses = context.getPeers().getPeersList(); for (String address : addresses) { PeerInfo peer = context.getPeers().getPeerByAddress(address); if (peer != null) { if (peer.getState() == PeerInfo.STATE_CONNECTED && peer.getBlacklistingTime() == 0 && peer.getAddress() != null && peer.getAddress().length() > 0 && !peer.isInner()) { wellKnownPeers.add(peer.getAddress()); } } } return wellKnownPeers.toArray(new String[0]); } SyncMetadataService(IFork fork, ExecutionContext context, IBlockchainProvider blockchain, Storage storage); @Override SalientAttributes getAttributes(); @Override String[] getWellKnownNodes(); @Override boolean addPeer(long peerID, String address); }### Answer: @Test public void getWellKnownNodes_should_return_array() throws Exception { SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(2, wkn.length); assertEquals(peer1Addr, wkn[0]); assertEquals(peer2Addr, wkn[1]); } @Test public void getWellKnownNodes_shouldnt_return_notconnected_peers() throws Exception { when(peer1.getState()).thenReturn(PeerInfo.STATE_AMBIGUOUS); when(peer2.getState()).thenReturn(PeerInfo.STATE_DISCONNECTED); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); } @Test public void getWellKnownNodes_shouldnt_return_blacklist_peers() throws Exception { when(peer1.getBlacklistingTime()).thenReturn(60L); when(peer2.getBlacklistingTime()).thenReturn(-60L); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); } @Test public void getWellKnownNodes_shouldnt_return_noaddress_peers() throws Exception { when(peer1.getAddress()).thenReturn(null); when(peer2.getAddress()).thenReturn(""); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); } @Test public void getWellKnownNodes_shouldnt_return_inner_peers() throws Exception { when(peer1.isInner()).thenReturn(true); when(peer2.isInner()).thenReturn(true); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); }
### Question: ColoredCoinBotService { public Info getInfo(String id) throws RemotePeerException, IOException { Account account = getColoredAccount(id); Info info = new Info(); info.state = State.Unauthorized; if (account == null) { return info; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (!coloredCoin.isIssued()) { return info; } info.state = State.OK; info.decimal = coloredCoin.getAttributes().decimalPoint; info.timestamp = coloredCoin.getAttributes().timestamp; info.supply = coloredCoin.getMoneySupply(); info.auto = (coloredCoin.getEmitMode() == ColoredCoinEmitMode.AUTO); return info; } ColoredCoinBotService(LedgerProvider ledgerProvider, IBlockchainProvider blockchain); Info getInfo(String id); }### Answer: @Test public void getInformation_OK() throws Exception { AccountID id = new AccountID(1L); targetAccount = new Account(id); ColoredCoinProperty coloredCoin = new ColoredCoinProperty(); coloredCoin.setEmitMode(ColoredCoinEmitMode.PRESET); coloredCoin.setMoneySupply(10000L); coloredCoin.setAttributes(new ColoredCoinProperty.Attributes(8, 1)); targetAccount = AccountProperties.setProperty(targetAccount, coloredCoin); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.OK); assertEquals(info.decimal, Integer.valueOf(8)); assertEquals(info.supply, Long.valueOf(10000L)); assertEquals(info.timestamp, Integer.valueOf(1)); assertFalse(info.auto); } @Test public void getInformation_not_found() throws Exception { AccountID id = new AccountID(1L); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.Unauthorized); assertNull(info.decimal); assertNull(info.supply); } @Test public void getInformation_illegal_state() throws Exception { AccountID id = new AccountID(1L); targetAccount = new Account(id); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.Unauthorized); assertNull(info.decimal); assertNull(info.supply); }
### Question: Fork implements IFork { @Override public boolean isCome(int timestamp) { return items.getFirst().isCome(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer: @Test public void isCome() { assertFalse("Before fork", forkState.isCome(50)); assertFalse("Fork started", forkState.isCome(100)); assertTrue("On fork", forkState.isCome(150)); assertTrue("Fork ended", forkState.isCome(200)); assertTrue("After fork", forkState.isCome(250)); }
### Question: Fork implements IFork { @Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer: @Test public void isPassed() { assertFalse("Before fork", forkState.isPassed(50)); assertFalse("Fork started", forkState.isPassed(100)); assertFalse("On fork", forkState.isPassed(150)); assertFalse("Fork ended", forkState.isPassed(200)); assertTrue("After fork", forkState.isPassed(250)); }
### Question: Fork implements IFork { @Override public int getNumber(int timestamp) { Item item = getItem(timestamp); return (item == null) ? -1 : item.getNumber(); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); }### Answer: @Test public void getNumber() { assertEquals("Before fork", 1, forkState.getNumber(50)); assertEquals("Fork started", 1, forkState.getNumber(100)); assertEquals("On fork", 2, forkState.getNumber(150)); assertEquals("Fork ended", 2, forkState.getNumber(200)); assertEquals("After fork", 2, forkState.getNumber(250)); }
### Question: PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } PeerStarter(Config config); static PeerStarter create(Config config); void initialize(); ExecutionContext getExecutionContext(); void setExecutionContext(ExecutionContext executionContext); Storage getStorage(); ITimeProvider getTimeProvider(); void setTimeProvider(ITimeProvider timeProvider); Backlog getBacklog(); void setBacklog(Backlog backlog); BlockchainProvider getBlockchainProvider(); void setBlockchainProvider(BlockchainProvider blockchainProvider); Fork getFork(); void setFork(Fork fork); JrpcServiceProxyFactory getProxyFactory(); void setProxyFactory(JrpcServiceProxyFactory proxyFactory); ISigner getSigner(); void setSigner(ISigner signer); BlockGenerator getBlockGenerator(); void setBlockGenerator(BlockGenerator blockGenerator); BacklogCleaner getCleaner(); void setCleaner(BacklogCleaner cleaner); CryptoProvider getSignatureVerifier(); void setSignatureVerifier(CryptoProvider cryptoProvider); LedgerProvider getLedgerProvider(); void setLedgerProvider(LedgerProvider ledgerProvider); BlockchainEventManager getBlockchainEventManager(); void setBlockchainEventManager(BlockchainEventManager blockchainEventManager); BacklogEventManager getBacklogEventManager(); void setBacklogEventManager(BacklogEventManager backlogEventManager); Config getConfig(); TransactionValidatorFabricImpl getTransactionValidatorFabric(); void setTransactionValidatorFabric(TransactionValidatorFabricImpl transactionValidatorFabric); ITransactionEstimator getEstimator(); void setEstimator(ITransactionEstimator estimator); IAccountHelper getAccountHelper(); void setAccountHelper(IAccountHelper accountHelper); ITransactionMapper getTransactionMapper(); void setTransactionMapper(ITransactionMapper transactionMapper); }### Answer: @Test public void testSyncSnapshotDisable() throws Exception { String connectURI = "jdbc:sqlite:file:memInitializerJsonTest2?mode=memory&cache=shared"; try { PeerStarter ps1 = create(connectURI, genesisJson, genesisForks, true); PeerStarter ps2 = create(connectURI, genesisJson, genesisForks, false); assertTrue("Snapshot mode switched", true); } catch (Exception ex) { assertTrue("Snapshot mode cannot be switched", false); } } @Test public void testSyncSnapshotEnable() throws Exception { String connectURI = "jdbc:sqlite:file:memInitializerJsonTest3?mode=memory&cache=shared"; try { PeerStarter ps1 = create(connectURI, genesisJson, genesisForks, false); PeerStarter ps2 = create(connectURI, genesisJson, genesisForks, true); assertTrue("Snapshot mode switched", false); } catch (Exception ex) { assertTrue("Snapshot mode cannot be switched", true); } }
### Question: VersionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getVersion() != 1) { return ValidationResult.error("Version is not supported."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void unknown_version() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Version is not supported."); Transaction tx = Builder.newTransaction(timeProvider).version(12345).build(networkID, sender); validate(tx); }
### Question: FeePerByteValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); long fee = tx.getFee(); if (fee < length * Constant.TRANSACTION_MIN_FEE_PER_BYTE) { return ValidationResult.error("Invalid fee."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void fee_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(0L).build(networkID, sender); tx.setLength(1); validate(tx); } @Test public void too_small_fee() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(10L).build(networkID, sender); tx.setLength(1024 + 1); validate(tx); }
### Question: FutureTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isFuture(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } FutureTimestampValidationRule(ITimeProvider timeProvider); FutureTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void future_timestamp() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() - 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); }
### Question: TypeValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (allowedTypes.contains(tx.getType())) { return ValidationResult.success; } return ValidationResult.error("Invalid transaction type. Type :" + tx.getType()); } TypeValidationRule(Set<Integer> allowedTypes); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).type(10).build(networkID, sender); validate(tx); } @Test public void unknown_type() throws Exception { int type = 12345; expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction type. Type :" + type); Transaction tx = Builder.newTransaction(timeProvider).type(type).build(networkID, sender); validate(tx); }
### Question: ConfirmationsSetValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Map<String, Object> confirmations = tx.getConfirmations(); if (confirmations == null) { return ValidationResult.success; } Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } Set<AccountID> accounts = accountHelper.getConfirmingAccounts(sender, timeProvider.get()); if (accounts == null) { accounts = new HashSet<>(); } else { accounts = new HashSet<>(accounts); } if (allowPayer && tx.getPayer() != null) { accounts.add(tx.getPayer()); } for (String id : confirmations.keySet()) { AccountID acc; try { acc = new AccountID(id); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (!accounts.contains(acc)) { return ValidationResult.error("Account '" + acc.toString() + "' can not sign transaction."); } } return ValidationResult.success; } ConfirmationsSetValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); boolean isAllowPayer(); void setAllowPayer(boolean allowPayer); }### Answer: @Test public void unset_mfa() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("can not sign transaction."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, delegate1, new ISigner[] { sender, delegate2 }); validate(tx); } @Test public void unspecified_delegate() throws Exception { ISigner unknown = new Signer("33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"); AccountID id = new AccountID(unknown.getPublicKey()); expectedException.expect(ValidateException.class); expectedException.expectMessage("Account '" + id + "' can not sign transaction."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {unknown}); validate(tx); } @Test public void mfa_allow_payer() throws Exception { ISigner unknown = new Signer("33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"); AccountID id = new AccountID(unknown.getPublicKey()); Transaction tx = Builder.newTransaction(timeProvider).payedBy(id).build(networkID, sender, new ISigner[] {unknown}); validate(tx); } @Test public void unset_mfa_allow_payer() throws Exception { AccountID id = new AccountID(sender.getPublicKey()); Transaction tx = Builder.newTransaction(timeProvider).payedBy(id).build(networkID, delegate1, new ISigner[] { sender }); validate(tx); }
### Question: PayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() == null) { return ValidationResult.success; } if (tx.getSenderID().equals(tx.getPayer())) { return ValidationResult.error("Invalid payer"); } if (tx.getConfirmations() == null || !tx.getConfirmations().containsKey(tx.getPayer().toString())) { return ValidationResult.error("Payer not confirm"); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); } @Test public void no_payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void illegal_payer() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid payer"); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(new AccountID(sender.getPublicKey())) .build(networkID, sender); validate(tx); } @Test public void payer_not_confirm() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Payer not confirm"); Transaction tx = Builder.newTransaction(timeProvider).payedBy(payerAccount).build(networkID, sender); validate(tx); }
### Question: ExpiredTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isExpired(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } ExpiredTimestampValidationRule(ITimeProvider timeProvider); ExpiredTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void expired() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() + tx.getDeadline() + 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); }
### Question: DeadlineValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getDeadline() < 1 || tx.getDeadline() > Constant.TRANSACTION_MAX_LIFETIME) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void deadline_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timestamp).deadline((short) 0).build(networkID, sender); validate(tx); } @Test public void deadline_max() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timeProvider) .deadline((short) (Constant.TRANSACTION_MAX_LIFETIME + 1)) .build(networkID, sender); validate(tx); }
### Question: ReferencedTransactionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getReference() != null) { return ValidationResult.error("Illegal reference."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void success_without_note() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Illegal reference."); Transaction tx = Builder.newTransaction(timeProvider).refBy(new TransactionID(12345L)).build(networkID, sender); validate(tx); }
### Question: EmptyPayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() != null) { return ValidationResult.error("Forbidden."); } if (tx.hasNestedTransactions()) { for (Transaction transaction : tx.getNestedTransactions().values()) { ValidationResult result = this.validate(transaction, ledger); if (result.hasError) { return result; } } } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); }### Answer: @Test public void payer_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); } @Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); } @Test public void payer_nested_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); } @Test public void payer_nested_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); }
### Question: Uploader { public void upload(List<MobileEventJson> batch) { try { Request request = makeRequest(batch); if (request != null) { Log.d(TAG, String.format("Uploading batch of size %d", batch.size())); this.doUpload(request, MAX_RETRIES); } } catch (IOException e) { Log.e(TAG, "Encountered IOException in upload", e); } } Uploader(TaskManager taskManager, ConfigProvider configProvider); void upload(List<MobileEventJson> batch); }### Answer: @Test public void testUploadOtherErrorExhaustRetries() throws Exception { WireMock.stubFor(makeCall(429)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(0l), Mockito.eq(TimeUnit.SECONDS)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(3l), Mockito.eq(TimeUnit.SECONDS)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(12l), Mockito.eq(TimeUnit.SECONDS)); WireMock.verify(3, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); } @Test public void testUploadOtherEventualSuccess() throws Exception { WireMock.stubFor(makeCall(429) .inScenario("default") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("failure")); WireMock.stubFor(makeCall(200) .inScenario("default") .whenScenarioStateIs("failure") .willSetStateTo("success") ); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(2, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); } @Test public void testUploadNothing() { Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.<MobileEventJson>emptyList()); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); } @Test public void testUpload200() throws Exception { WireMock.stubFor(makeCall(200)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(1, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); } @Test public void testUpload400() throws Exception { WireMock.stubFor(makeCall(400)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(1, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); }
### Question: Sift { private Sift() { } private Sift(); static void open(@NonNull Context context, Config config, String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); }### Answer: @Test public void testSift() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl( mockContext(preferences), null, "", false, mockTaskManager()); assertNotNull(sift.getConfig()); assertNull(sift.getConfig().accountId); assertNull(sift.getConfig().beaconKey); assertNotNull(sift.getConfig().serverUrlFormat); assertFalse(sift.getConfig().disallowLocationCollection); assertNull(sift.getUserId()); assertNotNull(sift.getQueue(SiftImpl.DEVICE_PROPERTIES_QUEUE_IDENTIFIER)); assertNull(sift.getQueue("some-queue")); assertNotNull(sift.createQueue("some-queue", new Queue.Config.Builder().build())); try { sift.createQueue("some-queue", new Queue.Config.Builder().build()); fail(); } catch (IllegalStateException e) { assertEquals("Queue exists: some-queue", e.getMessage()); } assertTrue(preferences.fields.isEmpty()); }
### Question: Sift { public static synchronized void unsetUserId() { setUserId(null); } private Sift(); static void open(@NonNull Context context, Config config, String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); }### Answer: @Test public void testUnsetUserId() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl(mockContext(preferences), null, "", false, mockTaskManager()); sift.setUserId("gary"); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); MobileEventJson event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertEquals("gary", event.userId); sift.unsetUserId(); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertNull(event.userId); }
### Question: Queue { State unarchive(String archive) { if (archive == null) { return new State(); } try { return Sift.GSON.fromJson(archive, State.class); } catch (JsonSyntaxException e) { Log.d(TAG, "Encountered exception in Queue.State unarchive", e); return new State(); } } Queue(String archive, UserIdProvider userIdProvider, UploadRequester uploadRequester, Queue.Config config); }### Answer: @Test public void testUnarchiveLegacyQueueState() throws IOException, NoSuchFieldException, IllegalAccessException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); String legacyQueueState = "{\"config\":{\"acceptSameEventAfter\":1,\"uploadWhenMoreThan\":2," + "\"uploadWhenOlderThan\":3},\"queue\":[],\"lastEvent\":{\"time\":1513206382563," + "\"user_id\":\"USER_ID\",\"installation_id\":\"a4c7e6b6cae420e9\"," + "\"android_app_state\":{\"activity_class_name\":\"HelloSift\"," + "\"sdk_version\":\"0.9.7\",\"battery_level\":0.5,\"battery_state\":2," + "\"battery_health\":2,\"plug_state\":1," + "\"network_addresses\":[\"10.0.2.15\",\"fe80::5054:ff:fe12:3456\"]}}," + "\"lastUploadTimestamp\":1513206386326}"; Object o = new Queue(null, USER_ID_PROVIDER, uploadRequester, null) .unarchive(legacyQueueState); Field field = o.getClass().getDeclaredField("config"); field.setAccessible(true); Queue.Config config = (Queue.Config) field.get(o); assertEquals(config, new Queue.Config.Builder() .withAcceptSameEventAfter(1) .withUploadWhenMoreThan(2) .withUploadWhenOlderThan(3) .build() ); field = o.getClass().getDeclaredField("lastEvent"); field.setAccessible(true); MobileEventJson lastEvent = (MobileEventJson) field.get(o); assertEquals(lastEvent, new MobileEventJson() .withTime(1513206382563L) .withUserId("USER_ID") .withInstallationId("a4c7e6b6cae420e9") .withAndroidAppState(new AndroidAppStateJson() .withActivityClassName("HelloSift") .withSdkVersion("0.9.7") .withBatteryLevel(0.5) .withBatteryState(2L) .withBatteryHealth(2L) .withPlugState(1L) .withNetworkAddresses(Arrays.asList("10.0.2.15", "fe80::5054:ff:fe12:3456")) ) ); field = o.getClass().getDeclaredField("lastUploadTimestamp"); field.setAccessible(true); long lastUploadTimestamp = (long) field.get(o); assertEquals(lastUploadTimestamp, 1513206386326L); field = o.getClass().getDeclaredField("queue"); field.setAccessible(true); List queue = (List) field.get(o); assertEquals(queue.size(), 0); }
### Question: DaoTransaction extends DaoIdentifiable { public static DaoTransaction createAndPersist(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount) throws NotEnoughMoneyException { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoTransaction transaction = new DaoTransaction(from, to, amount); try { session.save(transaction); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } return transaction; } private DaoTransaction(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount); protected DaoTransaction(); static DaoTransaction createAndPersist(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount); DaoInternalAccount getFrom(); DaoAccount getTo(); BigDecimal getAmount(); Date getCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testCreateAndPersist() { SessionManager.beginWorkUnit(); try { yo.getInternalAccount().setAmount(new BigDecimal("200")); fred.getInternalAccount().setAmount(new BigDecimal("200")); DaoTransaction.createAndPersist(yo.getInternalAccount(), tom.getInternalAccount(), new BigDecimal("120")); assertEquals(0, yo.getInternalAccount().getAmount().compareTo(new BigDecimal("80"))); assertEquals(0, tom.getInternalAccount().getAmount().compareTo(new BigDecimal("120"))); SessionManager.flush(); b219.setExternalAccount(DaoExternalAccount.createAndPersist(b219, AccountType.IBAN, "plop")); DaoTransaction.createAndPersist(fred.getInternalAccount(), b219.getExternalAccount(), new BigDecimal("120")); assertEquals(0, fred.getInternalAccount().getAmount().compareTo(new BigDecimal("80"))); assertEquals(0, b219.getExternalAccount().getAmount().compareTo(new BigDecimal("120"))); } catch (final NotEnoughMoneyException e) { fail(); } SessionManager.endWorkUnitAndFlush(); }
### Question: DaoComment extends DaoKudosable implements DaoCommentable { public static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoComment comment = new DaoComment(father, team, member, text); try { session.save(comment); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createCommentEvent(father.getMilestone().getOffer().getFeature(), EventType.BUG_ADD_COMMENT, father, comment, father.getMilestone().getOffer(), father.getMilestone()); return comment; } private DaoComment(final DaoMember member, final DaoTeam team, final String text); private DaoComment(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); protected DaoComment(); static DaoCommentable getCommentable(final int id); static Long getCommentCount(Date from, Date to); static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); void addChildComment(final DaoComment comment); String getText(); void setText(final String content, final DaoMember author); PageIterable<DaoComment> getChildren(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); @Override void addComment(final DaoComment comment); DaoUserContent getCommented(); DaoComment getFather(); DaoBug getFatherBug(); DaoFeature getFatherFeature(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testCreateAndPersist() { final DaoComment comment = DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), "A text"); assertEquals("A text", comment.getText()); try { DaoComment.createAndPersist((DaoComment) null, null, null, "A text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), ""); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } }
### Question: DaoComment extends DaoKudosable implements DaoCommentable { public void addChildComment(final DaoComment comment) { if (comment == null) { throw new NonOptionalParameterException(); } if (comment == this) { throw new BadProgrammerException("Cannot add ourself as child comment."); } comment.father = this; this.children.add(comment); } private DaoComment(final DaoMember member, final DaoTeam team, final String text); private DaoComment(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); protected DaoComment(); static DaoCommentable getCommentable(final int id); static Long getCommentCount(Date from, Date to); static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); void addChildComment(final DaoComment comment); String getText(); void setText(final String content, final DaoMember author); PageIterable<DaoComment> getChildren(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); @Override void addComment(final DaoComment comment); DaoUserContent getCommented(); DaoComment getFather(); DaoBug getFatherBug(); DaoFeature getFatherFeature(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testAddChildComment() { final DaoComment comment = DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), "A text"); final DaoComment commentChild = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(fred.getLogin()), "A comment"); comment.addChildComment(commentChild); final DaoComment commentChild1 = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(yo.getLogin()), "hello"); comment.addChildComment(commentChild1); final DaoComment commentChild2 = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(tom.getLogin()), "An other text"); comment.addChildComment(commentChild2); final DaoComment commentChildChild = DaoComment.createAndPersist(commentChild1, null, DaoMember.getByLogin(tom.getLogin()), "An other text"); commentChild1.addChildComment(commentChildChild); try { comment.addChildComment(comment); fail(); } catch (final BadProgrammerException e) { assertTrue(true); } try { comment.addChildComment(null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @SuppressWarnings("synthetic-access") public static FeatureImplementation create(final DaoFeature dao) { return new MyCreator().create(dao); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCreate() { final Feature feature = FeatureImplementation.create(DaoFeature.createAndPersist(memberTom.getDao(), null, DaoDescription.createAndPersist(memberTom.getDao(), null, Language.FR, "title", "description"), DaoSoftware.getByName("VLC"))); assertNotNull(feature); assertNull(FeatureImplementation.create(null)); }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessComment(final Action action) { return canAccess(new RgtFeature.Comment(), action); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCanAccessComment() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessComment(Action.READ)); assertFalse(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessComment(Action.READ)); assertTrue(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessComment(Action.READ)); assertTrue(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessContribution(final Action action) { return canAccess(new RgtFeature.Contribute(), action); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCanAccessContribution() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessContribution(Action.READ)); assertFalse(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessContribution(Action.READ)); assertTrue(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessContribution(Action.READ)); assertTrue(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessOffer(final Action action) { return canAccess(new RgtFeature.Offer(), action); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCanAccessOffer() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessOffer(Action.READ)); assertFalse(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessOffer(Action.READ)); assertTrue(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessOffer(Action.READ)); assertTrue(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation) throws UnauthorizedOperationException { tryAccess(new RgtFeature.Offer(), Action.WRITE); final Offer offer = new Offer(AuthToken.getMember(), AuthToken.getAsTeam(), this, amount, description, license, language, dateExpire, secondsBeforeValidation); follow(AuthToken.getMember()); return doAddOffer(offer); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testAddOffer() { final Feature feature = createFeatureByThomas(); assertEquals(FeatureState.PENDING, feature.getFeatureState()); AuthToken.authenticate(memeberFred); assertNull(feature.getSelectedOffer()); assertEquals(0, feature.getOffers().getPageSize()); try { AuthToken.authenticate(memeberFred); feature.addOffer(new BigDecimal("120"), "description", "GNU GPL V3",Language.FR, DateUtils.tomorrow(), 0); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(FeatureState.PREPARING, feature.getFeatureState()); assertNotNull(feature.getSelectedOffer()); assertEquals(FeatureState.PREPARING, feature.getFeatureState()); }
### Question: FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public void cancelDevelopment() throws UnauthorizedOperationException { throwWrongStateExceptionOnNondevelopingState(); getSelectedOffer().tryAccess(new RgtOffer.SelectedOffer(), Action.WRITE); setStateObject(getStateObject().eventDeveloperCanceled()); } FeatureImplementation(final Member author, final Team team, final Language language, final String title, final String description, final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCancelDevelopment() throws NotEnoughMoneyException, UnauthorizedOperationException { final Feature feature = createFeatureAddOffer120AddContribution120BeginDev(); Mockit.setUpMock(DaoFeature.class, new MockFeatureValidationTimeOut()); try { feature.cancelDevelopment(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberYo); feature.cancelDevelopment(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } AuthToken.authenticate(memberTom); assertEquals(120, feature.getContribution().intValue()); feature.cancelDevelopment(); assertEquals(0, feature.getContribution().intValue()); assertEquals(FeatureState.DISCARDED, feature.getFeatureState()); Mockit.tearDownMocks(); }
### Question: DaoVersionedString extends DaoIdentifiable { public void addVersion(final String content, final DaoMember author) { this.currentVersion = new DaoStringVersion(content, this, author); versions.add(currentVersion); } private DaoVersionedString(final String content, final DaoMember author); protected DaoVersionedString(); static DaoVersionedString createAndPersist(final String content, final DaoMember author); void addVersion(final String content, final DaoMember author); void useVersion(final DaoStringVersion version); String getContent(); PageIterable<DaoStringVersion> getVersions(); DaoStringVersion getCurrentVersion(); void compact(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public final void testAddVersion() { final DaoVersionedString str = DaoVersionedString.createAndPersist("plop", fred); str.addVersion("plip", tom); assertEquals(str.getContent(), "plip"); assertEquals(str.getCurrentVersion().getAuthor(), tom); }
### Question: Actor extends Identifiable<T> { public final String getLogin() { return getDao().getLogin(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetLogin() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getLogin(), db.getTom().getLogin()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getLogin(), db.getPublicGroup().getLogin()); }
### Question: Actor extends Identifiable<T> { public final Date getDateCreation() throws UnauthorizedPublicReadOnlyAccessException { tryAccess(new RgtActor.DateCreation(), Action.READ); return getDao().getDateCreation(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetDateCreation() { final Member tom = Member.create(db.getTom()); try { assertEquals(tom.getDateCreation().getTime(), db.getTom().getDateCreation().getTime()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { assertEquals(publicTeam.getDateCreation(), db.getPublicGroup().getDateCreation()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } }
### Question: Actor extends Identifiable<T> { public final InternalAccount getInternalAccount() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.InternalAccount(), Action.READ); return InternalAccount.create(getDao().getInternalAccount()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetInternalAccount() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getInternalAccount().getId(), db.getTom().getInternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getInternalAccount(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getInternalAccount().getId(), db.getPublicGroup().getInternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } }
### Question: Actor extends Identifiable<T> { public final ExternalAccount getExternalAccount() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.ExternalAccount(), Action.READ); return ExternalAccount.create(getDao().getExternalAccount()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetExternalAccount() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getExternalAccount().getId(), db.getTom().getExternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getExternalAccount(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getExternalAccount().getId(), db.getPublicGroup().getExternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } }
### Question: Actor extends Identifiable<T> { public final PageIterable<BankTransaction> getBankTransactions() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.BankTransaction(), Action.READ); return new BankTransactionList(getDao().getBankTransactions()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetBankTransactions() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getBankTransactions().size(), db.getTom().getBankTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getBankTransactions(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getBankTransactions().size(), db.getPublicGroup().getBankTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } }
### Question: Actor extends Identifiable<T> { public PageIterable<Contribution> getContributions() { return doGetContributions(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetContributions() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getContributions().size(), db.getTom().getContributions(true).size()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getContributions().size(), db.getPublicGroup().getContributions().size()); }
### Question: Actor extends Identifiable<T> { public abstract String getDisplayName(); protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testGetDisplayName() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getDisplayName(), db.getTom().getFullname()); }
### Question: Actor extends Identifiable<T> { public final boolean canAccessDateCreation() { return canAccess(new RgtActor.DateCreation(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testCanAccessDateCreation() { final Member tom = Member.create(db.getTom()); assertTrue(tom.canAccessDateCreation()); }
### Question: Actor extends Identifiable<T> { public final boolean canGetInternalAccount() { return canAccess(new RgtActor.InternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testCanGetInternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetInternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetInternalAccount()); }
### Question: Actor extends Identifiable<T> { public final boolean canGetExternalAccount() { return canAccess(new RgtActor.ExternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testCanGetExternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetExternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetExternalAccount()); }
### Question: DaoVersionedString extends DaoIdentifiable { public void compact() { String previousContent = null; for (final DaoStringVersion version : versions) { if (!version.isCompacted()) { final String savedContent = version.getContent(); if (previousContent != null) { version.compact(previousContent); } previousContent = savedContent; } else { if (previousContent == null) { throw new BadProgrammerException("First string version should never be compacted !"); } previousContent = version.getContentUncompacted(previousContent); } } } private DaoVersionedString(final String content, final DaoMember author); protected DaoVersionedString(); static DaoVersionedString createAndPersist(final String content, final DaoMember author); void addVersion(final String content, final DaoMember author); void useVersion(final DaoStringVersion version); String getContent(); PageIterable<DaoStringVersion> getVersions(); DaoStringVersion getCurrentVersion(); void compact(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public final void testCompact() { final DaoVersionedString str = DaoVersionedString.createAndPersist("plop", fred); str.addVersion("plop\nplip\n", fred); str.addVersion("plop\nplup\n", fred); str.addVersion("plop\nplup\nplop\ncoucou\nHello\n", fred); str.addVersion("plop\nplup\nplop\ncoucou\n", fred); str.compact(); Iterator<DaoStringVersion> iterator = str.getVersions().iterator(); assertEquals(iterator.next().getContent(), "plop"); assertEquals(iterator.next().getContentUncompacted("plop"), "plop\nplip\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplip\n"), "plop\nplup\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplup\n"), "plop\nplup\nplop\ncoucou\nHello\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplup\nplop\ncoucou\nHello\n"), "plop\nplup\nplop\ncoucou\n"); iterator = str.getVersions().iterator(); assertFalse(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); }
### Question: Actor extends Identifiable<T> { public final boolean canGetBankTransactionAccount() { return canAccess(new RgtActor.BankTransaction(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testCanGetBankTransactionAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetBankTransactionAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetBankTransactionAccount()); }
### Question: Actor extends Identifiable<T> { public final boolean canGetContributions() { return canAccess(new RgtActor.Contribution(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer: @Test public final void testCanGetContributions() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertTrue(tom.canGetContributions()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertTrue(publicTeam.canGetContributions()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetMessage() { return canAccess(new RgtBankTransaction.Message(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetMessage() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetMessage()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetMessage()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetMessage()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetMessage()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetMessage()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetMessage()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetValuePaid() { return canAccess(new RgtBankTransaction.ValuePaid(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetValuePaid() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetValuePaid()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetValuePaid()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetValuePaid()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetValue() { return canAccess(new RgtBankTransaction.Value(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetValue() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetValue()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetValue()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetValue()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetValue()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetValue()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetValue()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetState() { return canAccess(new RgtBankTransaction.State(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetState() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetState()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetState()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetState()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetState()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetState()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetState()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetCreationDate() { return canAccess(new RgtBankTransaction.CreationDate(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetCreationDate() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetCreationDate()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetCreationDate()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetCreationDate()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetModificationDate() { return canAccess(new RgtBankTransaction.ModificationDate(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetModificationDate() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetModificationDate()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetModificationDate()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetModificationDate()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetReference() { return canAccess(new RgtBankTransaction.Reference(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetReference() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetReference()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetReference()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetReference()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetReference()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetReference()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetReference()); }
### Question: BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetAuthor() { return canAccess(new RgtBankTransaction.Author(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; }### Answer: @Test public final void testCanGetAuthor() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetAuthor()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetAuthor()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetAuthor()); }
### Question: DaoDescription extends DaoIdentifiable { public static DaoDescription createAndPersist(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); if (member == null || language == null || title == null || title.isEmpty() || description == null || description.isEmpty()) { throw new NonOptionalParameterException(); } final DaoDescription descr = new DaoDescription(member, team, language, title, description); try { session.save(descr); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } return descr; } private DaoDescription(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description); protected DaoDescription(); static DaoDescription createAndPersist(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description); void addTranslation(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description); void setDefaultLanguage(final Language defaultLanguage); DaoTranslation getDefaultTranslation(); PageIterable<DaoTranslation> getTranslations(); DaoTranslation getTranslation(final Language language); Language getDefaultLanguage(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testCreateAndPersist() { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", "a text"); try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", ""); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, null, "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, null, "A title", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(null, null, Language.FR, "A title", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } }
### Question: Account extends Identifiable<T> { public final boolean canAccessTransaction() { return canAccess(new RgtAccount.Transaction(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testCanAccessTransaction() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessTransaction()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessTransaction()); }
### Question: Account extends Identifiable<T> { public final boolean canAccessAmount() { return canAccess(new RgtAccount.Amount(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testCanAccessAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessAmount()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessAmount()); }
### Question: Account extends Identifiable<T> { public final boolean canAccessActor() { return canAccess(new RgtAccount.Actor(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testCanAccessActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessActor()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessActor()); }
### Question: Account extends Identifiable<T> { public final boolean canAccessCreationDate() { return canAccess(new RgtAccount.CreationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testCanAccessCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessCreationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessCreationDate()); }
### Question: Account extends Identifiable<T> { public final boolean canAccessLastModificationDate() { return canAccess(new RgtAccount.LastModificationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testCanAccessLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessLastModificationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessLastModificationDate()); }
### Question: Account extends Identifiable<T> { public final Date getLastModificationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.LastModificationDate(), Action.READ); return getDao().getLastModificationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testGetLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getLastModificationDate(); assertEquals(tomAccount.getLastModificationDate(), db.getTom().getInternalAccount().getLastModificationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getLastModificationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getLastModificationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
### Question: Account extends Identifiable<T> { public final BigDecimal getAmount() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Amount(), Action.READ); return getDao().getAmount(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testGetAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getAmount(); assertEquals(tomAccount.getAmount(), db.getTom().getInternalAccount().getAmount()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
### Question: Account extends Identifiable<T> { public final PageIterable<Transaction> getTransactions() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Transaction(), Action.READ); return new TransactionList(getDao().getTransactions()); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testGetTransactions() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getTransactions(); assertEquals(tomAccount.getTransactions().size(), db.getTom().getInternalAccount().getTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
### Question: Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testGetActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getActor(); assertEquals(tomAccount.getActor().getId(), db.getTom().getInternalAccount().getActor().getId()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
### Question: Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer: @Test public void testGetCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getCreationDate(); assertEquals(tomAccount.getCreationDate(), db.getTom().getInternalAccount().getCreationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
### Question: DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); DaoMember getMember(); DaoActor getAuthor(); Date getCreationDate(); DaoTeam getAsTeam(); PageIterable<DaoFileMetadata> getFiles(); boolean isDeleted(); void setIsDeleted(final Boolean isDeleted); void addFile(final DaoFileMetadata daoFileMetadata); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void testGetAuthor() { assertEquals(yo, feature.getMember()); }
### Question: DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testCreateFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, yo.getFeatures(false).iterator().next()); } @Test public void testRetrieveFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, DBRequests.getAll(DaoFeature.class).iterator().next()); assertEquals(yo, feature.getMember()); }
### Question: DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testAddOffer() { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature = DBRequests.getById(DaoFeature.class, feature.getId()); feature.addOffer(createOffer(feature)); assertEquals(1, feature.getOffers().size()); }
### Question: DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }### Answer: @Test public void testAddComment() throws Throwable { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "4")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "3")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "2")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "1")); feature = DBRequests.getById(DaoFeature.class, feature.getId()); assertEquals(4, feature.getComments().size()); }
### Question: JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); }### Answer: @Test public void testMinimal() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("\n[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); } @Test public void testMinimalNoComment() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); }
### Question: JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }### Answer: @Test public void testExtractAttributesMultiline() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("bar jim", doc.getAttribute("foo")); }
### Question: KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); static final String SPEAKEASY_KEY_SEPARATOR; }### Answer: @Test public void testKeyFromFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.jar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1-bar-2.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.0.zip")); assertEquals("foo-bar", KeyExtractor.extractFromFilename("foo-bar.zip")); } @Test public void testKeyFromTempFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar.zip")); assertEquals("foo-1", KeyExtractor.extractFromFilename("foo-1----speakeasy-jim.jar")); }
### Question: RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } static List<String> getEntries(File root); static List<String> walk(URI root, File dir); }### Answer: @Test public void testGetEntries() throws IOException { final File dir = tmp.newFolder("names"); new File(dir, "foo.txt").createNewFile(); new File(dir, "a/b").mkdirs(); new File(dir, "a/bar.txt").createNewFile(); new File(dir, "c").mkdirs(); assertEquals(newArrayList("a/", "a/b/", "a/bar.txt", "c/", "foo.txt"), RepositoryDirectoryUtil.getEntries(dir)); }