src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
MigrateUtils { public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum); static int getCurTotalSizeForTask(List<MigrateTask> rangeList); static int getCurTotalSize(List<NodeIndexRange> slots); static void merge(List<List<NodeIndexRange>> copy, SortedMap<String, List<MigrateTask>> tasks); static List<List<NodeIndexRange>> copy(List<List<NodeIndexRange>> integerListMap); }
@Test public void balanceExpand() { List<List<NodeIndexRange>> integerListMap = new ArrayList<>(); integerListMap.add(Lists.newArrayList(new NodeIndexRange(0, 0, 32))); integerListMap.add(Lists.newArrayList(new NodeIndexRange(1, 33, 65))); integerListMap.add(Lists.newArrayList(new NodeIndexRange(2, 66, 99))); int totalSlots = 100; List<String> oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3"); List<String> newDataNodes = Lists.newArrayList("dn4", "dn5"); SortedMap<String, List<MigrateTask>> tasks = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn4=[MigrateTask{from='dn1'\n" + ", to='dn4'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=12)]\n" + "}, MigrateTask{from='dn2'\n" + ", to='dn4'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=33, valueEnd=39)]\n" + "}], dn5=[MigrateTask{from='dn2'\n" + ", to='dn5'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=45)]\n" + "}, MigrateTask{from='dn3'\n" + ", to='dn5'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=79)]\n" + "}]}", Objects.toString(tasks)); merge(integerListMap, tasks); oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3", "dn4", "dn5"); newDataNodes = Lists.newArrayList("dn6", "dn7", "dn8", "dn9"); SortedMap<String, List<MigrateTask>> tasks1 = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn6=[MigrateTask{from='dn1'\n" + ", to='dn6'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=13, valueEnd=21)]\n" + "}, MigrateTask{from='dn2'\n" + ", to='dn6'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=46, valueEnd=48)]\n" + "}], dn7=[MigrateTask{from='dn2'\n" + ", to='dn7'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=49, valueEnd=54)]\n" + "}, MigrateTask{from='dn3'\n" + ", to='dn7'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=80, valueEnd=84)]\n" + "}], dn8=[MigrateTask{from='dn3'\n" + ", to='dn8'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=85, valueEnd=88)]\n" + "}, MigrateTask{from='dn4'\n" + ", to='dn8'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=6)]\n" + "}], dn9=[MigrateTask{from='dn4'\n" + ", to='dn9'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=7, valueEnd=8)]\n" + "}, MigrateTask{from='dn5'\n" + ", to='dn9'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=45), NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=68)]\n" + "}]}", Objects.toString(tasks1)); merge(integerListMap, tasks1); oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3", "dn4", "dn5", "dn6", "dn7", "dn8", "dn9"); newDataNodes = Lists.newArrayList("dn10", "dn11", "dn12", "dn13", "dn14", "dn15", "dn16", "dn17", "dn18", "dn19", "dn20", "dn21", "dn22", "dn23", "dn24", "dn25", "dn26", "dn27", "dn28", "dn29", "dn30", "dn31", "dn32", "dn33", "dn34", "dn35", "dn36", "dn37", "dn38", "dn39", "dn40", "dn41", "dn42", "dn43", "dn44", "dn45", "dn46", "dn47", "dn48", "dn49", "dn50", "dn51", "dn52", "dn53", "dn54", "dn55", "dn56", "dn57", "dn58", "dn59", "dn60", "dn61", "dn62", "dn63", "dn64", "dn65", "dn66", "dn67", "dn68", "dn69", "dn70", "dn71", "dn72", "dn73", "dn74", "dn75", "dn76", "dn77", "dn78", "dn79", "dn80", "dn81", "dn82", "dn83", "dn84", "dn85", "dn86", "dn87", "dn88", "dn89", "dn90", "dn91", "dn92", "dn93", "dn94", "dn95", "dn96", "dn97", "dn98", "dn99", "dn100"); SortedMap<String, List<MigrateTask>> tasks2 = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn10=[MigrateTask{from='dn1'\n" + ", to='dn10'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=22, valueEnd=22)]\n" + "}], dn100=[MigrateTask{from='dn9'\n" + ", to='dn100'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=67, valueEnd=67)]\n" + "}], dn11=[MigrateTask{from='dn1'\n" + ", to='dn11'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=23, valueEnd=23)]\n" + "}], dn12=[MigrateTask{from='dn1'\n" + ", to='dn12'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=24, valueEnd=24)]\n" + "}], dn13=[MigrateTask{from='dn1'\n" + ", to='dn13'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=25, valueEnd=25)]\n" + "}], dn14=[MigrateTask{from='dn1'\n" + ", to='dn14'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=26, valueEnd=26)]\n" + "}], dn15=[MigrateTask{from='dn1'\n" + ", to='dn15'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=27, valueEnd=27)]\n" + "}], dn16=[MigrateTask{from='dn1'\n" + ", to='dn16'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=28, valueEnd=28)]\n" + "}], dn17=[MigrateTask{from='dn1'\n" + ", to='dn17'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=29, valueEnd=29)]\n" + "}], dn18=[MigrateTask{from='dn1'\n" + ", to='dn18'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=30, valueEnd=30)]\n" + "}], dn19=[MigrateTask{from='dn1'\n" + ", to='dn19'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=31, valueEnd=31)]\n" + "}], dn20=[MigrateTask{from='dn2'\n" + ", to='dn20'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=55, valueEnd=55)]\n" + "}], dn21=[MigrateTask{from='dn2'\n" + ", to='dn21'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=56, valueEnd=56)]\n" + "}], dn22=[MigrateTask{from='dn2'\n" + ", to='dn22'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=57, valueEnd=57)]\n" + "}], dn23=[MigrateTask{from='dn2'\n" + ", to='dn23'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=58, valueEnd=58)]\n" + "}], dn24=[MigrateTask{from='dn2'\n" + ", to='dn24'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=59, valueEnd=59)]\n" + "}], dn25=[MigrateTask{from='dn2'\n" + ", to='dn25'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=60, valueEnd=60)]\n" + "}], dn26=[MigrateTask{from='dn2'\n" + ", to='dn26'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=61, valueEnd=61)]\n" + "}], dn27=[MigrateTask{from='dn2'\n" + ", to='dn27'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=62, valueEnd=62)]\n" + "}], dn28=[MigrateTask{from='dn2'\n" + ", to='dn28'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=63, valueEnd=63)]\n" + "}], dn29=[MigrateTask{from='dn2'\n" + ", to='dn29'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=64, valueEnd=64)]\n" + "}], dn30=[MigrateTask{from='dn3'\n" + ", to='dn30'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=89, valueEnd=89)]\n" + "}], dn31=[MigrateTask{from='dn3'\n" + ", to='dn31'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=90, valueEnd=90)]\n" + "}], dn32=[MigrateTask{from='dn3'\n" + ", to='dn32'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=91, valueEnd=91)]\n" + "}], dn33=[MigrateTask{from='dn3'\n" + ", to='dn33'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=92, valueEnd=92)]\n" + "}], dn34=[MigrateTask{from='dn3'\n" + ", to='dn34'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=93, valueEnd=93)]\n" + "}], dn35=[MigrateTask{from='dn3'\n" + ", to='dn35'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=94, valueEnd=94)]\n" + "}], dn36=[MigrateTask{from='dn3'\n" + ", to='dn36'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=95, valueEnd=95)]\n" + "}], dn37=[MigrateTask{from='dn3'\n" + ", to='dn37'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=96, valueEnd=96)]\n" + "}], dn38=[MigrateTask{from='dn3'\n" + ", to='dn38'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=97, valueEnd=97)]\n" + "}], dn39=[MigrateTask{from='dn3'\n" + ", to='dn39'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=98, valueEnd=98)]\n" + "}], dn40=[MigrateTask{from='dn4'\n" + ", to='dn40'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=9, valueEnd=9)]\n" + "}], dn41=[MigrateTask{from='dn4'\n" + ", to='dn41'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=10, valueEnd=10)]\n" + "}], dn42=[MigrateTask{from='dn4'\n" + ", to='dn42'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=11, valueEnd=11)]\n" + "}], dn43=[MigrateTask{from='dn4'\n" + ", to='dn43'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=12, valueEnd=12)]\n" + "}], dn44=[MigrateTask{from='dn4'\n" + ", to='dn44'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=33, valueEnd=33)]\n" + "}], dn45=[MigrateTask{from='dn4'\n" + ", to='dn45'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=34, valueEnd=34)]\n" + "}], dn46=[MigrateTask{from='dn4'\n" + ", to='dn46'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=35, valueEnd=35)]\n" + "}], dn47=[MigrateTask{from='dn4'\n" + ", to='dn47'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=36, valueEnd=36)]\n" + "}], dn48=[MigrateTask{from='dn4'\n" + ", to='dn48'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=37, valueEnd=37)]\n" + "}], dn49=[MigrateTask{from='dn4'\n" + ", to='dn49'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=38, valueEnd=38)]\n" + "}], dn50=[MigrateTask{from='dn5'\n" + ", to='dn50'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=69, valueEnd=69)]\n" + "}], dn51=[MigrateTask{from='dn5'\n" + ", to='dn51'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=70, valueEnd=70)]\n" + "}], dn52=[MigrateTask{from='dn5'\n" + ", to='dn52'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=71, valueEnd=71)]\n" + "}], dn53=[MigrateTask{from='dn5'\n" + ", to='dn53'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=72, valueEnd=72)]\n" + "}], dn54=[MigrateTask{from='dn5'\n" + ", to='dn54'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=73, valueEnd=73)]\n" + "}], dn55=[MigrateTask{from='dn5'\n" + ", to='dn55'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=74, valueEnd=74)]\n" + "}], dn56=[MigrateTask{from='dn5'\n" + ", to='dn56'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=75, valueEnd=75)]\n" + "}], dn57=[MigrateTask{from='dn5'\n" + ", to='dn57'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=76, valueEnd=76)]\n" + "}], dn58=[MigrateTask{from='dn5'\n" + ", to='dn58'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=77, valueEnd=77)]\n" + "}], dn59=[MigrateTask{from='dn5'\n" + ", to='dn59'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=78, valueEnd=78)]\n" + "}], dn60=[MigrateTask{from='dn6'\n" + ", to='dn60'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=13, valueEnd=13)]\n" + "}], dn61=[MigrateTask{from='dn6'\n" + ", to='dn61'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=14, valueEnd=14)]\n" + "}], dn62=[MigrateTask{from='dn6'\n" + ", to='dn62'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=15, valueEnd=15)]\n" + "}], dn63=[MigrateTask{from='dn6'\n" + ", to='dn63'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=16, valueEnd=16)]\n" + "}], dn64=[MigrateTask{from='dn6'\n" + ", to='dn64'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=17, valueEnd=17)]\n" + "}], dn65=[MigrateTask{from='dn6'\n" + ", to='dn65'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=18, valueEnd=18)]\n" + "}], dn66=[MigrateTask{from='dn6'\n" + ", to='dn66'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=19, valueEnd=19)]\n" + "}], dn67=[MigrateTask{from='dn6'\n" + ", to='dn67'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=20, valueEnd=20)]\n" + "}], dn68=[MigrateTask{from='dn6'\n" + ", to='dn68'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=21, valueEnd=21)]\n" + "}], dn69=[MigrateTask{from='dn6'\n" + ", to='dn69'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=46, valueEnd=46)]\n" + "}], dn70=[MigrateTask{from='dn6'\n" + ", to='dn70'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=47, valueEnd=47)]\n" + "}], dn71=[MigrateTask{from='dn7'\n" + ", to='dn71'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=49, valueEnd=49)]\n" + "}], dn72=[MigrateTask{from='dn7'\n" + ", to='dn72'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=50, valueEnd=50)]\n" + "}], dn73=[MigrateTask{from='dn7'\n" + ", to='dn73'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=51, valueEnd=51)]\n" + "}], dn74=[MigrateTask{from='dn7'\n" + ", to='dn74'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=52, valueEnd=52)]\n" + "}], dn75=[MigrateTask{from='dn7'\n" + ", to='dn75'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=53, valueEnd=53)]\n" + "}], dn76=[MigrateTask{from='dn7'\n" + ", to='dn76'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=54, valueEnd=54)]\n" + "}], dn77=[MigrateTask{from='dn7'\n" + ", to='dn77'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=80, valueEnd=80)]\n" + "}], dn78=[MigrateTask{from='dn7'\n" + ", to='dn78'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=81, valueEnd=81)]\n" + "}], dn79=[MigrateTask{from='dn7'\n" + ", to='dn79'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=82, valueEnd=82)]\n" + "}], dn80=[MigrateTask{from='dn7'\n" + ", to='dn80'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=83, valueEnd=83)]\n" + "}], dn81=[MigrateTask{from='dn8'\n" + ", to='dn81'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=85, valueEnd=85)]\n" + "}], dn82=[MigrateTask{from='dn8'\n" + ", to='dn82'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=86, valueEnd=86)]\n" + "}], dn83=[MigrateTask{from='dn8'\n" + ", to='dn83'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=87, valueEnd=87)]\n" + "}], dn84=[MigrateTask{from='dn8'\n" + ", to='dn84'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=88, valueEnd=88)]\n" + "}], dn85=[MigrateTask{from='dn8'\n" + ", to='dn85'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=0)]\n" + "}], dn86=[MigrateTask{from='dn8'\n" + ", to='dn86'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=1, valueEnd=1)]\n" + "}], dn87=[MigrateTask{from='dn8'\n" + ", to='dn87'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=2, valueEnd=2)]\n" + "}], dn88=[MigrateTask{from='dn8'\n" + ", to='dn88'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=3, valueEnd=3)]\n" + "}], dn89=[MigrateTask{from='dn8'\n" + ", to='dn89'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=4, valueEnd=4)]\n" + "}], dn90=[MigrateTask{from='dn8'\n" + ", to='dn90'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=5, valueEnd=5)]\n" + "}], dn91=[MigrateTask{from='dn9'\n" + ", to='dn91'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=7, valueEnd=7)]\n" + "}], dn92=[MigrateTask{from='dn9'\n" + ", to='dn92'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=8, valueEnd=8)]\n" + "}], dn93=[MigrateTask{from='dn9'\n" + ", to='dn93'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=40)]\n" + "}], dn94=[MigrateTask{from='dn9'\n" + ", to='dn94'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=41, valueEnd=41)]\n" + "}], dn95=[MigrateTask{from='dn9'\n" + ", to='dn95'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=42, valueEnd=42)]\n" + "}], dn96=[MigrateTask{from='dn9'\n" + ", to='dn96'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=43, valueEnd=43)]\n" + "}], dn97=[MigrateTask{from='dn9'\n" + ", to='dn97'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=44, valueEnd=44)]\n" + "}], dn98=[MigrateTask{from='dn9'\n" + ", to='dn98'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=45, valueEnd=45)]\n" + "}], dn99=[MigrateTask{from='dn9'\n" + ", to='dn99'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=66)]\n" + "}]}",tasks2.toString()); }
GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } GPatternUTF8Lexer(GPatternIdRecorder idRecorder); void init(String text); void init(ByteBuffer buffer, int startOffset, int limit); boolean nextToken(); boolean hasChar(); int peekAsciiChar(int step); int nextChar(); String getCurTokenString(); String getString(int start, int end); boolean fastEquals(int startOffset, int endOffset, byte[] symbol); static final int DEMO; static int ignorelength; }
@Test public void init() { GPatternIdRecorder recorder = new GPatternIdRecorderImpl(false); recorder.load(Collections.emptySet()); GPatternUTF8Lexer utf8Lexer = new GPatternUTF8Lexer(recorder); String text = "1234 abc 1a2b3c 'aε“ˆε“ˆε“ˆε“ˆ1' `qac`"; utf8Lexer.init(text); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1234", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("abc", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1a2b3c", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("'aε“ˆε“ˆε“ˆε“ˆ1'", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("`qac`", utf8Lexer.getCurTokenString()); }
HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); }
@Test public void testTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertTrue(loadedXml.isEmpty()); } @Test public void testNonTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertFalse(loadedXml.isEmpty()); }
YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath); }
@Test public void testProcessFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); request.setNeedTransform(false); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); } @Test public void testTransformFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_TRANSFORMED_CONTENT.toLowerCase(), new String(baos.toByteArray()).trim().toLowerCase()); } @Test public void testTransformXFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/xtest.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); }
DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }
@Test public void testAddUser() throws Exception { final long userId = createUser(); assertEquals(1, removeUser(userId)); }
DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }
@Test public void testGetUser() throws Exception { final long userId = createUser(); final UserInfo userInfo = dbUserService.getUser(userId); assertEquals("xxx", userInfo.getLogin()); assertEquals("x x", userInfo.getFio()); assertEquals("123", userInfo.getPasswdHash()); assertEquals("11", userInfo.getPasswdAdd()); assertEquals(1, removeUser(userId)); }
DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }
@Test public void testCheckUser() throws Exception { final long userId = createUser(); assertTrue(dbUserService.checkUser(userId, "123")); assertFalse(dbUserService.checkUser(userId * 2, "11")); assertFalse(dbUserService.checkUser(userId * 3, "123")); assertFalse(dbUserService.checkUser(userId, null)); assertFalse(dbUserService.checkUser(userId * 5, null)); assertEquals(1, removeUser(userId)); }
Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } Minimizer(ResourceType type); @Inject Minimizer(ICompressor compressor, ResourceType type); @Override void enableDisableMinimize(boolean enable); @Override void enableDisableCompress(boolean enable); @Override void enableDisableCache(boolean enable); @Override void enableDisableInMemoryCache(boolean enable); @Override void enableDisableProcessInline(boolean enable); @Deprecated void enableDisableVerifyResource(boolean verify); @Override boolean isMinimizeEnabled(); @Override boolean isCompressEnabled(); @Override boolean isCacheEnabled(); @Override void setResourceDir(String dir); @Override void setRootDir(String dir); @Override void setUrlContextPath(String ctxPath); @Override void setCacheDir(File dir); @Override void setResourceUrlRoot(String urlRoot); @Override void setResourceUrlPath(String urlPath); @Override void setCacheUrlPath(String urlPath); @Override void clearCache(); @Override void setFileLocator(IFileLocator fileLocator); @Override void setBufferLocator(IBufferLocator bufferLocator); @Override void setRouteMapper(IRouteMapper routeMapper); @Override long getLastModified(File file); @Override void checkCache(); @Override List<String> process(List<String> resourceNames); @Override List<String> processWithoutMinimize(List<String> resourceNames); @Override String processInline(String content); @Override String processStatic(File file); IResource minimize(String resourceNames); static void copy_(Reader in, Writer out); ResourceType getType(); void setResourcesParam(String resourcesParam_); static final String SYS_PROP_LESS_ENABLED; static final String SYS_PROP_COFFEE_ENABLED; }
@Test(expected = IllegalStateException.class) public void testInvalidSetup() { jm.setCacheDir(cacheDir); }
EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } EmailSender(JavaMailSender javaMailSender); }
@Test public void shouldSendEmail() throws Exception { String to = "test@codecouple.pl"; String from = "blog@codecouple.pl"; String title = "Title"; String content = "Content"; emailSender.sendEmail(to, from, title, content); MimeMessage[] receivedMessages = server.getReceivedMessages(); assertThat(receivedMessages.length).isEqualTo(1); MimeMessage receivedMessage = receivedMessages[0]; assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(to); assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(from); assertThat(receivedMessage.getSubject()).isEqualTo(title); assertThat(receivedMessage.getContent().toString()).contains(content); assertThat(content).isEqualTo(GreenMailUtil.getBody(server.getReceivedMessages()[0])); }
MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); }
@Test public void unbindWhenDisposed() { Disposable disposable = MerlinFlowable.from(merlin) .subscribe(); disposable.dispose(); verify(merlin).unbind(); } @Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinFlowable.from(context, merlinBuilder).subscribe(); }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenMissingDisconnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, null, bindables); registrar.clearRegistrations(); verifyZeroInteractions(disconnectables); } @Test public void givenMissingBindables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, disconnectables, null); registrar.clearRegistrations(); verifyZeroInteractions(bindables); } @Test public void whenClearingRegistrations_thenDelegatesClearingToRegisters() { registrar.clearRegistrations(); verify(connectables).clear(); verify(disconnectables).clear(); verify(bindables).clear(); } @Test public void givenMissingConnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(null, disconnectables, bindables); registrar.clearRegistrations(); verifyZeroInteractions(connectables); }
Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); }
@Test public void givenSuccessfulRequest_whenSynchronouslyPinging_thenChecksResponseCodeIsValid() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); ping.doSynchronousPing(); verify(responseCodeValidator).isResponseCodeValid(RESPONSE_CODE); } @Test public void givenSuccessfulRequest_whenSynchronouslyPinging_thenReturnsTrue() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); given(responseCodeValidator.isResponseCodeValid(RESPONSE_CODE)).willReturn(true); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isTrue(); } @Test public void givenRequestFailsWithIOException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new IOException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); } @Test public void givenRequestFailsWithRuntimeException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new RuntimeException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); }
Merlin { public void bind() { merlinServiceBinder.bindService(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }
@Test public void whenBinding_thenBindsService() { merlin.bind(); verify(serviceBinder).bindService(); }
Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }
@Test public void whenUnbinding_thenUnbindsService() { merlin.unbind(); verify(serviceBinder).unbind(); } @Test public void whenUnbinding_thenClearsRegistrations() { merlin.unbind(); verify(registrar).clearRegistrations(); }
Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }
@Test public void whenRegisteringConnectable_thenRegistersConnectable() { Connectable connectable = mock(Connectable.class); merlin.registerConnectable(connectable); verify(registrar).registerConnectable(connectable); }
Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }
@Test public void whenRegisteringDisconnectable_thenRegistersDisconnectable() { Disconnectable disconnectable = mock(Disconnectable.class); merlin.registerDisconnectable(disconnectable); verify(registrar).registerDisconnectable(disconnectable); }
Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }
@Test public void whenRegisteringBindable_thenRegistersBindable() { Bindable bindable = mock(Bindable.class); merlin.registerBindable(bindable); verify(registrar).registerBindable(bindable); }
ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); }
@Test public void givenNetworkInfo_whenExtracting_thenReturnsConnectivityChangeEvent() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(networkInfo); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_EXTRA_INFO, ANY_REASON )); } @Test public void givenNetworkInfoIsUnavailable_whenExtracting_thenReturnsConnectivityChangeEventWithoutConnection() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(UNAVAILABLE_NETWORK_INFO); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithoutConnection()); }
EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); }
@Test public void whenPinging_thenCreatesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTaskFactory).create(ENDPOINT, pingerCallback); } @Test public void whenPinging_thenExecutesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTask).execute(); }
EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); }
@Test public void whenNoNetworkToPing_thenCallsOnFailure() { endpointPinger.noNetworkToPing(pingerCallback); verify(pingerCallback).onFailure(); }
ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator, ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever, ConnectivityChangeEventCreator creator); }
@Test public void givenNullIntent_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = null; notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } @Test public void givenIntentWithoutConnectivityAction_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithoutConnectivityAction(); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } @Test public void givenIntentWithConnectivityAction_whenNotifying_thenNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); notifier.notify(context, intent); verify(connectivityChangesNotifier).notify(ANY_CHANGE_EVENT); } @Test public void givenIntentWithConnectivityAction_butNullBinder_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(merlinBinderRetriever.retrieveConnectivityChangesNotifier(context)).willReturn(null); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } @Test public void givenIntentWithConnectivityAction_butIncorrectBinder_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(merlinBinderRetriever.retrieveConnectivityChangesNotifier(context)).willReturn(incorrectBinder()); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } @Test public void givenIntentWithConnectivityAction_butCannotNotify_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); }
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringConnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Connectable connectable = mock(Connectable.class); registrar.registerConnectable(connectable); } @Test public void givenRegister_whenRegisteringConnectable_thenRegistersConnectableWithConnector() { Connectable connectable = mock(Connectable.class); registrar.registerConnectable(connectable); verify(connectables).register(connectable); }
ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context, ConnectivityManager connectivityManager, AndroidVersion androidVersion, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
@Test public void givenRegisteredBroadcastReceiver_whenBindingForASecondTime_thenOriginalBroadcastReceiverIsRegisteredAgain() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(context, times(2)).registerReceiver(eq(broadcastReceiver.getValue()), refEq(new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallbacks_whenBindingForASecondTime_thenOriginalNetworkCallbacksIsRegisteredAgain() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(connectivityManager, times(2)).registerNetworkCallback(refEq((new NetworkRequest.Builder()).build()), eq(merlinNetworkCallback.getValue())); }
ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context, ConnectivityManager connectivityManager, AndroidVersion androidVersion, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
@Test public void givenRegisteredBroadcastReceiver_whenUnbinding_thenUnregistersOriginallyRegisteredBroadcastReceiver() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.unregister(); verify(context).unregisterReceiver(broadcastReceiver.getValue()); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallback_whenUnbinding_thenUnregistersOriginallyRegisteredNetworkCallbacks() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.unregister(); verify(connectivityManager).unregisterNetworkCallback(merlinNetworkCallback.getValue()); }
BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); }
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Bindable bindable = givenRegisteredBindable(); bindCallbackManager.onMerlinBind(networkStatus); verify(bindable).onBind(networkStatus); } @Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Bindable> bindables = givenMultipleRegisteredBindables(); bindCallbackManager.onMerlinBind(networkStatus); for (Bindable bindable : bindables) { verify(bindable).onBind(networkStatus); } }
ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever, DisconnectCallbackManager disconnectCallbackManager, ConnectCallbackManager connectCallbackManager, BindCallbackManager bindCallbackManager, EndpointPinger endpointPinger); }
@Test public void givenNetworkWasConnected_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { givenNetworkWas(CONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(AVAILABLE_NETWORK); } @Test public void givenNetworkWasDisconnected_whenNotifyingOfInitialState_thenForwardsNetworkUnavailableToListener() { givenNetworkWas(DISCONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(NetworkStatus.newUnavailableInstance()); } @Test public void givenEndpointPingHasNotOccurred_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { given(networkStatusRetriever.retrieveNetworkStatus()).willReturn(AVAILABLE_NETWORK); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(AVAILABLE_NETWORK); } @Test public void givenNetworkWasConnected_andNullBindListener_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { connectivityChangesForwarder = new ConnectivityChangesForwarder( networkStatusRetriever, disconnectCallbackManager, connectCallbackManager, null, endpointPinger ); givenNetworkWas(CONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager, never()).onMerlinBind(any(NetworkStatus.class)); } @Test public void givenEndpointPingHasNotOccurred_andNullBindListener_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { connectivityChangesForwarder = new ConnectivityChangesForwarder( networkStatusRetriever, disconnectCallbackManager, connectCallbackManager, null, endpointPinger ); given(networkStatusRetriever.retrieveNetworkStatus()).willReturn(AVAILABLE_NETWORK); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager, never()).onMerlinBind(any(NetworkStatus.class)); }
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test(expected = IllegalStateException.class) public void givenMissingRegister_thenRegisteringDisconnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(disconnectable); } @Test public void givenRegister_whenRegisteringDisconnectable_thenRegistersDisconnectableWithDisconnector() { Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(disconnectable); verify(this.disconnectables).register(disconnectable); }
ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever, DisconnectCallbackManager disconnectCallbackManager, ConnectCallbackManager connectCallbackManager, BindCallbackManager bindCallbackManager, EndpointPinger endpointPinger); }
@Test public void givenConnectivityChangeEvent_whenNotifyingOfConnectivityChangeEvent_thenDelegatesRefreshingToRetriever() { ConnectivityChangeEvent connectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(CONNECTED, ANY_INFO, ANY_REASON); connectivityChangesForwarder.forward(connectivityChangeEvent); verify(networkStatusRetriever).fetchWithPing(eq(endpointPinger), any(EndpointPinger.PingerCallback.class)); }
ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } ConnectivityReceiver(); ConnectivityReceiver(ConnectivityReceiverConnectivityChangeNotifier connectivityReceiverConnectivityChangeNotifier); @Override void onReceive(Context context, Intent intent); }
@Test public void whenReceivingAnIntent_thenForwardsToConnectivityChangeNotifier() { connectivityReceiver.onReceive(context, intent); verify(notifier).notify(context, intent); }
NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
@Test public void givenMerlinsBeardIsConnected_whenFetchingWithPing_thenPingsUsingHostPinger() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).ping(pingerCallback); } @Test public void givenMerlinsBeardIsDisconnected_whenFetchingWithPing_thenCallsNoNetworkToPing() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).noNetworkToPing(pingerCallback); }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
@Test public void givenMerlinsBeardIsConnected_whenGettingNetworkStatus_thenReturnsNetworkStatusAvailable() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newAvailableInstance()); } @Test public void givenMerlinsBeardIsDisconnected_whenGettingNetworkStatus_thenReturnsNetworkStatusUnavailable() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newUnavailableInstance()); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringBindable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); } @Test public void givenRegister_whenRegisteringBindable_thenRegistersBindableWithBinder() { Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); verify(bindables).register(bindable); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsDisconnected_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(DISCONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); } @Test public void givenNetworkIsNull_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(null); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); } @Test public void givenNetworkIsConnected_whenCheckingForConnectivity_thenReturnsTrue() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(CONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isTrue(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsConnectedViaWifi_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsTrue() { givenNetworkStateForBelowLollipop(CONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isTrue(); } @Test public void givenNetworkIsDisconnected_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsFalse() { givenNetworkStateForBelowLollipop(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsConnectedViaWifi_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsTrue() { givenNetworkStateForLollipopOrAbove(CONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isTrue(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsDisconnected_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsFalse() { givenNetworkStateForLollipopOrAbove(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); } @Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(BELOW_LOLLIPOP); given(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).willReturn(null); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(LOLLIPOP_OR_ABOVE); given(connectivityManager.getAllNetworks()).willReturn(new Network[]{}); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsConnectedViaMobile_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToMobile_thenReturnsTrue() { givenNetworkStateForBelowLollipop(CONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isTrue(); } @Test public void givenNetworkIsDisconnected_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateForBelowLollipop(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsConnectedViaMobile_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsTrue() { givenNetworkStateForLollipopOrAbove(CONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isTrue(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsDisconnected_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateForLollipopOrAbove(DISCONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); } @Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(false); given(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)).willReturn(null); boolean connectedToWifi = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToWifi).isFalse(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNoAvailableNetworks_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(true); given(connectivityManager.getAllNetworks()).willReturn(new Network[]{}); boolean connectedToWifi = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToWifi).isFalse(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkWithoutNetworkInfo_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateWithoutNetworkInfoForLollipopOrAbove(); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenSuccessfulPing_whenCheckingCaptivePortal_thenCallsOnResultWithTrue() { willAnswer(new Answer<EndpointPinger.PingerCallback>() { @Override public EndpointPinger.PingerCallback answer(InvocationOnMock invocation) { EndpointPinger.PingerCallback cb = invocation.getArgument(0); cb.onSuccess(); return cb; } }).given(endpointPinger).ping(any(EndpointPinger.PingerCallback.class)); merlinsBeard.hasInternetAccess(mockCaptivePortalCallback); then(mockCaptivePortalCallback).should().onResult(true); } @Test public void givenFailurePing_whenCheckingCaptivePortal_thenCallsOnResultWithFalse() { willAnswer(new Answer<EndpointPinger.PingerCallback>() { @Override public EndpointPinger.PingerCallback answer(InvocationOnMock invocation) { EndpointPinger.PingerCallback cb = invocation.getArgument(0); cb.onFailure(); return cb; } }).given(endpointPinger).ping(any(EndpointPinger.PingerCallback.class)); merlinsBeard.hasInternetAccess(mockCaptivePortalCallback); then(mockCaptivePortalCallback).should().onResult(false); } @Test public void givenSuccessfulPing_whenCheckingHasInternetAccessSync_thenReturnsTrue() { given(mockPing.doSynchronousPing()).willReturn(true); boolean result = merlinsBeard.hasInternetAccess(); assertThat(result).isTrue(); } @Test public void givenFailedPing_whenCheckingHasInternetAccessSync_thenReturnsFalse() { given(mockPing.doSynchronousPing()).willReturn(false); boolean result = merlinsBeard.hasInternetAccess(); assertThat(result).isFalse(); }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }
@Test public void givenRegisteredDisconnectable_whenCallingOnDisconect_thenCallsDisconnectForDisconnectable() { Disconnectable disconnectable = givenRegisteredDisconnectable(); disconnectCallbackManager.onDisconnect(); verify(disconnectable).onDisconnect(); } @Test public void givenMultipleRegisteredDisconnectables_whenCallingOnConnect_thenCallsConnectForAllDisconnectables() { List<Disconnectable> disconnectables = givenMultipleRegisteredDisconnectables(); disconnectCallbackManager.onDisconnect(); for (Disconnectable disconnectable : disconnectables) { verify(disconnectable).onDisconnect(); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
@Test public void givenIntentWithNoConnectivityOfConnected_whenCreatingAConnectivityChangeEvent_thenReturnsConnectedConnectivityChangeEvent() { givenIntentWithNoConnectivityExtraOf(CONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); } @Test public void givenIntentWithNoConnectivityOfDisconnected_whenCreatingAConnectivityChangeEvent_thenReturnsDisconnectedConnectivityChangeEvent() { givenIntentWithNoConnectivityExtraOf(DISCONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( DISCONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); } @Test public void givenMerlinsBeardIsConnected_whenCreatingAConnectivityChangeEvent_thenReturnsConnectedConnectivityChangeEvent() { givenMerlinsBeardIs(CONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); } @Test public void givenMerlinsBeardIsDisconnected_whenCreatingAConnectivityChangeEvent_thenReturnsDisconnectedConnectivityChangeEvent() { givenMerlinsBeardIs(DISCONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( DISCONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectable(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); } @Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Connectable> connectables = givenMultipleRegisteredConnectables(); connectCallbackManager.onConnect(); for (Connectable connectable : connectables) { verify(connectable).onConnect(); } } @Test public void givenRegisteredConnectable_whenCallingOnConnectAndAddingConnectable_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectableModifyingConnectables(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); }
MerlinService extends Service { public static boolean isBound() { return isBound; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenOnBindHasBeenCalled_whenCheckingIsBound_thenReturnsTrue() { givenBoundMerlinService(); boolean bound = MerlinService.isBound(); assertThat(bound).isTrue(); }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenBoundMerlinService_whenCallingOnUnbind_thenUnregistersConnectivityChangesRegister() { givenBoundMerlinService(); merlinService.onUnbind(intent); verify(connectivityChangesRegister).unregister(); } @Test public void givenUnboundService_whenNotifying_thenDoesNotForwardEvent() { MerlinService.LocalBinder localBinder = givenBoundMerlinService(); merlinService.onUnbind(null); localBinder.notify(ANY_CONNECTIVITY_CHANGE_EVENT); verifyZeroInteractions(connectivityChangesForwarder); }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenConnectivityChangesRegisterIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesRegister.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesForwarder(connectivityChangesForwarder); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); } @Test public void givenConnectivityChangesForwarderIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesForwarder.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesRegister(connectivityChangesRegister); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenConnectedNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(CONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); } @Test public void givenNoNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); } @Test public void givenCannotNotify_whenNetworkIsAvailable_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onAvailable(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenDisconnectedNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); } @Test public void givenNoNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); } @Test public void givenCannotNotify_whenLosingNetwork_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLosing(MISSING_NETWORK, MAX_MS_TO_LIVE); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenDisconnectedNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); } @Test public void givenNoNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); } @Test public void givenCannotNotify_whenNetworkIsLost_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLost(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }
@Test public void unbindWhenUnsubscribed() { Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin).unbind(); } @Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinObservable.from(context, merlinBuilder).subscribe(); }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
@Test public void testOnCreateShouldExtractStateFromIntent() throws JSONException { OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().get(); assertThat(activity.mCompleteIntent).isEqualTo(this.mCompleteIntent); assertThat(activity.mCancelIntent).isEqualTo(this.mCancelIntent); } @Test public void testOnStartShouldSignOutIfConfigurationHasChanged() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); new OAuthClientConfiguration( context, context.getSharedPreferences(OAuthClientConfiguration.PREFS_NAME, MODE_PRIVATE), ConfigurationStreams.getOtherConfiguration() ); doNothing().when(mCancelIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class ).newIntent(createStartIntent()).create().start().get(); assertThat(activity.isFinishing()).isTrue(); } @Test public void testOnStartShouldCompleteIfStateIsAuthorized() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); AuthStateManager stateManager = AuthStateManager.getInstance(context); stateManager.replace(mAuthState); when(mAuthState.isAuthorized()).thenReturn(true); doNothing().when(mCompleteIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().start().get(); assertThat(activity.isFinishing()).isTrue(); }
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testReadStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.readState(); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); } mPrefsLock.unlock(); assertThat(sut.readState()).isNotNull(); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testWriteStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.writeState(new AuthState()); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } mPrefsLock.unlock(); sut.writeState(new AuthState()); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); } @Test public void testWriteStateRemovesKeyWhenWritingNull() { sut.writeState(new AuthState()); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); sut.writeState(null); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testRefreshWithoutTokenCallsListener() { FakeOktaAuthListener listener = new FakeOktaAuthListener(); sut.refreshAccessToken(listener); assertThat(listener.hasCalledOnTokenFailure()).isTrue(); assertThat(listener.getTokenExceptions().get(0)) .isEqualTo(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); } @Test public void testRefreshFailsClientAuthenticationCallsListener() throws ClientAuthentication.UnsupportedAuthenticationMethod { when(mAuthState.getRefreshToken()).thenReturn("refreshTokenHere"); when(mAuthState.getClientAuthentication()) .thenThrow(new ClientAuthentication. UnsupportedAuthenticationMethod("tokenEndpointAuthMethod")); FakeOktaAuthListener listener = new FakeOktaAuthListener(); sut.refreshAccessToken(listener); verify(mAuthState, times(1)).getClientAuthentication(); assertThat(listener.hasCalledOnTokenFailure()).isTrue(); assertThat(listener.getTokenExceptions().get(0)) .isEqualTo(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); } @Test public void testRefreshCallsIntoAppAuth() throws ClientAuthentication.UnsupportedAuthenticationMethod { TokenRequest tokenRequest = mock(TokenRequest.class); FakeOktaAuthListener listener = new FakeOktaAuthListener(); when(mAuthState.getRefreshToken()).thenReturn("refreshTokenHere"); when(mAuthState.getClientAuthentication()).thenReturn(mClientAuthentication); when(mAuthState.createTokenRefreshRequest()).thenReturn(tokenRequest); sut.refreshAccessToken(listener); verify(mAuthService, times(1)) .performTokenRequest( any(TokenRequest.class), any(ClientAuthentication.class), any(AuthorizationService.TokenResponseCallback.class)); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testSignOutFromOkta() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); String idToken = TestUtils.getUnsignedIdToken(); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); when(authState.isAuthorized()).thenReturn(true); when(authState.getIdToken()).thenReturn(idToken); when(mConfiguration.getEndSessionRedirectUri()) .thenReturn(TestUtils.TEST_APP_REDIRECT_URI); when(mConfiguration.hasConfigurationChanged()).thenReturn(false); ArgumentCaptor<EndSessionRequest> argument = ArgumentCaptor.forClass(EndSessionRequest.class); sut.signOutFromOkta(mContext, success, failure); verify(mAuthService, times(1)) .performEndOfSessionRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(argument.getValue().idToken) .isEqualTo(idToken); assertThat(argument.getValue().configuration.toJsonString()) .isEqualTo(TestUtils.getTestServiceConfig().toJsonString()); assertThat(argument.getValue().redirectUri) .isEqualTo(TestUtils.TEST_APP_REDIRECT_URI); } @Test(expected = IllegalStateException.class) public void testLogoutNoLogedinUserFoundException(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.isAuthorized()).thenReturn(false); when(mConfiguration.hasConfigurationChanged()).thenReturn(false); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); sut.signOutFromOkta(mContext, success, failure); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testLoginWithoutPayloadSuccess() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); AuthorizationRequest expectedRequest = TestUtils.getTestAuthRequest(); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); sut.mAuthRequest.set(TestUtils.getTestAuthRequest()); sut.login(mContext, success, failure); ArgumentCaptor<AuthorizationRequest> argument = ArgumentCaptor.forClass(AuthorizationRequest.class); verify(mAuthService, times(1)) .performAuthorizationRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(expectedRequest.clientId) .isEqualTo(argument.getValue().clientId); assertThat(expectedRequest.configuration.toJsonString()) .isEqualTo(argument.getValue().configuration.toJsonString()); } @Test public void testLoginWithPayloadSuccess() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); when(mConfiguration.getRedirectUri()).thenReturn(TestUtils.TEST_APP_REDIRECT_URI); when(mConfiguration.getScopes()).thenReturn(new HashSet<>(TestUtils.TEST_SCOPES_SUPPORTED)); sut.mClientId.set(TestUtils.TEST_CLIENT_ID); AuthenticationPayload payload = new AuthenticationPayload.Builder() .addParameter("testName", "testValue") .setState("testState") .setLoginHint("loginHint") .build(); sut.login(mContext, success, failure, payload); ArgumentCaptor<AuthorizationRequest> argument = ArgumentCaptor .forClass(AuthorizationRequest.class); verify(mAuthService, times(1)) .performAuthorizationRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(argument.getValue().loginHint) .isEqualTo(payload.getLoginHint()); assertThat(argument.getValue().additionalParameters) .isEqualTo(payload.getAdditionalParameters()); assertThat(argument.getValue().state) .isEqualTo(payload.getState()); } @Test public void testLoginIllegalStateExceptionConfigurationChanged(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); when(mConfiguration.hasConfigurationChanged()).thenReturn(true); try { sut.login(mContext, success, failure); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta Configuration has changed"); return; } fail("Expected exception not thrown"); } @Test public void testLoginIllegalStateExceptionNoAuthorizationConfiguration(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState mockedState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(mockedState); when(mockedState.getAuthorizationServiceConfiguration()).thenReturn(null); try { sut.login(mContext, success, failure); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta should be initialized first"); return; } fail("Expected exception not thrown"); }
OktaAppAuth { public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testGetTokenSuccess() { String testIdToken = "testIdToken"; String testAccessToken = "testAccessToken"; String testRefreshToken = "testRefreshToken"; when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getIdToken()).thenReturn(testIdToken); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToken); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); Tokens tokens = sut.getTokens(); assertThat(tokens.getAccessToken()).isEqualTo(testAccessToken); assertThat(tokens.getIdToken()).isEqualTo(testIdToken); assertThat(tokens.getRefreshToken()).isEqualTo(testRefreshToken); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAccessTokenRevocationSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testAccessToken) && url.contains(testClientId)){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(testAccessToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); } @Test public void testAccessTokenRevocationFailure() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testAccessToken) && url.contains(testClientId)){ return new MockResponse().setResponseCode(400); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(testAccessToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(false); latch.countDown(); } @Override public void onError(AuthorizationException ex) { if (ex.type == AuthorizationException.TYPE_OAUTH_TOKEN_ERROR) { isPassed.set(true); } latch.countDown(); } }); latch.await(); assertTrue("onSuccess has been called",isPassed.get()); } @Test public void testAllTokenRevocationSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testRefreshToke = "testRefreshToke"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testAccessToken) || url.contains(testRefreshToke)) ){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToke); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); } @Test public void testAllTokenRevocationNoRefreshTokenSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testAccessToken)) ){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); when(mAuthState.getRefreshToken()).thenReturn(null); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); } @Test public void testAllTokenRevocationRefreshTokenFailure() throws JSONException, InterruptedException { final String testRefreshToken = "testRefreshToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testRefreshToken)) ){ return new MockResponse().setResponseCode(400); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToken); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(false); latch.countDown(); } @Override public void onError(AuthorizationException ex) { if (ex.type == AuthorizationException.TYPE_OAUTH_TOKEN_ERROR) { isPassed.set(true); } latch.countDown(); } }); latch.await(); assertTrue("onSuccess has been called",isPassed.get()); } @Test public void testTokenRevocationConfigChangedException() { String testToken = "testToken"; when(mConfiguration.hasConfigurationChanged()).thenReturn(true); try { sut.revoke(testToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { fail("Test should fail with exception"); } @Override public void onError(AuthorizationException ex) { fail("Test should fail with exception"); } }); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta Configuration has changed"); return; } fail("Test should fail with exception"); } @Test public void testTokenRevocationOktaNotInitializedException() { String testToken = "testToken"; AuthState mockedState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(mockedState); when(mockedState.getAuthorizationServiceConfiguration()).thenReturn(null); try { sut.revoke(testToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { fail("Test should fail with exception"); } @Override public void onError(AuthorizationException ex) { fail("Test should fail with exception"); } }); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta should be initialized first"); return; } fail("Test should fail with exception"); }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
@Test public void testInValidCredentialsPerformAuthorizationRequest() { FakeNativeOktaAuthListener listener = new FakeNativeOktaAuthListener(); sessionAuthenticationService.performAuthorizationRequest(request, null, listener); assertTrue(listener.hasCalledOnTokenFailure()); } @Test public void testNullListenerPerformAuthorizationRequest() { sessionAuthenticationService.performAuthorizationRequest(request, VALID_SESSION, null); sessionAuthenticationService.performAuthorizationRequest(request, null, null); }
OAuthClientConfiguration { public String getClientId() { return mClientId; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetClientId() { assertThat(sut.getClientId()).isEqualTo("example_client_id"); }
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void getRedirectUri() { assertThat(sut.getRedirectUri()).isEqualTo( Uri.parse("com.okta.appauth.android.test:/oauth2redirect")); }
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetDiscoveryUriAppendsWellKnownDiscovery() { assertThat(sut.getDiscoveryUri()).isEqualTo( Uri.parse("https: ); }
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetScopes() { assertThat(sut.getScopes()).contains("openid", "foo"); }
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testGetCurrentCachesState() { AuthState state = sut.getCurrent(); assertThat(sut.getCurrent()).isSameAs(state); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
GesturePane extends Control implements GesturePaneOps { public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testScrollBarDisabled() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); assertThat(pane.lookupAll("*")) .haveExactly(1, createBarCondition(HORIZONTAL, false)) .haveExactly(1, createBarCondition(VERTICAL, false)); }
GesturePane extends Control implements GesturePaneOps { public void setTarget(Transformable target) { this.target.set(target); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testSetTarget() { pane.setTarget(new Transformable() { @Override public double width() { return 128; } @Override public double height() { return 128; } @Override public void setTransform(Affine affine) { } }); pane.setTarget(new Transformable() { @Override public double width() { return 1014; } @Override public double height() { return 1024; } @Override public void setTransform(Affine affine) { } }); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testSetContent() { pane.setContent(new Rectangle(128, 128)); pane.setContent(new Rectangle(1024, 1024)); } @Test public void testContentBoundChanged() throws Exception { Rectangle rect = new Rectangle(128, 128, Color.RED); pane.setContent(rect); Thread.sleep(50); rect.setWidth(1000); rect.setHeight(1000); Thread.sleep(50); rect.setHeight(0); rect.setHeight(0); }
GesturePane extends Control implements GesturePaneOps { public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testViewportCentre() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); assertThat(pane.viewportCentre()).isEqualTo(new Point2D(256, 256)); }
GesturePane extends Control implements GesturePaneOps { public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testTargetPointAtViewportCentre() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); Point2D expected = pane.targetPointAt(pane.viewportCentre()) .orElseThrow(AssertionError::new); assertThat(pane.targetPointAtViewportCentre()).isEqualTo(expected); }
GesturePane extends Control implements GesturePaneOps { final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testScale() { pane.zoomTo(2, pane.targetPointAtViewportCentre()); assertThat(pane.getCurrentScale()).isEqualTo(2d); }
GesturePane extends Control implements GesturePaneOps { public double getCurrentScale() { return scaleX.get(); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testScaleByTouch() { double factor = 4.2; pane.fireEvent(new ZoomEvent(ZoomEvent.ZOOM, 0, 0, 0, 0, false, false, false, false, false, false, factor, factor, null)); assertThat(pane.getCurrentScale()).isEqualTo(factor); }
GesturePane extends Control implements GesturePaneOps { @Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testCentreOn() { final double zoom = 2d; final double dx = 300d; final double dy = 200d; pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); pane.zoomTo(zoom, pane.targetPointAtViewportCentre()); final Transform last = target.captureTransform(); pane.centreOn(new Point2D(dx, dy)); final Transform now = target.captureTransform(); assertThat(now.getTx()).isEqualTo(-last.getTx() - dx * zoom); assertThat(now.getTy()).isEqualTo(-last.getTy() - dy * zoom); }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
@Test public void testExtractAuthorFromDirectoryName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); File parent = createMock(File.class); expect(mock.getParentFile()).andReturn(parent); expect(parent.getName()).andReturn("Christopher, Matt"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new ParentDirectoryAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, hasItems(new Author("Matt", "Christopher"))); assertThat(authorScores.getScore(), is(1.0)); } @Test public void testExtractMultipleAuthorsFromDirectoryName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); File parent = createMock(File.class); expect(mock.getParentFile()).andReturn(parent); expect(parent.getName()).andReturn("Jacques, Brian & Chalk, Gary"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new ParentDirectoryAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); double value = authorScores.getScore(); verifyAll(); assertThat(authors, hasItems(new Author("Brian", "Jacques"), new Author("Gary", "Chalk"))); assertThat(authorScores.getScore(), is(1.0)); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }
@Test public void testExtractAuthorFromFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Abbott, Megan - Dare Me.epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, contains(new Author("Megan", "Abbott"))); assertThat(authorScores.getScore(), is(1.0)); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }
@Test public void testExtractAuthorFromOtherFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("P. L. Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, hasItems(new Author("P. L.", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); } @Test public void testExtractAuthorFromOnlyLastname() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); double value = authorScores.getScore(); verifyAll(); assertThat(authors, hasItems(new Author("", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); }
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
@Test public void extractAuthorFromMetaData() { File file = new File("src/test/resources/epubs/Alexandre Dumas - The countess of Charney.epub"); BookImportContext bookImportContext = new BookImportContext(file); Score<List<Author>> authorScores = new MetaDataAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); assertThat(authors, hasItems(new Author("Alexandre", "Dumas"))); assertThat(authorScores.getScore(), is(1.0)); }
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } @NotNull @Override Isbn13Score score(BookImportContext context); static final int ISBN_LENGTH; }
@Test public void testIsbn() { MetaDataIsbn13ScoreStrategy strategy = new MetaDataIsbn13ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890123").buildContext(); Isbn13Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890123")); assertThat(score.getScore(), is(1.0)); }
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } @NotNull @Override Isbn10Score score(BookImportContext context); static final int ISBN_LENGTH; }
@Test public void testIsbn() { MetaDataIsbn10ScoreStrategy strategy = new MetaDataIsbn10ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890").buildContext(); Isbn10Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890")); assertThat(score.getScore(), is(1.0)); }
BookProducer { public Book produce(BookImportContext context) throws IOException { Book book = new Book(); book.setAuthors(new AuthorScorer().determineBestScore(context).getValue()); book.setSource("import"); book.setTitle(new TitleScorer().determineBestScore(context).getValue()); book.setLanguage((new LanguageScorer().determineBestScore(context).getValue())); book.setIsbn10(new Isbn10Scorer().determineBestScore(context).getValue()); book.setIsbn13(new Isbn13Scorer().determineBestScore(context).getValue()); book.setSummary(new SummaryScorer().determineBestScore(context).getValue()); book.setPublisher(new PublisherScorer().determineBestScore(context).getValue()); book.setPublicationDate(new PublicationDateScorer().determineBestScore(context).getValue()); book.setTags(new TagsScorer().determineBestScore(context).getValue()); Binary epub = getBinaryFromFile(context); book.setEpub(epub); book.setFileSizeInKb(epub.getContents().length / 1024); book.setCover(new CoverScorer().determineBestScore(context).getValue()); book.setContents(getContent(context.getEpubBook().getContents()) ); log.info("Produced book {}", book); return book; } Book produce(BookImportContext context); }
@Test public void testEnrichBooks() throws Exception { BookImportContext bookImportContext = new BookImportContext(new File("src/test/resources/epubs/W. H. Davenport Adams - Some heroes of Travel.epub")); Book book = new BookProducer().produce(bookImportContext); assertThat(book.getFirstAuthor(), is(new Author("Davenport", "Adams W. H."))); }
Response { public int getCode() { return code; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }
@Test public void getCode() throws Exception { }
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onPreExecute() { super.onPreExecute(); } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }
@Test public void onPreExecute() throws Exception { }
BitMapTask extends Task<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... urls) { try { Response response = makeRequest(mUrl, method, params, headers); Bitmap bitmap = response.getAsBitmap(); if (this.mCacheManager != null) { if (this.mCacheManager.getDataFromCache(mUrl) == null) this.mCacheManager.addDataToCache(mUrl, bitmap); } return bitmap; } catch (Exception e) { e.printStackTrace(); error = true; } return null; } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }
@Test public void doInBackground() throws Exception { }
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onPostExecute(Bitmap data) { super.onPostExecute(data); if (!error) this.callback.onResponse(data); else this.callback.onError(); } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }
@Test public void onPostExecute() throws Exception { }
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onCancelled() { super.onCancelled(); if (this.mCacheManager != null) { this.mCacheManager.removeDataFromCache(mUrl); } } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }
@Test public void onCancelled() throws Exception { }
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onPreExecute() { super.onPreExecute(); } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }
@Test public void onPreExecute() throws Exception { }
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected JSONArray doInBackground(String... urls) { try { Response response = makeRequest(mUrl, method, params, headers); JSONArray json = new JSONArray(response.getDataAsString()); if (this.mCacheManager != null) { if (this.mCacheManager.getDataFromCache(mUrl) == null) this.mCacheManager.addDataToCache(mUrl, json); } return json; } catch (Exception e) { e.printStackTrace(); error = true; } return null; } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }
@Test public void doInBackground() throws Exception { }
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onPostExecute(JSONArray data) { super.onPostExecute(data); if (!error) this.callback.onResponse(data); else this.callback.onError(); } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }
@Test public void onPostExecute() throws Exception { }
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onCancelled() { super.onCancelled(); if (this.mCacheManager != null) { this.mCacheManager.removeDataFromCache(mUrl); } } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }
@Test public void onCancelled() throws Exception { }
RequestParams { public String getKey() { return key; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }
@Test public void getKey() throws Exception { }
RequestParams { public RequestParams setKey(String key) { this.key = key; return this; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }
@Test public void setKey() throws Exception { }
Response { public Response setCode(int code) { this.code = code; return this; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }
@Test public void setCode() throws Exception { }
RequestParams { public String getValue() { return value; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }
@Test public void getValue() throws Exception { }
RequestParams { public RequestParams setValue(String value) { this.value = value; return this; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }
@Test public void setValue() throws Exception { }
HeaderParams { public String getKey() { return key; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }
@Test public void getKey() throws Exception { }
HeaderParams { public HeaderParams setKey(String key) { this.key = key; return this; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }
@Test public void setKey() throws Exception { }
HeaderParams { public String getValue() { return value; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }
@Test public void getValue() throws Exception { }
HeaderParams { public HeaderParams setValue(String value) { this.value = value; return this; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }
@Test public void setValue() throws Exception { }
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override protected int sizeOf(String key, T data) { int bytesCount; if (data instanceof Bitmap) { bytesCount = ((Bitmap) data).getByteCount(); } else if (data instanceof JSONObject) { bytesCount = ((JSONObject) data).toString().getBytes().length; } else { bytesCount = ((JSONArray) data).toString().getBytes().length; } return bytesCount / 1024; } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }
@Test public void sizeOf() throws Exception { }
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void addDataToCache(String key, T data) { if (getDataFromCache(key) == null) { synchronized (this) { put(key, data); cacheHitTimestamp.put(key, SystemClock.uptimeMillis()); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }
@Test public void addDataToCache() throws Exception { }
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void removeDataFromCache(String key) { if (getDataFromCache(key) != null) { synchronized (this) { remove(key); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }
@Test public void removeDataFromCache() throws Exception { }
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public T getDataFromCache(String key) { synchronized (this) { cacheHitTimestamp.put(key, SystemClock.uptimeMillis()); evictUnused(); } return get(key); } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }
@Test public void getDataFromCache() throws Exception { }
Response { public InputStream getData() { return inputStream; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }
@Test public void getData() throws Exception { }
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void evictUnused() { Map<String, T> items = snapshot(); for (String key : items.keySet()) { long cacheTime = cacheHitTimestamp.get(key); if (cacheTime + timeout < SystemClock.uptimeMillis()) { remove(key); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }
@Test public void evictUnused() throws Exception { }
JsonArray extends Type<JSONArray> { public JsonArray setCallback(HttpListener<JSONArray> listener) { this.mListener = listener; this.mListener.onRequest(); JSONArray data; if (mCacheManager != null) { data = mCacheManager.getDataFromCache(url); if (data != null) { mListener.onResponse(data); return this; } } mTask = new JsonArrayTask(method, url, params, headers, mListener); mTask.setmCachemanager(mCacheManager); mTask.execute(); return this; } JsonArray(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonArray setCallback(HttpListener<JSONArray> listener); boolean cancel(); JsonArray setCacheManager(CacheManagerInterface<JSONArray> cache); }
@Test public void setCallback() throws Exception { }