target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testFindValidLogs() { Map<String[], Long> mapIO = new HashMap<String[], Long>() {{ put(new String[]{}, -1L); put(new String[]{"o 1"}, 1L); put(new String[]{"?", "o 1"}, -1L); put(new String[]{"I 1", "?", "O 1"}, -1L); put(new String[]{"i 2", "o 1"}, 2L); put(new String[]{"?", "O 1", "?", "O 2"}, -1L); }}; for (Map.Entry<String[], Long> io : mapIO.entrySet()) { List<String> ar = new ArrayList<String>(); for (String str : io.getKey()) { ar.add(str); } Assert.assertEquals( io.getValue().longValue(), Coupon.findValidLogs(ar) ); } }
public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; }
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } }
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } }
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } static void main(String[] args); static long findValidLogs(List<String> logs); }
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } static void main(String[] args); static long findValidLogs(List<String> logs); }
@Test public void testElectionWinner() { String ret = ElectionWinner.electionWinner(new String[] {"Alex", "Michael", "harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"}); Assert.assertEquals("Michael", ret); }
public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; }
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } }
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } }
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } static String electionWinner(String[] votes); }
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } static String electionWinner(String[] votes); }
@Test public void testDeltaEncode() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{25626, 25757, 24367, 24267, 16, 100, 2, 7277}, new int[]{25626, -128, 131, -128, -1390, -100, -128, -24251, 84, -98, -128, 7275}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = DeltaEncode.delta_encode(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } }
public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; }
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } }
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } }
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } static int[] delta_encode(final int[] array); }
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } static int[] delta_encode(final int[] array); }
@Test public void testZombieCluster() { Map<String[], Integer> mapIO = new HashMap<String[], Integer>() {{ put(new String[]{"10000", "01000", "00100", "00010", "00001"}, 5); put(new String[]{"1100", "1110", "0110", "0001"}, 2); }}; for (Map.Entry<String[], Integer> io : mapIO.entrySet()) { int ret = ZombieCluster.zombieCluster(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; }
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }
@Test public void testGetDay() { Map<String[], String> mapIO = new HashMap<String[], String>() {{ put(new String[]{"05", "08", "2015"}, "WEDNESDAY"); put(new String[]{"04", "06", "2018"}, "MONDAY"); put(new String[]{"06", "06", "2018"}, "WEDNESDAY"); }}; for (Map.Entry<String[], String> io : mapIO.entrySet()) { String[] params = io.getKey(); String ret = GetDay.getDay(params[0], params[1], params[2]); Assert.assertEquals(io.getValue(), ret); } }
public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; }
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } }
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } }
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } static String getDay(String day, String month, String year); }
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } static String getDay(String day, String month, String year); }
@Test public void testGetRanks() { Map<List<int[]>, int[]> ioMap = new HashMap<List<int[]>, int[]>() {{ put(new ArrayList() {{ add(new int[] {100, 100, 50, 40, 40, 20, 10}); add(new int[] {5, 25, 50, 120}); }}, new int[] {6, 4, 2, 1}); }}; for (Map.Entry<List<int[]>, int[]> io : ioMap.entrySet()) { int[] ranks = LeaderBoard.getRanks(io.getKey().get(0), io.getKey().get(1)); Assert.assertArrayEquals(ranks, io.getValue()); } }
public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; }
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } }
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } }
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } static int[] getRanks(int[] scores, int[] alice); static void main(String[] args); }
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } static int[] getRanks(int[] scores, int[] alice); static void main(String[] args); }
@Test public void testWaitingTime() { Map<int[], long[]> mapIO = new HashMap<int[], long[]>(){{ put(new int[]{2, 6, 3, 4, 5}, new long[]{2, 12}); put(new int[]{1, 1, 1, 1}, new long[]{0, 1}); put(new int[]{5, 5, 2, 3}, new long[]{3, 11}); }}; for(Map.Entry<int[], long[]> io : mapIO.entrySet()) { long ret = WaitingTime.waitingTime(io.getKey(), (int)io.getValue()[0]); Assert.assertEquals(io.getValue()[1], ret); } }
public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; }
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } }
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } }
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } static long waitingTime(int[] tickets, int p); }
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } static long waitingTime(int[] tickets, int p); }
@Test public void testMain() { Hello.main(null); }
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); }
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } }
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } }
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); }
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); }
@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); } }
public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); }
IP { public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); } }
IP { public static boolean isValid(String ip) { if (ip == null || ip.length() <= 0) { return false; } return ip.trim().matches(new MyRegex().pattern); } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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]) ); } }
public static int winOrLose(long first, long second) { if (first > second) return 1; else if (first < second) return 0; return random.nextBoolean() ? 1 : 0; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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); }
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); } }
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); } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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; } }
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; } }
@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); }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; }
SubStr { public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; } }
SubStr { public static String[] splitTokens(String str) { if (str == null || str.trim().length() <= 0) { return null; } String[] strArr = str.trim().split("[ !,?._'@]+"); return strArr; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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(); }
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(); } }
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(); } }
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(); } }
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(); } }
@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) ); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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); }
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); }
@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); } }
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; }
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; } }
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; } }
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; } }
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; } }
@Test public void testGetInstrumentedObject() { AopInstrumenter instrumenter = new AopInstrumenter(); AopService service = (AopService) instrumenter.getInstrumentedClass(AopServiceImpl.class); service.findInfo("Instrumenter from test"); }
public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); }
AopInstrumenter implements MethodInterceptor { public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } }
AopInstrumenter implements MethodInterceptor { public Object getInstrumentedClass(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } }
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); }
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); }
@Test public void testApp() { App.main(null); }
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"); }
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"); } }
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"); } }
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); }
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); }
@Test public void testGetAopProxyedObject() { AopService service = (AopService) AopFactory.getAopProxyedObject(AopServiceImpl.class.getName()); service.findInfo("Jonn from test"); }
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; }
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; } }
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; } }
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); }
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); }
@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); }
public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; }
RedisService { public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; } }
RedisService { public long incr(String key) { Long ret = strValOps.increment(key, 1L); return ret == null ? 0 : ret; } }
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); }
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); }
@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()); }
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
@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()); }
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
@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()); }
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
@Test void testNoHook() throws ClassNotFoundException, IOException { SortedSet<HookMetadata> result = parser.parse(className -> className.equals(HookMetadataParserTest.class.getName())); Assertions.assertTrue(result.isEmpty()); }
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
HookMetadataParser { SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); } HookMetadataParser(Collection<Path> hookJars); SortedSet<HookMetadata> parse(Predicate<String> classNameFilter); }
@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()); }
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."); }
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."); } }
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); }
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); }
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); }
@Test void testCmdlineParserVersioned() { String[] cmdlineArgs = new String[] { "-javaagent:promagent-1.0-SNAPSHOT.jar" }; assertEquals("promagent-1.0-SNAPSHOT.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString()); }
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."); }
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."); } }
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); }
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); }
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); }
@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")); }
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."); }
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."); } }
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); }
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); }
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); }
@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()); }
@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 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 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); }
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); }
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); }
@Test public void success_without_note() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@Test public void check_alphabet() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).note(alphabet).build(networkID, sender); validate(tx); }
@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 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 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); }
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); }
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); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@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; }
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; } }
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; } }
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); }
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); }
@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); }
@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; }
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; } }
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; } }
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); }
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); }
@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]); }
@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 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 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); }
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); }
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); }
@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())); }
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 { 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 { 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); }
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); }
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); }
@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())); }
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 { 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 { 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); }
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); }
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); }
@Test public void getState_for_notexisting_account() throws Exception { assertEquals(AccountBotService.State.NotFound, service.getState(new AccountID(12345L).toString())); }
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 { 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 { 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); }
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); }
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); }
@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); }
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 { 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 { 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); }
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); }
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); }
@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); }
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 { 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 { 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); }
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); }
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); }
@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)); }
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 { 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 { 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); }
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); }
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); }
@Test public void getInformation_for_existing_account() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(100); account = AccountProperties.setProperty(account, validationMode); account = AccountProperties.setProperty(account, new GeneratingBalanceProperty(1000L, 0)); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); Assert.assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertTrue(1000L == info.deposit); assertNull(info.votingRights); assertNull(info.quorum); assertEquals(AccountBotService.SignType.Normal, info.signType); assertNull(info.coloredCoin); }
public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
@Test public void getInformation_for_existing_colored_coin() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(100); account = AccountProperties.setProperty(account, validationMode); account = AccountProperties.setProperty(account, new GeneratingBalanceProperty(1000L, 0)); ColoredCoinProperty coloredCoin = new ColoredCoinProperty(); coloredCoin.setEmitMode(ColoredCoinEmitMode.PRESET); coloredCoin.setAttributes(new ColoredCoinProperty.Attributes(2, 0)); coloredCoin.setMoneySupply(50000L); account = AccountProperties.setProperty(account, coloredCoin); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertTrue(1000L == info.deposit); assertNull(info.votingRights); assertNull(info.quorum); assertEquals(AccountBotService.SignType.Normal, info.signType); Assert.assertEquals(info.coloredCoin, new ColoredCoinID(id).toString()); }
public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
@Test public void getInformation_for_public_account() throws Exception { String seed = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; ISigner signer = new TestSigner(seed); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setPublicMode(seed); validationMode.setWeightForAccount(new AccountID(1L), 70); validationMode.setWeightForAccount(new AccountID(2L), 50); validationMode.setTimestamp(0); account = AccountProperties.setProperty(account, validationMode); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(AccountBotService.SignType.Public, info.signType); assertEquals(seed, info.seed); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertNull(info.quorum); assertNull(info.votingRights.weight); assertTrue(info.votingRights.delegates.get(new AccountID(1L).toString()) == 70); assertTrue(info.votingRights.delegates.get(new AccountID(2L).toString()) == 50); assertTrue(info.votingRights.delegates.size() == 2); assertNull(info.coloredCoin); }
public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
@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]); }
@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 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 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); }
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); }
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); }
@Test public void getInformation_for_mfa_account() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(70); validationMode.setWeightForAccount(new AccountID(1L), 40); validationMode.setQuorum(40); validationMode.setQuorum(TransactionType.Payment, 90); validationMode.setTimestamp(0); account = AccountProperties.setProperty(account, validationMode); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(AccountBotService.SignType.MFA, info.signType); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertTrue(info.quorum.quorum == 40); assertTrue(info.quorum.quorumByTypes.get(TransactionType.Payment) == 90); assertTrue(info.quorum.quorumByTypes.size() == 1); assertTrue(info.votingRights.weight == 70); assertTrue(info.votingRights.delegates.get(new AccountID(1L).toString()) == 40); assertTrue(info.votingRights.delegates.size() == 1); assertNull(info.coloredCoin); }
public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
@Test public void getInformation_for_notexisting_account() throws Exception { AccountBotService.Info info = service.getInformation(new AccountID(12345L).toString()); assertEquals(AccountBotService.State.Unauthorized, info.state); assertNull(info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertNull(info.signType); assertNull(info.quorum); assertNull(info.votingRights); assertNull(info.coloredCoin); }
public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); }
@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); }
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 { 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 { 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); }
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); }
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); }
@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); }
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 { 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 { 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); }
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); }
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); }
@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); }
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 { 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 { 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); }
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); }
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); }
@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)); }
@Override public boolean isCome(int timestamp) { return items.getFirst().isCome(timestamp); }
Fork implements IFork { @Override public boolean isCome(int timestamp) { return items.getFirst().isCome(timestamp); } }
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); }
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); }
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); }
@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)); }
@Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); }
Fork implements IFork { @Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); } }
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); }
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); }
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); }
@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)); }
@Override public int getNumber(int timestamp) { Item item = getItem(timestamp); return (item == null) ? -1 : item.getNumber(); }
Fork implements IFork { @Override public int getNumber(int timestamp) { Item item = getItem(timestamp); return (item == null) ? -1 : item.getNumber(); } }
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); }
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); }
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); }
@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); } }
public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; }
PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } }
PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } PeerStarter(Config config); }
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); }
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); }
@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); } }
public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; }
PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } }
PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } PeerStarter(Config config); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@Test public void test_reference() { tx.setReference(new TransactionID(132L)); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J9:REFERENCE23:EON-T-66222-22222-2224L6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
@Test public void test_attachment() { tx.setData(new HashMap<String, Object>() { { put("int", 123); put("str", "data"); } }); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTD3:INTI123E3:STR4:DATAE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
@Test public void test_note() { tx.setNote("test"); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J4:NOTE4:TEST6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
@Test public void test_nested() { Transaction tx2 = new Transaction(); tx2.setVersion(1); tx2.setFee(10); tx2.setTimestamp(1); tx2.setDeadline(3600); tx2.setType(100); tx2.setSenderID(new AccountID(100L)); tx2.setSignature(new byte[64]); tx.setNestedTransactions(new HashMap<String, Transaction>() { { put(tx2.getID().toString(), tx2); } }); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE5:BILLSD23:EON-T-32222-2NVPE-L3ZGVD10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EEE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
@Test public void test_payer() { tx.setPayer(new AccountID(123L)); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J5:PAYER21:EON-V5222-22222-22JXK6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); }
@Test public void transaction_base() throws Exception { Transaction a = Builder.newTransaction(timestamp).attach(null).build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void transaction_contains_reference() throws Exception { Transaction a = Builder.newTransaction(timestamp).attach(null).refBy(referencedTx).build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void transaction_contains_nested_transaction() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .addNested(Builder.newTransaction(timestamp).build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp).build(networkID, signer2)) .build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void transaction_contains_confirmations() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .build(networkID, signer, new ISigner[] {signer1, signer2}); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void transaction_contains_payer() throws Exception { Transaction a = Builder.newTransaction(timestamp) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer, new ISigner[] {signer1, signer2}); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@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); }
@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 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 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); }
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); }
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); }
@Test public void transaction_contains_nested_transaction_payed() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .addNested(Builder.newTransaction(timestamp) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp) .payedBy(new AccountID(signer1.getPublicKey())) .build(networkID, signer2)) .build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void db_transaction_format() throws Exception { Transaction tx1 = Builder.newTransaction(timestamp).build(networkID, signer1); Transaction tx2 = Builder.newTransaction(timestamp).build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp) .refBy(referencedTx) .attach(attachment) .note("note") .addNested(tx1) .addNested(tx2) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer, new ISigner[] {signer1, signer2}); DbTransaction dbTx = DTOConverter.convert(tx); Assert.assertEquals(dbTx.getVersion(), tx.getVersion()); Assert.assertEquals(dbTx.getType(), tx.getType()); Assert.assertEquals(dbTx.getTimestamp(), timestamp); Assert.assertEquals(dbTx.getDeadline(), 3600); Assert.assertEquals(dbTx.getFee(), 10L); Assert.assertEquals(dbTx.getNote(), "note"); Assert.assertEquals(dbTx.getReference(), referencedTx.getValue()); Assert.assertEquals(dbTx.getSenderID(), new AccountID(signer.getPublicKey()).getValue()); Assert.assertEquals(dbTx.getSignature(), Format.convert(tx.getSignature())); Assert.assertEquals(dbTx.getAttachment(), new String(bencode.encode(attachment))); Assert.assertEquals(dbTx.getConfirmations(), new String(bencode.encode(tx.getConfirmations()))); Assert.assertEquals(dbTx.getPayerID(), tx.getPayer().getValue()); Map<String, Object> map = new HashMap<>(); map.put(tx1.getID().toString(), StorageTransactionMapper.convert(tx1)); map.put(tx2.getID().toString(), StorageTransactionMapper.convert(tx2)); Assert.assertEquals(dbTx.getNestedTransactions(), new String(bencode.encode(map))); }
public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getVersion() != 1) { return ValidationResult.error("Version is not supported."); } return ValidationResult.success; }
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; } }
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; } }
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); }
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); }
@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); }
@Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getVersion() != 1) { return ValidationResult.error("Version is not supported."); } return ValidationResult.success; }
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; } }
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; } }
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); }
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); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@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; }
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; } }
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; } }
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); }
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); }
@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); }
@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; }
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; } }
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; } }
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); }
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); }
@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); }
@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; }
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; } }
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; } }
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); }
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); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isFuture(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; }
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 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); }
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); }
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); }
@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); }
@Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isFuture(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; }
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 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); }
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); }
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); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).type(10).build(networkID, sender); validate(tx); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); }
@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; }
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; } }
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; } }
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); }
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); }
@Test public void no_payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@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; }
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; } }
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; } }
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); }
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); }
@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); }
@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; }
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; } }
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; } }
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); }
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); }
@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); }
@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; }
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; } }
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; } }
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); }
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); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; }
SignatureValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; } }
SignatureValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; } SignatureValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); }
SignatureValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; } SignatureValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); }
SignatureValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; } SignatureValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); }
@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); }
@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 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 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); }
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); }
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); }