src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CacheAnalysisImpl implements ICacheAnalysis { @Override public CacheAnalysis analyze(List<Session> sessionlist) { long analysisStartTime = System.currentTimeMillis(); CacheAnalysis result = new CacheAnalysis(); long totalRequestResponseBytes = 0; long totalRequestResponseDupBytes = 0; double duplicateContentBytesRatio = 0.0; Map<String, CacheEntry> cacheEntries = new HashMap<String, CacheEntry>(); Map<String, CacheEntry> dupEntries = new HashMap<String, CacheEntry>(); Map<String, SortedSet<Range>> rangeEntries = new HashMap<String, SortedSet<Range>>(); List<CacheEntry> diagnosisResults = new ArrayList<CacheEntry>(); List<CacheEntry> duplicateContent = new ArrayList<CacheEntry>(); List<CacheEntry> duplicateContentWithOriginals = new ArrayList<CacheEntry>(); Map<CacheExpiration, List<CacheEntry>> cacheExpirationResponses = result.getCacheExpirationResponses(); dulpicateEntires = new ArrayList<DuplicateEntry>(); for (CacheExpiration expiration : CacheExpiration.values()) { cacheExpirationResponses.put(expiration, new ArrayList<CacheEntry>()); } List<HttpRequestResponseInfoWithSession> rrInfo = new ArrayList<HttpRequestResponseInfoWithSession>(); for (Session session : sessionlist) { if (!session.isUdpOnly()) { for (HttpRequestResponseInfo item : session.getRequestResponseInfo()) { HttpRequestResponseInfoWithSession itemsession = new HttpRequestResponseInfoWithSession(); itemsession.setInfo(item); itemsession.setSession(session); rrInfo.add(itemsession); } } } Collections.sort(rrInfo); for (HttpRequestResponseInfoWithSession httpreqres : rrInfo) { HttpRequestResponseInfo response = httpreqres.getInfo(); Session session = httpreqres.getSession(); PacketInfo firstPacket = session.getPackets().get(0); if (response.getDirection() == HttpDirection.REQUEST) { continue; } int statusCode = response.getStatusCode(); if (statusCode == 0) { diagnosisResults .add(new CacheEntry(null, response, Diagnosis.CACHING_DIAG_INVALID_RESPONSE, 0, firstPacket)); continue; } if (statusCode != 200 && statusCode != 206) { diagnosisResults .add(new CacheEntry(null, response, Diagnosis.CACHING_DIAG_INVALID_REQUEST, 0, firstPacket)); continue; } HttpRequestResponseInfo request = response.getAssocReqResp(); if (request == null) { diagnosisResults.add( new CacheEntry(request, response, Diagnosis.CACHING_DIAG_REQUEST_NOT_FOUND, 0, firstPacket)); continue; } totalRequestResponseBytes += response.getContentLength(); String requestType = request.getRequestType(); if (!HttpRequestResponseInfo.HTTP_GET.equals(requestType) && !HttpRequestResponseInfo.HTTP_PUT.equals(requestType) && !HttpRequestResponseInfo.HTTP_POST.equals(requestType)) { diagnosisResults .add(new CacheEntry(request, response, Diagnosis.CACHING_DIAG_INVALID_REQUEST, 0, firstPacket)); continue; } if (request.getHostName() == null || request.getObjName() == null) { diagnosisResults.add( new CacheEntry(request, response, Diagnosis.CACHING_DIAG_INVALID_OBJ_NAME, 0, firstPacket)); continue; } if (response.isNoStore() || request.isNoStore() || HttpRequestResponseInfo.HTTP_POST.equals(requestType) || HttpRequestResponseInfo.HTTP_PUT.equals(requestType)) { cacheEntries.remove(getObjFullName(request, response)); dupEntries.remove(getObjDuplicateName(request, response)); diagnosisResults .add(new CacheEntry(request, response, Diagnosis.CACHING_DIAG_NOT_CACHABLE, 0, firstPacket)); continue; } CacheEntry cacheEntry = cacheEntries.get(getObjFullName(request, response)); CacheEntry cacheDuplicateEntry = dupEntries.get(getObjDuplicateName(request, response)); CacheEntry newCacheEntry; if (cacheEntry == null) { Diagnosis diagnosis = Diagnosis.CACHING_DIAG_CACHE_MISSED; newCacheEntry = new CacheEntry(request, response, diagnosis, firstPacket); newCacheEntry.setSession(session); addToCache(newCacheEntry, rangeEntries, cacheEntries, dupEntries, session); newCacheEntry.setCacheCount(1); diagnosisResults.add(newCacheEntry); if (cacheDuplicateEntry != null) { diagnosis = Diagnosis.CACHING_DIAG_ETAG_DUPLICATE; } dulpicateEntires.add(new DuplicateEntry(request, response, diagnosis, firstPacket, session, getContent(response, session))); continue; } else { int oldCount = cacheEntry.getCacheCount(); cacheEntry.setCacheCount(oldCount + 1); } CacheExpiration expStatus = cacheExpired(cacheEntry, request.getAbsTimeStamp()); SortedSet<Range> ranges = rangeEntries .get(getObjFullName(cacheEntry.getRequest(), cacheEntry.getResponse())); boolean isfullcachehit = isFullCacheHit(response, ranges); if (isfullcachehit) { switch (expStatus) { case CACHE_EXPIRED: case CACHE_EXPIRED_HEURISTIC: newCacheEntry = handleCacheExpired(session, response, request, firstPacket, cacheEntry); diagnosisResults.add(newCacheEntry); break; case CACHE_NOT_EXPIRED: case CACHE_NOT_EXPIRED_HEURISTIC: newCacheEntry = new CacheEntry(request, response, Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP, firstPacket); dulpicateEntires.add(new DuplicateEntry(request, response, Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP, firstPacket, session, getContent(response, session))); diagnosisResults.add(newCacheEntry); break; default: newCacheEntry = null; } } else { long bytesInCache = getBytesInCache(response, ranges); switch (expStatus) { case CACHE_EXPIRED: case CACHE_EXPIRED_HEURISTIC: newCacheEntry = handleCacheExpiredWithByteInCache(session, response, request, firstPacket, cacheEntry, bytesInCache); diagnosisResults.add(newCacheEntry); break; case CACHE_NOT_EXPIRED: case CACHE_NOT_EXPIRED_HEURISTIC: newCacheEntry = new CacheEntry(request, response, Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP_PARTIALHIT, bytesInCache, firstPacket); dulpicateEntires.add(new DuplicateEntry(request, response, Diagnosis.CACHING_DIAG_NOT_EXPIRED_DUP, firstPacket, session, getContent(response, session))); diagnosisResults.add(newCacheEntry); break; default: newCacheEntry = null; } } cacheExpirationResponses.get(expStatus).add(newCacheEntry); if (newCacheEntry != null) { newCacheEntry.setCacheHit(cacheEntry); } } Set<CacheEntry> dupsWithOrig = new HashSet<CacheEntry>(); Map<String, DuplicateEntry> dulpicateEntiresMap = new HashMap<String, DuplicateEntry>(); CacheEntry cache; for (DuplicateEntry dupEntry : dulpicateEntires) { if (dupEntry.getContentLength() > 0) { String key = dupEntry.getRequest().getHostName() + dupEntry.getHttpObjectName() + dupEntry.getContentLength(); if (dupEntry.getHttpObjectName() != null) { if (!dulpicateEntiresMap.containsKey(key)) { dupEntry.setCount(1); dulpicateEntiresMap.put(key, dupEntry); } else { if (Arrays.equals(dulpicateEntiresMap.get(key).getContent(), dupEntry.getContent())) { int count = dulpicateEntiresMap.get(key).getCount(); if (count == 1) { cache = new CacheEntry(dulpicateEntiresMap.get(key).getRequest(), dulpicateEntiresMap.get(key).getResponse(), dulpicateEntiresMap.get(key).getDiagnosis(), dulpicateEntiresMap.get(key).getSessionFirstPacket()); cache.setSession(dupEntry.getSession()); dupsWithOrig.add(cache); } cache = new CacheEntry(dupEntry.getRequest(), dupEntry.getResponse(), dupEntry.getDiagnosis(), dupEntry.getSessionFirstPacket()); dupsWithOrig.add(cache); dupEntry = new DuplicateEntry(dupEntry.getRequest(), dupEntry.getResponse(), dupEntry.getDiagnosis(), dupEntry.getSessionFirstPacket(), dupEntry.getSession(), dupEntry.getContent()); dupEntry.setCount(count + 1); dulpicateEntiresMap.replace(key, dupEntry); } } } } } for (Entry<String, DuplicateEntry> cacheEntry2 : dulpicateEntiresMap.entrySet()) { if (cacheEntry2.getValue().getCount() > 1) { int count = cacheEntry2.getValue().getCount(); cache = new CacheEntry(cacheEntry2.getValue().getRequest(), cacheEntry2.getValue().getResponse(), cacheEntry2.getValue().getDiagnosis(), cacheEntry2.getValue().getSessionFirstPacket()); cache.setHitCount(count); if (count > 2) { totalRequestResponseDupBytes += (cacheEntry2.getValue().getHttpRequestResponse().getContentLength() * (count - 1)); } else { totalRequestResponseDupBytes += cacheEntry2.getValue().getHttpRequestResponse().getContentLength(); } duplicateContent.add(cache); } } duplicateContentWithOriginals.addAll(dupsWithOrig); Collections.sort(duplicateContentWithOriginals); duplicateContentBytesRatio = totalRequestResponseBytes != 0 ? (double) totalRequestResponseDupBytes / totalRequestResponseBytes : 0.0; result.setCacheExpirationResponses(cacheExpirationResponses); result.setDiagnosisResults(diagnosisResults); result.setDuplicateContent(duplicateContent); result.setDuplicateContentBytesRatio(duplicateContentBytesRatio); result.setDuplicateContentWithOriginals(duplicateContentWithOriginals); result.setTotalRequestResponseBytes(totalRequestResponseBytes); result.setTotalRequestResponseDupBytes(totalRequestResponseDupBytes); GoogleAnalyticsUtil.getGoogleAnalyticsInstance().sendAnalyticsTimings(cacheAnalysisTitle, System.currentTimeMillis() - analysisStartTime, analysisCategory); return result; } @Override CacheAnalysis analyze(List<Session> sessionlist); byte[] getContent(HttpRequestResponseInfo response, Session session); }
|
@Test public void analyze_() { List<PacketInfo> packets = new ArrayList<PacketInfo>(); pktInfo01 = Mockito.mock(PacketInfo.class); pktInfo02 = Mockito.mock(PacketInfo.class); for (int i = 0; i < 60; i++) { httpRequestInfoArray[i] = mock(HttpRequestResponseInfo.class); } for (int i = 0; i < 20; i++) { when(httpRequestInfoArray[i].isNoStore()).thenReturn(true); if (i % 2 == 1) { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.REQUEST); when(httpRequestInfoArray[i].getHostName()).thenReturn("www.google.com"); when(httpRequestInfoArray[i].getObjName()).thenReturn(Util.getCurrentRunningDir()); } else { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.RESPONSE); when(httpRequestInfoArray[18].getStatusCode()).thenReturn(304); } } for (int i = 20; i < 60; i++) { when(httpRequestInfoArray[i].isNoStore()).thenReturn(false); when(httpRequestInfoArray[i].getHostName()).thenReturn("www.google.com" + i); when(httpRequestInfoArray[i].getObjName()).thenReturn(Util.getCurrentRunningDir()); when(httpRequestInfoArray[i - 2].isRangeResponse()).thenReturn(true); if ((i - 20) % 2 == 1) { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.REQUEST); } else { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.RESPONSE); when(httpRequestInfoArray[i].getStatusCode()).thenReturn(206); } } when(httpRequestInfoArray[2].getAssocReqResp()).thenReturn(httpRequestInfoArray[1]); when(httpRequestInfoArray[4].getAssocReqResp()).thenReturn(httpRequestInfoArray[3]); when(httpRequestInfoArray[6].getAssocReqResp()).thenReturn(httpRequestInfoArray[5]); when(httpRequestInfoArray[8].getAssocReqResp()).thenReturn(httpRequestInfoArray[7]); when(httpRequestInfoArray[10].getAssocReqResp()).thenReturn(httpRequestInfoArray[9]); when(httpRequestInfoArray[12].getAssocReqResp()).thenReturn(httpRequestInfoArray[11]); when(httpRequestInfoArray[14].getAssocReqResp()).thenReturn(httpRequestInfoArray[13]); for (int i = 18; i < 60; i++) { when(httpRequestInfoArray[i].getAssocReqResp()).thenReturn(httpRequestInfoArray[i - 1]); } for (int i = 50; i < 60; i++) { when(httpRequestInfoArray[i].isRangeResponse()).thenReturn(false); when(httpRequestInfoArray[i].isChunked()).thenReturn(true); } for (int i = 0; i < 50; i++) { when(httpRequestInfoArray[i].isRangeResponse()).thenReturn(true); } when(httpRequestInfoArray[7].getHostName()).thenReturn(null); when(httpRequestInfoArray[7].getObjName()).thenReturn(null); when(httpRequestInfoArray[0].getStatusCode()).thenReturn(400); when(httpRequestInfoArray[2].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[4].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[6].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[8].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[10].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[12].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[14].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[16].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[18].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[1].getRequestType()).thenReturn(HttpRequestResponseInfo.UTF8); when(httpRequestInfoArray[3].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[5].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[7].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[9].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[11].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[13].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[15].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[17].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[19].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[20].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[21].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); for (int i = 22; i < 60; i++) { if (i % 2 == 1) { when(httpRequestInfoArray[i].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); } } Date date01 = new Date(1421384400000L); Date date02 = new Date(1421384400000L - 76400000L); Date date03 = new Date(1421384400000L - 86400000L); Date date04 = new Date(1421383400000L - 176400000L); for (int i = 0; i < 60; i++) { when(httpRequestInfoArray[i].getMaxAge()).thenReturn(86400000L); } for (int i = 0; i < 60; i++) { if (i % 2 == 1) { when(httpRequestInfoArray[i].getExpires()).thenReturn(date03); when(httpRequestInfoArray[i].getDate()).thenReturn(date02); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date02); when(httpRequestInfoArray[i].getLastModified()).thenReturn(date); } else { if (i < 40) { when(httpRequestInfoArray[i].getLastModified()).thenReturn(date01); when(httpRequestInfoArray[i].getRangeFirst()).thenReturn(0); when(httpRequestInfoArray[i].getRangeLast()).thenReturn(5); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date02); when(httpRequestInfoArray[i].getExpires()).thenReturn(date); when(httpRequestInfoArray[i].getDate()).thenReturn(date03); } else { when(httpRequestInfoArray[i].getLastModified()).thenReturn(date02); when(httpRequestInfoArray[i].getExpires()).thenReturn(date04); when(httpRequestInfoArray[i].getDate()).thenReturn(date); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date); when(httpRequestInfoArray[i].getRangeFirst()).thenReturn(0); when(httpRequestInfoArray[i].getRangeLast()).thenReturn(13); } } } when(httpRequestInfoArray[30].isRangeResponse()).thenReturn(false); when(httpRequestInfoArray[31].isRangeResponse()).thenReturn(false); when(rrhelper.getActualByteCount(any(HttpRequestResponseInfo.class), any(Session.class))).thenReturn(2L); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); for (int i = 0; i < 60; i++) { value.add(httpRequestInfoArray[i]); } packets.add(pktInfo01); packets.add(pktInfo02); session01.setPackets(packets); session02.setPackets(packets); when(session01.getRequestResponseInfo()).thenReturn(value); when(session01.isUdpOnly()).thenReturn(false); when(session01.getPackets()).thenReturn(packets); when(session02.isUdpOnly()).thenReturn(false); when(session02.getRequestResponseInfo()).thenReturn(value); when(session02.getPackets()).thenReturn(packets); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); sessionList.add(session02); CacheAnalysis testResult = cacheAnalysis.analyze(sessionList); assertEquals(4, testResult.getCacheExpirationResponses().size()); assertEquals(60, testResult.getDiagnosisResults().size()); assertEquals(0, testResult.getDuplicateContentBytes()); assertEquals(0, testResult.getDuplicateContentBytesRatio(), 0.0); assertEquals(0, testResult.getDuplicateContentWithOriginals().size()); }
@Test public void analyze_2() { List<PacketInfo> packets = new ArrayList<PacketInfo>(); pktInfo01 = Mockito.mock(PacketInfo.class); pktInfo02 = Mockito.mock(PacketInfo.class); for (int i = 0; i < 60; i++) { httpRequestInfoArray[i] = mock(HttpRequestResponseInfo.class); } for (int i = 0; i < 20; i++) { when(httpRequestInfoArray[i].isNoStore()).thenReturn(true); if (i % 2 == 1) { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.REQUEST); when(httpRequestInfoArray[i].getHostName()).thenReturn("www.google.com"); when(httpRequestInfoArray[i].getObjName()).thenReturn(Util.getCurrentRunningDir()); when(httpRequestInfoArray[i].getContentLength()).thenReturn(5); } else { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.RESPONSE); when(httpRequestInfoArray[18].getStatusCode()).thenReturn(304); } } for (int i = 20; i < 60; i++) { when(httpRequestInfoArray[i].isNoStore()).thenReturn(false); when(httpRequestInfoArray[i].getHostName()).thenReturn("www.google.com" + i); when(httpRequestInfoArray[i].getObjName()).thenReturn(Util.getCurrentRunningDir()); when(httpRequestInfoArray[i - 2].isRangeResponse()).thenReturn(true); when(httpRequestInfoArray[i].getContentLength()).thenReturn(5); if ((i - 20) % 2 == 1) { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.REQUEST); } else { when(httpRequestInfoArray[i].getDirection()).thenReturn(HttpDirection.RESPONSE); when(httpRequestInfoArray[i].getStatusCode()).thenReturn(206); } } when(httpRequestInfoArray[2].getAssocReqResp()).thenReturn(null); when(httpRequestInfoArray[4].getAssocReqResp()).thenReturn(httpRequestInfoArray[3]); when(httpRequestInfoArray[6].getAssocReqResp()).thenReturn(httpRequestInfoArray[5]); when(httpRequestInfoArray[8].getAssocReqResp()).thenReturn(httpRequestInfoArray[7]); when(httpRequestInfoArray[10].getAssocReqResp()).thenReturn(httpRequestInfoArray[9]); when(httpRequestInfoArray[12].getAssocReqResp()).thenReturn(httpRequestInfoArray[11]); when(httpRequestInfoArray[14].getAssocReqResp()).thenReturn(httpRequestInfoArray[13]); for (int i = 18; i < 60; i++) { when(httpRequestInfoArray[i].getAssocReqResp()).thenReturn(httpRequestInfoArray[i - 1]); } for (int i = 50; i < 60; i++) { when(httpRequestInfoArray[i].isRangeResponse()).thenReturn(false); when(httpRequestInfoArray[i].isChunked()).thenReturn(true); when(httpRequestInfoArray[i].getContentLength()).thenReturn(5); } for (int i = 0; i < 50; i++) { when(httpRequestInfoArray[i].isRangeResponse()).thenReturn(true); } when(httpRequestInfoArray[7].getHostName()).thenReturn(null); when(httpRequestInfoArray[7].getObjName()).thenReturn(null); when(httpRequestInfoArray[0].getStatusCode()).thenReturn(0); when(httpRequestInfoArray[2].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[4].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[6].getStatusCode()).thenReturn(200); when(httpRequestInfoArray[8].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[10].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[12].getStatusCode()).thenReturn(206); when(httpRequestInfoArray[14].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[16].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[18].getStatusCode()).thenReturn(304); when(httpRequestInfoArray[1].getRequestType()).thenReturn(HttpRequestResponseInfo.UTF8); when(httpRequestInfoArray[3].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[5].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[7].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[9].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[11].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[13].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[15].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_POST); when(httpRequestInfoArray[17].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[19].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_PUT); when(httpRequestInfoArray[20].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); when(httpRequestInfoArray[21].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); for (int i = 22; i < 60; i++) { if (i % 2 == 1) { when(httpRequestInfoArray[i].getRequestType()).thenReturn(HttpRequestResponseInfo.HTTP_GET); } } Date date01 = new Date(1421384400000L); Date date02 = new Date(1421384400000L - 76400000L); Date date03 = new Date(1421384400000L - 86400000L); Date date04 = new Date(1421383400000L - 176400000L); for (int i = 0; i < 60; i++) { when(httpRequestInfoArray[i].getMaxAge()).thenReturn(86400000L); } for (int i = 0; i < 60; i++) { if (i % 2 == 1) { when(httpRequestInfoArray[i].getExpires()).thenReturn(date03); when(httpRequestInfoArray[i].getDate()).thenReturn(date02); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date02); when(httpRequestInfoArray[i].getLastModified()).thenReturn(date); } else { if (i < 40) { when(httpRequestInfoArray[i].getLastModified()).thenReturn(date01); when(httpRequestInfoArray[i].getRangeFirst()).thenReturn(0); when(httpRequestInfoArray[i].getRangeLast()).thenReturn(5); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date02); when(httpRequestInfoArray[i].getExpires()).thenReturn(date); when(httpRequestInfoArray[i].getDate()).thenReturn(date03); } else { when(httpRequestInfoArray[i].getLastModified()).thenReturn(date02); when(httpRequestInfoArray[i].getExpires()).thenReturn(date04); when(httpRequestInfoArray[i].getDate()).thenReturn(date); when(httpRequestInfoArray[i].getAbsTimeStamp()).thenReturn(date); when(httpRequestInfoArray[i].getRangeFirst()).thenReturn(0); when(httpRequestInfoArray[i].getRangeLast()).thenReturn(13); } } } when(httpRequestInfoArray[30].isRangeResponse()).thenReturn(false); when(httpRequestInfoArray[31].isRangeResponse()).thenReturn(false); when(rrhelper.getActualByteCount(any(HttpRequestResponseInfo.class), any(Session.class))).thenReturn(2L); List<HttpRequestResponseInfo> value = new ArrayList<HttpRequestResponseInfo>(); for (int i = 0; i < 60; i++) { value.add(httpRequestInfoArray[i]); } packets.add(pktInfo01); packets.add(pktInfo02); when(session01.getRequestResponseInfo()).thenReturn(value); when(session01.isUdpOnly()).thenReturn(false); when(session01.getPackets()).thenReturn(packets); when(session02.isUdpOnly()).thenReturn(false); when(session02.getRequestResponseInfo()).thenReturn(value); when(session02.getPackets()).thenReturn(packets); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(session01); sessionList.add(session02); CacheAnalysis testResult = cacheAnalysis.analyze(sessionList); assertEquals(4, testResult.getCacheExpirationResponses().size()); assertEquals(60, testResult.getDiagnosisResults().size()); assertEquals(95, testResult.getDuplicateContentBytes()); assertEquals(0, testResult.getDuplicateContentBytesRatio(), 0.475); assertEquals(38, testResult.getDuplicateContentWithOriginals().size()); }
|
VideoStreamConstructor { public String findPathNameTiebreaker(String pathName) { if (filemanager.fileExist(pathName)) { String temp = pathName; int pos = pathName.lastIndexOf("."); if (pos > 0) { for (int idx = 1; idx < 200; idx++) { temp = String.format("%s(%03d)%s", pathName.substring(0, pos), idx, pathName.substring(pos)); if (!filemanager.fileExist(temp)) { return temp; } } } else { for (int idx = 1; idx < 200; idx++) { temp = String.format("%s(%03d)", pathName, idx); if (!filemanager.fileExist(temp)) { return temp; } } } LOG.debug("duplicate file(s) found :" + pathName); return pathName + "(duplicated)"; } else { return pathName; } } VideoStreamConstructor(); String extractExtensionFromRequest(HttpRequestResponseInfo req); String extractNameFromRRInfo(HttpRequestResponseInfo req); String extractFullNameFromRRInfo(HttpRequestResponseInfo req); void extractVideo(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request, Double timeStamp); void updateVideoNameSize(); String shortenNameByParts(String srcString, String matchStr, int groupCount); String buildSegmentFullPathName(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); String buildPath(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request, int segmentID, String segmentQuality, String fileName); void collectFromFFMPEG(String fullPath, ChildManifest childManifest, Manifest manifest); ChildManifest locateChildManifestAndSegmentInfo(HttpRequestResponseInfo request, Double timeStamp, ManifestCollection manifestCollection); SegmentInfo nullSegmentInfo(); String buildByteRangeKey(HttpRequestResponseInfo request); Manifest extractManifestHLS(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); double parseResolution(String lines); boolean savePayload(byte[] content, String pathName); String findPathNameTiebreaker(String pathName); void addFailedRequest(HttpRequestResponseInfo request); Manifest extractManifestDash(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); ManifestCollection getManifestCollectionMap(); void init(); }
|
@Test public void testFindPathNameTiebreaker_when_no_duplicates() throws Exception { String pathName = tempFolder + "/fileNotThere"; String incrementedName = videoStreamConstructor.findPathNameTiebreaker(pathName); assertThat(incrementedName).isEqualTo(pathName); System.out.println("tempFolder :" + tempFolder); }
@Test public void testFindPathNameTiebreaker_when_noExtension() throws Exception { String incrementedName = videoStreamConstructor.findPathNameTiebreaker(pathName1); assertThat(incrementedName).isEqualTo(pathName1 + "(001)"); }
@Test public void testFindPathNameTiebreaker_when_Extension() throws Exception { String incrementedName = videoStreamConstructor.findPathNameTiebreaker(pathName1 + ".xyz"); assertThat(incrementedName).isEqualTo(pathName1 + "(001).xyz"); }
|
VideoStreamConstructor { public String shortenNameByParts(String srcString, String matchStr, int groupCount) { if (!StringUtils.isEmpty(matchStr) && !StringUtils.isEmpty(srcString)) { int[] pos = StringParse.getStringPositions(srcString, matchStr); if (groupCount > 0 && pos.length > groupCount) { return srcString.substring(pos[pos.length - groupCount] + 1); } } return srcString; } VideoStreamConstructor(); String extractExtensionFromRequest(HttpRequestResponseInfo req); String extractNameFromRRInfo(HttpRequestResponseInfo req); String extractFullNameFromRRInfo(HttpRequestResponseInfo req); void extractVideo(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request, Double timeStamp); void updateVideoNameSize(); String shortenNameByParts(String srcString, String matchStr, int groupCount); String buildSegmentFullPathName(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); String buildPath(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request, int segmentID, String segmentQuality, String fileName); void collectFromFFMPEG(String fullPath, ChildManifest childManifest, Manifest manifest); ChildManifest locateChildManifestAndSegmentInfo(HttpRequestResponseInfo request, Double timeStamp, ManifestCollection manifestCollection); SegmentInfo nullSegmentInfo(); String buildByteRangeKey(HttpRequestResponseInfo request); Manifest extractManifestHLS(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); double parseResolution(String lines); boolean savePayload(byte[] content, String pathName); String findPathNameTiebreaker(String pathName); void addFailedRequest(HttpRequestResponseInfo request); Manifest extractManifestDash(StreamingVideoData streamingVideoData, HttpRequestResponseInfo request); ManifestCollection getManifestCollectionMap(); void init(); }
|
@Test public void testShortenNameByParts() throws Exception { String fullString = "one:two:three:four:five"; String shortString = videoStreamConstructor.shortenNameByParts(fullString, ":", 2); assertThat(shortString).isEqualTo("four:five"); }
@Test public void testShortenNameByParts_when_full_count() throws Exception { String fullString = "one:two:three:four:five"; String shortString = videoStreamConstructor.shortenNameByParts(fullString, ":", 5); assertThat(shortString).isEqualTo("one:two:three:four:five"); }
@Test public void testShortenNameByParts_when_over_count() throws Exception { String fullString = "one:two:three:four:five"; String shortString = videoStreamConstructor.shortenNameByParts(fullString, ":", 6); assertThat(shortString).isEqualTo("one:two:three:four:five"); }
@Test public void testShortenNameByParts_when_no_count() throws Exception { String fullString = "one:two:three:four:five"; String shortString = videoStreamConstructor.shortenNameByParts(fullString, ":", 0); assertThat(shortString).isEqualTo("one:two:three:four:five"); }
|
RrcStateRangeFactoryImpl implements IRrcStateRangeFactory { @Override public List<RrcStateRange> create(List<PacketInfo> packetlist, Profile profile, double traceDuration) { if(profile.getProfileType() == ProfileType.T3G){ Profile3G prof = (Profile3G)profile; return this.create3G(packetlist, prof, traceDuration); }else if(profile.getProfileType() == ProfileType.WIFI){ ProfileWiFi prof = (ProfileWiFi)profile; return this.createWiFi(packetlist, prof, traceDuration); }else if(profile.getProfileType() == ProfileType.LTE){ ProfileLTE prof = (ProfileLTE)profile; return this.createLTE(packetlist, prof, traceDuration); }else{ throw new IllegalArgumentException("Invalid profile type for state machine: " + profile.getClass()); } } @Override List<RrcStateRange> create(List<PacketInfo> packetlist,
Profile profile, double traceDuration); }
|
@Test public void create_LTEIsIdle() { ProfileLTE profile02 = mock(ProfileLTE.class); when(profile02.getProfileType()).thenReturn(ProfileType.LTE); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); double traceDuration = 2000.0; List<RrcStateRange> testResult = rrcStateRangeFactory.create(packetlist1, profile02, traceDuration); assertEquals(1, testResult.size()); }
@Test public void create_ProfileIsLTE() { ProfileLTE profile01 = mock(ProfileLTE.class); List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); double traceDuration = 2000.0; when(profile01.getProfileType()).thenReturn(ProfileType.LTE); when(profile01.getPromotionTime()).thenReturn(1000.0); when(profile01.getInactivityTimer()).thenReturn(1000.0); when(profile01.getDrxShortTime()).thenReturn(1000.0); when(profile01.getDrxLongTime()).thenReturn(1000.0); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 100.0); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 500.0); when(pktInfoArray[3].getTimeStamp()).thenReturn(date.getTime() + 2300.0); when(pktInfoArray[4].getTimeStamp()).thenReturn(date.getTime() + 3005.0); when(pktInfoArray[5].getTimeStamp()).thenReturn(date.getTime() + 4500.0); when(pktInfoArray[6].getTimeStamp()).thenReturn(date.getTime() + 5501.0); when(pktInfoArray[7].getTimeStamp()).thenReturn(date.getTime() + 6001.0); when(pktInfoArray[8].getTimeStamp()).thenReturn(date.getTime() + 9001.0); when(pktInfoArray[9].getTimeStamp()).thenReturn(date.getTime() + 16001.0); when(pktInfoArray[10].getTimeStamp()).thenReturn(date.getTime() + 17001.0); when(pktInfoArray[11].getTimeStamp()).thenReturn(date.getTime() + 19000.0); when(pktInfoArray[12].getTimeStamp()).thenReturn(date.getTime() + 29900.0); when(pktInfoArray[13].getTimeStamp()).thenReturn(date.getTime() + 35500.0); when(pktInfoArray[14].getTimeStamp()).thenReturn(date.getTime() + 45005.0); when(pktInfoArray[15].getTimeStamp()).thenReturn(date.getTime() + 46500.0); when(pktInfoArray[16].getTimeStamp()).thenReturn(date.getTime() + 47501.0); when(pktInfoArray[17].getTimeStamp()).thenReturn(date.getTime() + 47601.0); when(pktInfoArray[18].getTimeStamp()).thenReturn(date.getTime() + 57001.0); when(pktInfoArray[19].getTimeStamp()).thenReturn(date.getTime() + 66001.0); for (int i = 0; i < 20; i++) { packetlist.add(pktInfoArray[i]); } List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile01, traceDuration); assertEquals(64, testList.size()); }
@Test public void create_WIFIIsIdleTrace() { ProfileWiFi profile04 = mock(ProfileWiFi.class); when(profile04.getProfileType()).thenReturn(ProfileType.WIFI); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); double traceDuration = 2000.0; List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist1, profile04, traceDuration); assertEquals(1, testList.size()); }
@Test public void create_ProfileIsWifi() { ProfileWiFi profile03 = mock(ProfileWiFi.class); when(profile03.getProfileType()).thenReturn(ProfileType.WIFI); List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); double traceDuration = 1000.0; when(profile03.getWifiTailTime()).thenReturn(1500.0); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() - 500.0); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 500.0); when(pktInfoArray[3].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[4].getTimeStamp()).thenReturn(date.getTime() + 2505.0); when(pktInfoArray[5].getTimeStamp()).thenReturn(date.getTime() + 3500.0); when(pktInfoArray[6].getTimeStamp()).thenReturn(date.getTime() + 4501.0); when(pktInfoArray[7].getTimeStamp()).thenReturn(date.getTime() + 5001.0); when(pktInfoArray[8].getTimeStamp()).thenReturn(date.getTime() + 6001.0); when(pktInfoArray[9].getTimeStamp()).thenReturn(date.getTime() + 6501.0); when(pktInfoArray[10].getTimeStamp()).thenReturn(date.getTime() + 7001.0); when(pktInfoArray[11].getTimeStamp()).thenReturn(date.getTime() + 9000.0); when(pktInfoArray[12].getTimeStamp()).thenReturn(date.getTime() + 9900.0); when(pktInfoArray[13].getTimeStamp()).thenReturn(date.getTime() + 15500.0); when(pktInfoArray[14].getTimeStamp()).thenReturn(date.getTime() + 25005.0); when(pktInfoArray[15].getTimeStamp()).thenReturn(date.getTime() + 36500.0); when(pktInfoArray[16].getTimeStamp()).thenReturn(date.getTime() + 47501.0); when(pktInfoArray[17].getTimeStamp()).thenReturn(date.getTime() + 57601.0); when(pktInfoArray[18].getTimeStamp()).thenReturn(date.getTime() + 107001.0); when(pktInfoArray[19].getTimeStamp()).thenReturn(date.getTime() + 216001.0); for (int i = 0; i < 20; i++) { packetlist.add(pktInfoArray[i]); } List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile03, traceDuration); assertEquals(26, testList.size()); }
@Test public void create3G_() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(1000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(1000.0); when(profile3g.getFachDchPromoMax()).thenReturn(1000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(1000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 100.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[3].getTimeStamp()).thenReturn(date.getTime() + 2300.0); when(pktInfoArray[3].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[3].getLen()).thenReturn(1000); when(pktInfoArray[3].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[4].getTimeStamp()).thenReturn(date.getTime() + 3005.0); when(pktInfoArray[4].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[4].getLen()).thenReturn(1000); when(pktInfoArray[4].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[5].getTimeStamp()).thenReturn(date.getTime() + 4500.0); when(pktInfoArray[5].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[5].getLen()).thenReturn(1000); when(pktInfoArray[5].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[6].getTimeStamp()).thenReturn(date.getTime() + 5501.0); when(pktInfoArray[6].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[6].getLen()).thenReturn(1000); when(pktInfoArray[6].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[7].getTimeStamp()).thenReturn(date.getTime() + 6001.0); when(pktInfoArray[7].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[7].getLen()).thenReturn(1000); when(pktInfoArray[7].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[8].getTimeStamp()).thenReturn(date.getTime() + 9601.0); when(pktInfoArray[8].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[8].getLen()).thenReturn(1000); when(pktInfoArray[8].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[9].getTimeStamp()).thenReturn(date.getTime() + 16001.0); when(pktInfoArray[9].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[9].getLen()).thenReturn(1000); when(pktInfoArray[9].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[10].getTimeStamp()).thenReturn(date.getTime() + 17601.0); when(pktInfoArray[10].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[10].getLen()).thenReturn(1000); when(pktInfoArray[10].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[11].getTimeStamp()).thenReturn(date.getTime() + 18000.0); when(pktInfoArray[11].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[11].getLen()).thenReturn(1000); when(pktInfoArray[11].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[12].getTimeStamp()).thenReturn(date.getTime() + 29900.0); when(pktInfoArray[12].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[12].getLen()).thenReturn(1000); when(pktInfoArray[12].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); when(pktInfoArray[13].getTimeStamp()).thenReturn(date.getTime() + 35500.0); when(pktInfoArray[13].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[13].getLen()).thenReturn(1000); when(pktInfoArray[13].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[14].getTimeStamp()).thenReturn(date.getTime() + 45005.0); when(pktInfoArray[14].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[14].getLen()).thenReturn(1000); when(pktInfoArray[14].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[15].getTimeStamp()).thenReturn(date.getTime() + 46500.0); when(pktInfoArray[15].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[15].getLen()).thenReturn(1000); when(pktInfoArray[15].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[16].getTimeStamp()).thenReturn(date.getTime() + 47501.0); when(pktInfoArray[16].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[16].getLen()).thenReturn(1000); when(pktInfoArray[16].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[17].getTimeStamp()).thenReturn(date.getTime() + 47601.0); when(pktInfoArray[17].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[17].getLen()).thenReturn(1000); when(pktInfoArray[17].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); when(pktInfoArray[18].getTimeStamp()).thenReturn(date.getTime() + 57001.0); when(pktInfoArray[18].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[18].getLen()).thenReturn(1000); when(pktInfoArray[18].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[19].getTimeStamp()).thenReturn(date.getTime() + 66001.0); when(pktInfoArray[19].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[19].getLen()).thenReturn(1000); when(pktInfoArray[19].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[20].getTimeStamp()).thenReturn(date.getTime() + 66301.0); when(pktInfoArray[20].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[20].getLen()).thenReturn(1000); when(pktInfoArray[20].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[21].getTimeStamp()).thenReturn(date.getTime() + 62301.0); when(pktInfoArray[21].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[21].getLen()).thenReturn(1000); when(pktInfoArray[21].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[22].getTimeStamp()).thenReturn(date.getTime() + 63101.0); when(pktInfoArray[22].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[22].getLen()).thenReturn(1000); when(pktInfoArray[22].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[23].getTimeStamp()).thenReturn(date.getTime() + 65501.0); when(pktInfoArray[23].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[23].getLen()).thenReturn(1000); when(pktInfoArray[23].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[24].getTimeStamp()).thenReturn(date.getTime() + 67501.0); when(pktInfoArray[24].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[24].getLen()).thenReturn(1000); when(pktInfoArray[24].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[25].getTimeStamp()).thenReturn(date.getTime() + 70501.0); when(pktInfoArray[25].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[25].getLen()).thenReturn(1000); when(pktInfoArray[25].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[26].getTimeStamp()).thenReturn(date.getTime() + 80501.0); when(pktInfoArray[26].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[26].getLen()).thenReturn(1000); when(pktInfoArray[26].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[27].getTimeStamp()).thenReturn(date.getTime() + 84601.0); when(pktInfoArray[27].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[27].getLen()).thenReturn(1000); when(pktInfoArray[27].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[28].getTimeStamp()).thenReturn(date.getTime() + 86101.0); when(pktInfoArray[28].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[28].getLen()).thenReturn(1000); when(pktInfoArray[28].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[29].getTimeStamp()).thenReturn(date.getTime() + 86301.0); when(pktInfoArray[29].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[29].getLen()).thenReturn(1000); when(pktInfoArray[29].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[30].getTimeStamp()).thenReturn(date.getTime() + 87901.0); when(pktInfoArray[30].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[30].getLen()).thenReturn(1000); when(pktInfoArray[30].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[31].getTimeStamp()).thenReturn(date.getTime() + 88301.0); when(pktInfoArray[31].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[31].getLen()).thenReturn(1000); when(pktInfoArray[31].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[32].getTimeStamp()).thenReturn(date.getTime() + 90401.0); when(pktInfoArray[32].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[32].getLen()).thenReturn(1000); when(pktInfoArray[32].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[33].getTimeStamp()).thenReturn(date.getTime() + 91101.0); when(pktInfoArray[33].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[33].getLen()).thenReturn(1000); when(pktInfoArray[33].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); when(pktInfoArray[34].getTimeStamp()).thenReturn(date.getTime() + 91500.0); when(pktInfoArray[34].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[34].getLen()).thenReturn(1000); when(pktInfoArray[34].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[35].getTimeStamp()).thenReturn(date.getTime() + 94605.0); when(pktInfoArray[35].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[35].getLen()).thenReturn(1000); when(pktInfoArray[35].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[36].getTimeStamp()).thenReturn(date.getTime() + 98700.0); when(pktInfoArray[36].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[36].getLen()).thenReturn(1000); when(pktInfoArray[36].getStateMachine()).thenReturn(RRCState.STATE_DCH); when(pktInfoArray[37].getTimeStamp()).thenReturn(date.getTime() + 98800.0); when(pktInfoArray[37].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[37].getLen()).thenReturn(1000); when(pktInfoArray[37].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[38].getTimeStamp()).thenReturn(date.getTime() + 98900.0); when(pktInfoArray[38].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[38].getLen()).thenReturn(1000); when(pktInfoArray[38].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[39].getTimeStamp()).thenReturn(date.getTime() + 99200.0); when(pktInfoArray[39].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[39].getLen()).thenReturn(1000); when(pktInfoArray[39].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[40].getTimeStamp()).thenReturn(date.getTime() + 99300.0); when(pktInfoArray[40].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[40].getLen()).thenReturn(1000); when(pktInfoArray[40].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[41].getTimeStamp()).thenReturn(date.getTime() + 109400.0); when(pktInfoArray[41].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[41].getLen()).thenReturn(1000); when(pktInfoArray[41].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[42].getTimeStamp()).thenReturn(date.getTime() + 109500.0); when(pktInfoArray[42].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[42].getLen()).thenReturn(1000); when(pktInfoArray[42].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[43].getTimeStamp()).thenReturn(date.getTime() + 119600.0); when(pktInfoArray[43].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[43].getLen()).thenReturn(1000); when(pktInfoArray[43].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[44].getTimeStamp()).thenReturn(date.getTime() + 123600.0); when(pktInfoArray[44].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[44].getLen()).thenReturn(1000); when(pktInfoArray[44].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[45].getTimeStamp()).thenReturn(date.getTime() + 124500.0); when(pktInfoArray[45].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[45].getLen()).thenReturn(1000); when(pktInfoArray[45].getStateMachine()).thenReturn(RRCState.STATE_FACH); when(pktInfoArray[46].getTimeStamp()).thenReturn(date.getTime() + 139600.0); when(pktInfoArray[46].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[46].getLen()).thenReturn(1000); when(pktInfoArray[46].getStateMachine()).thenReturn(RRCState.STATE_FACH); for (int i = 0; i < 47; i++) { packetlist.add(pktInfoArray[i]); } List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void create3G_test2() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(1000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(1000.0); when(profile3g.getFachDchPromoMax()).thenReturn(1000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(1000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.TAIL_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 100.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[1]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void create3G_test3() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMin()).thenReturn((double) date.getTime()); when(profile3g.getIdleDchPromoMax()).thenReturn(1500.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(1000.0); when(profile3g.getFachDchPromoMax()).thenReturn(1000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(1000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 100.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void create3G_test4() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn((double) date.getTime()); when(profile3g.getIdleDchPromoMin()).thenReturn((double) date.getTime()); when(profile3g.getIdleDchPromoMax()).thenReturn((double) date.getTime()); when(profile3g.getFachDchPromoAvg()).thenReturn((double) date.getTime()); when(profile3g.getFachDchPromoMin()).thenReturn((double) date.getTime()); when(profile3g.getFachDchPromoMax()).thenReturn((double) date.getTime()); when(profile3g.getDchFachTimer()).thenReturn((double) date.getTime()); when(profile3g.getFachIdleTimer()).thenReturn((double) date.getTime()); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 100.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[2]); when(pktInfoArray[3].getTimeStamp()).thenReturn(date.getTime() + 2300.0); when(pktInfoArray[3].getDir()).thenReturn(PacketDirection.UNKNOWN); when(pktInfoArray[3].getLen()).thenReturn(1000); when(pktInfoArray[3].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[3]); when(pktInfoArray[4].getTimeStamp()).thenReturn(date.getTime() + 3005.0); when(pktInfoArray[4].getDir()).thenReturn(PacketDirection.UNKNOWN); when(pktInfoArray[4].getLen()).thenReturn(1000); when(pktInfoArray[4].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[4]); when(pktInfoArray[5].getTimeStamp()).thenReturn(date.getTime() + 4500.0); when(pktInfoArray[5].getDir()).thenReturn(PacketDirection.UNKNOWN); when(pktInfoArray[5].getLen()).thenReturn(1000); when(pktInfoArray[5].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[5]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test5() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 5500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 5000.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test6() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 5500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 5000.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test7() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 7500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.UNKNOWN); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 10000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 15000.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.UNKNOWN); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test8() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 7500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.PROMO_FACH_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 10000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 15000.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.PROMO_IDLE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test9() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 7500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 10000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 15000.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test10() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(5000.0); when(profile3g.getFachIdleTimer()).thenReturn(10000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 3500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test11() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(2000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test12() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(2000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_DCH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test13() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(2000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.UPLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test14() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(2000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
@Test public void Create3G_test15() { Profile3G profile3g = mock(Profile3G.class); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getIdleDchPromoAvg()).thenReturn(12000.0); when(profile3g.getIdleDchPromoMin()).thenReturn(1000.0); when(profile3g.getIdleDchPromoMax()).thenReturn(20000.0); when(profile3g.getFachDchPromoAvg()).thenReturn(1000.0); when(profile3g.getFachDchPromoMin()).thenReturn(2500.0); when(profile3g.getFachDchPromoMax()).thenReturn(6000.0); when(profile3g.getDchFachTimer()).thenReturn(1000.0); when(profile3g.getFachIdleTimer()).thenReturn(2000.0); double traceDuration = 2000.0; List<PacketInfo> packetlist = new ArrayList<PacketInfo>(); when(pktInfoArray[0].getTimeStamp()).thenReturn(date.getTime() - 1500.0); when(pktInfoArray[0].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[0].getLen()).thenReturn(1000); when(pktInfoArray[0].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[0]); when(pktInfoArray[1].getTimeStamp()).thenReturn(date.getTime() + 1000.0); when(pktInfoArray[1].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[1].getLen()).thenReturn(1000); when(pktInfoArray[1].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[1]); when(pktInfoArray[2].getTimeStamp()).thenReturn(date.getTime() + 1500.0); when(pktInfoArray[2].getDir()).thenReturn(PacketDirection.DOWNLINK); when(pktInfoArray[2].getLen()).thenReturn(1000); when(pktInfoArray[2].getStateMachine()).thenReturn(RRCState.STATE_FACH); packetlist.add(pktInfoArray[2]); List<RrcStateRange> testList = rrcStateRangeFactory.create(packetlist, profile3g, traceDuration); assertEquals(1, testList.size()); }
|
KeywordSearchingHandler implements ISearchingHandler { @Override public SearchingResult search(SearchingPattern pattern, SearchingContent content) { if (!isValidPattern(pattern) || !isValidContent(content)) { return new SearchingResultBuilder().build(); } return searchingStrategy.applySearch(pattern, content); } @Override SearchingResult search(SearchingPattern pattern, SearchingContent content); @Override boolean isValidPattern(SearchingPattern pattern); @Override boolean isValidContent(SearchingContent content); }
|
@Test public void testSingleSearchingPattern() { SearchingPatternBuilder patternBuilder = new SearchingPatternBuilder(); patternBuilder.add("abc", PrivateDataType.regex_credit_card_number.name()); SearchingContent content = new SearchingContent("abcde"); SearchingResult result = searchingHandler.search(patternBuilder.build(), content); assertNotNull(result); assertEquals("abc", result.getWords().get(0)); }
@Test public void testMultiSearchingPattern() { SearchingPatternBuilder patternBuilder = new SearchingPatternBuilder(); patternBuilder.add("abc", PrivateDataType.regex_credit_card_number.name()) .add("bcd", PrivateDataType.regex_credit_card_number.name()) .add("def", PrivateDataType.regex_credit_card_number.name()); SearchingContent content = new SearchingContent("abcde"); SearchingResult result = searchingHandler.search(patternBuilder.build(), content); assertNotNull(result); assertEquals(2, result.getWords().size()); }
@Test public void testUnknownSearchingPattern() { SearchingPattern pattern = null; SearchingContent content = new SearchingContent("abcde"); SearchingResult result = searchingHandler.search(pattern, content); assertNotNull(result); assertEquals(0, result.getWords().size()); }
|
BurstCollectionAnalysisImpl implements IBurstCollectionAnalysis { @Override public BurstCollectionAnalysisData analyze(List<PacketInfo> packets, Profile profile, Map<Integer, Integer> packetSizeToCountMap, List<RrcStateRange> rrcstaterangelist, List<UserEvent> usereventlist, List<CpuActivity> cpuactivitylist, List<Session> sessionlist) { BurstCollectionAnalysisData data = new BurstCollectionAnalysisData(); Set<Integer> mss = calculateMssLargerPacketSizeSet(packetSizeToCountMap); List<Burst> burstCollection = groupIntoBursts(packets, profile, mss, rrcstaterangelist); data.setBurstCollection(burstCollection); if(!burstCollection.isEmpty()){ int longBurstCount = analyzeBursts(burstCollection, usereventlist, cpuactivitylist, profile); data.setLongBurstCount(longBurstCount); double totalEnergy = computeBurstEnergyRadioResource(rrcstaterangelist, burstCollection, profile); data.setTotalEnergy(totalEnergy); List<BurstAnalysisInfo> burstAnalysisInfo = analyzeBurstStat(burstCollection); data.setBurstAnalysisInfo(burstAnalysisInfo); PacketInfo shortestPacket = findShortestPeriodPacketInfo(burstCollection); data.setShortestPeriodPacketInfo(shortestPacket); } return data; } @Override BurstCollectionAnalysisData analyze(List<PacketInfo> packets,
Profile profile, Map<Integer, Integer> packetSizeToCountMap,
List<RrcStateRange> rrcstaterangelist,
List<UserEvent> usereventlist, List<CpuActivity> cpuactivitylist,
List<Session> sessionlist); }
|
@Test public void analyzeTest() { InetAddress iAdr = Mockito.mock(InetAddress.class); InetAddress iAdr1 = Mockito.mock(InetAddress.class); Mockito.when(iAdr.getAddress()).thenReturn(new byte[] { 89, 10, 1, 1 }); Mockito.when(iAdr1.getAddress()).thenReturn(new byte[] { 72, 12, 13, 1 }); Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(30); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); Mockito.when(packetInfo1.getTimeStamp()).thenReturn(500d); InetAddress iAdr2 = Mockito.mock(InetAddress.class); Mockito.when(iAdr2.getAddress()).thenReturn(new byte[] { 95, 10, 1, 1 }); TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getTimeStamp()).thenReturn(1000d); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(25); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); Mockito.when(packetInfo2.getTimeStamp()).thenReturn(10d); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(false); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(50d); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_RECOVER); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(15); Mockito.when(packetInfo3.getLen()).thenReturn(20); Mockito.when(packetInfo3.getAppName()).thenReturn("Test3"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test3String"); Mockito.when(packetInfo3.getTimeStamp()).thenReturn(700d); PacketInfo packetInfo4 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo4.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo4.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo4.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK); Mockito.when(packetInfo4.getTimeStamp()).thenReturn(90d); Mockito.when(packetInfo4.getPayloadLen()).thenReturn(10); PacketInfo packetInfo5 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo5.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo5.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo5.getTcpInfo()).thenReturn(TcpInfo.TCP_DATA_RECOVER); Mockito.when(packetInfo5.getTimeStamp()).thenReturn(750d); Mockito.when(packetInfo5.getPayloadLen()).thenReturn(5); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); packetsList.add(packetInfo4); packetsList.add(packetInfo5); ProfileWiFi profile = Mockito.mock(ProfileWiFi.class); Mockito.when(profile.getBurstTh()).thenReturn(50d); Mockito.when(profile.getLongBurstTh()).thenReturn(40.0d); Mockito.when(profile.getLargeBurstDuration()).thenReturn(150d); Mockito.when(profile.getLargeBurstSize()).thenReturn(50); Mockito.when(profile.getProfileType()).thenReturn(ProfileType.WIFI); Mockito.when(profile.getWifiTailTime()).thenReturn(25.0d); Mockito.when(profile.getWifiIdlePower()).thenReturn(50.0d); Mockito.when(profile.getWifiTailTime()).thenReturn(75.0d); Map<Integer, Integer> packetSizeToCountMap = new HashMap<Integer, Integer>(); packetSizeToCountMap.put(1001, 10); packetSizeToCountMap.put(2002, 20); packetSizeToCountMap.put(3003, 30); RrcStateRange rrcStateRange1 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange1.getBeginTime()).thenReturn(500d); Mockito.when(rrcStateRange1.getEndTime()).thenReturn(490d); Mockito.when(rrcStateRange1.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange2 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange2.getBeginTime()).thenReturn(8.30d); Mockito.when(rrcStateRange2.getEndTime()).thenReturn(12.30d); Mockito.when(rrcStateRange2.getState()).thenReturn(RRCState.PROMO_FACH_DCH); RrcStateRange rrcStateRange3 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange3.getBeginTime()).thenReturn(0.0d); Mockito.when(rrcStateRange3.getEndTime()).thenReturn(-2.0d); Mockito.when(rrcStateRange3.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange4 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange4.getBeginTime()).thenReturn(25d); Mockito.when(rrcStateRange4.getEndTime()).thenReturn(75d); Mockito.when(rrcStateRange4.getState()).thenReturn(RRCState.WIFI_TAIL); RrcStateRange rrcStateRange5 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange5.getBeginTime()).thenReturn(55d); Mockito.when(rrcStateRange5.getEndTime()).thenReturn(95d); Mockito.when(rrcStateRange5.getState()).thenReturn(RRCState.PROMO_IDLE_DCH); List<RrcStateRange> rrcstaterangelist = new ArrayList<RrcStateRange>(); rrcstaterangelist.add(rrcStateRange1); rrcstaterangelist.add(rrcStateRange2); rrcstaterangelist.add(rrcStateRange3); rrcstaterangelist.add(rrcStateRange4); rrcstaterangelist.add(rrcStateRange5); UserEvent uEvent1 = Mockito.mock(UserEvent.class); Mockito.when(uEvent1.getEventType()).thenReturn(UserEventType.SCREEN_LANDSCAPE); Mockito.when(uEvent1.getPressTime()).thenReturn(503d); Mockito.when(uEvent1.getReleaseTime()).thenReturn(6d); UserEvent uEvent2 = Mockito.mock(UserEvent.class); Mockito.when(uEvent2.getEventType()).thenReturn(UserEventType.SCREEN_PORTRAIT); Mockito.when(uEvent2.getPressTime()).thenReturn(14d); Mockito.when(uEvent2.getReleaseTime()).thenReturn(2000d); UserEvent uEvent3 = Mockito.mock(UserEvent.class); Mockito.when(uEvent3.getEventType()).thenReturn(UserEventType.KEY_RED); Mockito.when(uEvent3.getPressTime()).thenReturn(497d); Mockito.when(uEvent3.getReleaseTime()).thenReturn(499d); UserEvent uEvent4 = Mockito.mock(UserEvent.class); Mockito.when(uEvent4.getEventType()).thenReturn(UserEventType.EVENT_UNKNOWN); Mockito.when(uEvent4.getPressTime()).thenReturn(25d); Mockito.when(uEvent4.getReleaseTime()).thenReturn(4d); UserEvent uEvent5 = Mockito.mock(UserEvent.class); Mockito.when(uEvent5.getEventType()).thenReturn(UserEventType.KEY_SEARCH); Mockito.when(uEvent5.getPressTime()).thenReturn(752d); Mockito.when(uEvent5.getReleaseTime()).thenReturn(30000d); List<UserEvent> uEventList = new ArrayList<UserEvent>(); uEventList.add(uEvent1); uEventList.add(uEvent2); uEventList.add(uEvent3); uEventList.add(uEvent4); uEventList.add(uEvent5); CpuActivity cActivity1 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity1.getTimeStamp()).thenReturn(23000d); Mockito.when(cActivity1.getTotalCpuUsage()).thenReturn(5000d); CpuActivity cActivity2 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity2.getTimeStamp()).thenReturn(24000d); Mockito.when(cActivity2.getTotalCpuUsage()).thenReturn(6000d); CpuActivity cActivity3 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity3.getTimeStamp()).thenReturn(25000d); Mockito.when(cActivity3.getTotalCpuUsage()).thenReturn(6000d); List<CpuActivity> cpuActivityList = new ArrayList<CpuActivity>(); cpuActivityList.add(cActivity1); cpuActivityList.add(cActivity2); cpuActivityList.add(cActivity3); Session aSession = Mockito.mock(Session.class); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(aSession); BurstCollectionAnalysisData bcaData = aBurstCollectionAnalysis.analyze(packetsList, profile, packetSizeToCountMap, rrcstaterangelist, uEventList, cpuActivityList, sessionList); assertEquals(2, bcaData.getBurstAnalysisInfo().size()); assertEquals(3, bcaData.getBurstCollection().size()); assertEquals(0, bcaData.getLongBurstCount()); assertEquals(0, (int) bcaData.getTotalEnergy()); }
@Test public void analyze2Test() { InetAddress iAdr = Mockito.mock(InetAddress.class); InetAddress iAdr1 = Mockito.mock(InetAddress.class); Mockito.when(iAdr.getAddress()).thenReturn(new byte[] { 89, 10, 1, 1 }); Mockito.when(iAdr1.getAddress()).thenReturn(new byte[] { 72, 12, 13, 1 }); Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); Mockito.when(packetInfo1.getTimeStamp()).thenReturn(500d); InetAddress iAdr2 = Mockito.mock(InetAddress.class); Mockito.when(iAdr2.getAddress()).thenReturn(new byte[] { 95, 10, 1, 1 }); TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getTimeStamp()).thenReturn(1000d); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); Mockito.when(packetInfo2.getTimeStamp()).thenReturn(10d); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(false); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(50d); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_RECOVER); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo3.getLen()).thenReturn(20); Mockito.when(packetInfo3.getAppName()).thenReturn("Test3"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test3String"); Mockito.when(packetInfo3.getTimeStamp()).thenReturn(0d); PacketInfo packetInfo4 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo4.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo4.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo4.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK); Mockito.when(packetInfo4.getTimeStamp()).thenReturn(90d); Mockito.when(packetInfo4.getPayloadLen()).thenReturn(0); PacketInfo packetInfo5 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo5.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo5.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo5.getTcpInfo()).thenReturn(TcpInfo.TCP_DATA_RECOVER); Mockito.when(packetInfo5.getTimeStamp()).thenReturn(750d); Mockito.when(packetInfo5.getPayloadLen()).thenReturn(0); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); packetsList.add(packetInfo4); packetsList.add(packetInfo5); Profile3G profile = Mockito.mock(Profile3G.class); Mockito.when(profile.getBurstTh()).thenReturn(50d); Mockito.when(profile.getLongBurstTh()).thenReturn(40.0d); Mockito.when(profile.getLargeBurstDuration()).thenReturn(150d); Mockito.when(profile.getLargeBurstSize()).thenReturn(50); Mockito.when(profile.getProfileType()).thenReturn(ProfileType.T3G); Mockito.when(profile.getBurstTh()).thenReturn(25.0d); Mockito.when(profile.getCarrier()).thenReturn("ATT"); Mockito.when(profile.getCloseSpacedBurstThreshold()).thenReturn(45d); Mockito.when(profile.getDchFachTimer()).thenReturn(50.0d); Mockito.when(profile.getDchTimerResetSize()).thenReturn(75); Mockito.when(profile.getDchTimerResetWin()).thenReturn(75d); Mockito.when(profile.getDevice()).thenReturn("lg"); Mockito.when(profile.getFachDchPromoAvg()).thenReturn(100d); Mockito.when(profile.getFachDchPromoMax()).thenReturn(200d); Mockito.when(profile.getIdleDchPromoMin()).thenReturn(50d); Mockito.when(profile.getLargeBurstDuration()).thenReturn(500d); Mockito.when(profile.getLargeBurstSize()).thenReturn(1000); Mockito.when(profile.getLongBurstTh()).thenReturn(250d); Map<Integer, Integer> packetSizeToCountMap = new HashMap<Integer, Integer>(); packetSizeToCountMap.put(1001, 10); packetSizeToCountMap.put(2002, 20); packetSizeToCountMap.put(3003, 30); RrcStateRange rrcStateRange1 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange1.getBeginTime()).thenReturn(500d); Mockito.when(rrcStateRange1.getEndTime()).thenReturn(590d); Mockito.when(rrcStateRange1.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange2 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange2.getBeginTime()).thenReturn(8.30d); Mockito.when(rrcStateRange2.getEndTime()).thenReturn(12.30d); Mockito.when(rrcStateRange2.getState()).thenReturn(RRCState.PROMO_FACH_DCH); RrcStateRange rrcStateRange3 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange3.getBeginTime()).thenReturn(0.0d); Mockito.when(rrcStateRange3.getEndTime()).thenReturn(-2.0d); Mockito.when(rrcStateRange3.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange4 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange4.getBeginTime()).thenReturn(25d); Mockito.when(rrcStateRange4.getEndTime()).thenReturn(75d); Mockito.when(rrcStateRange4.getState()).thenReturn(RRCState.WIFI_TAIL); RrcStateRange rrcStateRange5 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange5.getBeginTime()).thenReturn(105d); Mockito.when(rrcStateRange5.getEndTime()).thenReturn(95d); Mockito.when(rrcStateRange5.getState()).thenReturn(RRCState.PROMO_IDLE_DCH); List<RrcStateRange> rrcstaterangelist = new ArrayList<RrcStateRange>(); rrcstaterangelist.add(rrcStateRange1); rrcstaterangelist.add(rrcStateRange2); rrcstaterangelist.add(rrcStateRange3); rrcstaterangelist.add(rrcStateRange4); rrcstaterangelist.add(rrcStateRange5); UserEvent uEvent1 = Mockito.mock(UserEvent.class); Mockito.when(uEvent1.getEventType()).thenReturn(UserEventType.SCREEN_LANDSCAPE); Mockito.when(uEvent1.getPressTime()).thenReturn(503d); Mockito.when(uEvent1.getReleaseTime()).thenReturn(6d); UserEvent uEvent2 = Mockito.mock(UserEvent.class); Mockito.when(uEvent2.getEventType()).thenReturn(UserEventType.SCREEN_PORTRAIT); Mockito.when(uEvent2.getPressTime()).thenReturn(14d); Mockito.when(uEvent2.getReleaseTime()).thenReturn(2000d); UserEvent uEvent3 = Mockito.mock(UserEvent.class); Mockito.when(uEvent3.getEventType()).thenReturn(UserEventType.KEY_RED); Mockito.when(uEvent3.getPressTime()).thenReturn(497d); Mockito.when(uEvent3.getReleaseTime()).thenReturn(499d); UserEvent uEvent4 = Mockito.mock(UserEvent.class); Mockito.when(uEvent4.getEventType()).thenReturn(UserEventType.EVENT_UNKNOWN); Mockito.when(uEvent4.getPressTime()).thenReturn(25d); Mockito.when(uEvent4.getReleaseTime()).thenReturn(4d); UserEvent uEvent5 = Mockito.mock(UserEvent.class); Mockito.when(uEvent5.getEventType()).thenReturn(UserEventType.KEY_SEARCH); Mockito.when(uEvent5.getPressTime()).thenReturn(752d); Mockito.when(uEvent5.getReleaseTime()).thenReturn(30000d); List<UserEvent> uEventList = new ArrayList<UserEvent>(); uEventList.add(uEvent1); uEventList.add(uEvent2); uEventList.add(uEvent3); uEventList.add(uEvent4); uEventList.add(uEvent5); CpuActivity cActivity1 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity1.getTimeStamp()).thenReturn(23000d); Mockito.when(cActivity1.getTotalCpuUsage()).thenReturn(5000d); CpuActivity cActivity2 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity2.getTimeStamp()).thenReturn(24000d); Mockito.when(cActivity2.getTotalCpuUsage()).thenReturn(6000d); CpuActivity cActivity3 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity3.getTimeStamp()).thenReturn(25000d); Mockito.when(cActivity3.getTotalCpuUsage()).thenReturn(6000d); List<CpuActivity> cpuActivityList = new ArrayList<CpuActivity>(); cpuActivityList.add(cActivity1); cpuActivityList.add(cActivity2); cpuActivityList.add(cActivity3); Session aSession = Mockito.mock(Session.class); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(aSession); BurstCollectionAnalysisData bcaData = aBurstCollectionAnalysis.analyze(packetsList, profile, packetSizeToCountMap, rrcstaterangelist, uEventList, cpuActivityList, sessionList); if (bcaData != null) { assertEquals(3, bcaData.getBurstAnalysisInfo().size()); assertEquals(3, bcaData.getBurstCollection().size()); assertEquals(0, bcaData.getLongBurstCount()); assertEquals(0, (int) bcaData.getTotalEnergy()); } }
@Test public void analyze3Test() { InetAddress iAdr = Mockito.mock(InetAddress.class); InetAddress iAdr1 = Mockito.mock(InetAddress.class); Mockito.when(iAdr.getAddress()).thenReturn(new byte[] { 89, 10, 1, 1 }); Mockito.when(iAdr1.getAddress()).thenReturn(new byte[] { 72, 12, 13, 1 }); Set<InetAddress> inetSet = new HashSet<InetAddress>(); inetSet.add(iAdr); inetSet.add(iAdr1); DomainNameSystem dns = Mockito.mock(DomainNameSystem.class); Mockito.when(dns.getIpAddresses()).thenReturn(inetSet); Mockito.when(dns.getDomainName()).thenReturn("www.att.com"); UDPPacket udpPacket = Mockito.mock(UDPPacket.class); Mockito.when(udpPacket.isDNSPacket()).thenReturn(true); Mockito.when(udpPacket.getDns()).thenReturn(dns); Mockito.when(udpPacket.getSourcePort()).thenReturn(83); Mockito.when(udpPacket.getDestinationPort()).thenReturn(84); Mockito.when(udpPacket.getDestinationIPAddress()).thenReturn(iAdr); PacketInfo packetInfo1 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo1.getPacket()).thenReturn(udpPacket); Mockito.when(packetInfo1.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo1.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo1.getLen()).thenReturn(10); Mockito.when(packetInfo1.getAppName()).thenReturn("Test1"); Mockito.when(packetInfo1.getTcpFlagString()).thenReturn("TestString"); Mockito.when(packetInfo1.getTimeStamp()).thenReturn(500d); InetAddress iAdr2 = Mockito.mock(InetAddress.class); Mockito.when(iAdr2.getAddress()).thenReturn(new byte[] { 95, 10, 1, 1 }); TCPPacket tcpPacket = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket.getSourcePort()).thenReturn(81); Mockito.when(tcpPacket.getDestinationPort()).thenReturn(82); Mockito.when(tcpPacket.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket.isSYN()).thenReturn(true); Mockito.when(tcpPacket.isFIN()).thenReturn(true); Mockito.when(tcpPacket.isRST()).thenReturn(true); Mockito.when(tcpPacket.getTimeStamp()).thenReturn(1000d); PacketInfo packetInfo2 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo2.getPacket()).thenReturn(tcpPacket); Mockito.when(packetInfo2.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(packetInfo2.getTcpInfo()).thenReturn(TcpInfo.TCP_ESTABLISH); Mockito.when(packetInfo2.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo2.getLen()).thenReturn(15); Mockito.when(packetInfo2.getAppName()).thenReturn("Test2"); Mockito.when(packetInfo2.getTcpFlagString()).thenReturn("Test2String"); Mockito.when(packetInfo2.getTimeStamp()).thenReturn(10d); TCPPacket tcpPacket2 = Mockito.mock(TCPPacket.class); Mockito.when(tcpPacket2.getSourcePort()).thenReturn(95); Mockito.when(tcpPacket2.getDestinationPort()).thenReturn(99); Mockito.when(tcpPacket2.getDestinationIPAddress()).thenReturn(iAdr2); Mockito.when(tcpPacket2.isSYN()).thenReturn(true); Mockito.when(tcpPacket2.isFIN()).thenReturn(true); Mockito.when(tcpPacket2.isRST()).thenReturn(false); Mockito.when(tcpPacket2.getTimeStamp()).thenReturn(50d); PacketInfo packetInfo3 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo3.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo3.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo3.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK_RECOVER); Mockito.when(packetInfo3.getPayloadLen()).thenReturn(0); Mockito.when(packetInfo3.getLen()).thenReturn(20); Mockito.when(packetInfo3.getAppName()).thenReturn("Test3"); Mockito.when(packetInfo3.getTcpFlagString()).thenReturn("Test3String"); Mockito.when(packetInfo3.getTimeStamp()).thenReturn(0d); PacketInfo packetInfo4 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo4.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo4.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo4.getTcpInfo()).thenReturn(TcpInfo.TCP_ACK); Mockito.when(packetInfo4.getTimeStamp()).thenReturn(90d); Mockito.when(packetInfo4.getPayloadLen()).thenReturn(0); PacketInfo packetInfo5 = Mockito.mock(PacketInfo.class); Mockito.when(packetInfo5.getPacket()).thenReturn(tcpPacket2); Mockito.when(packetInfo5.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(packetInfo5.getTcpInfo()).thenReturn(TcpInfo.TCP_DATA_RECOVER); Mockito.when(packetInfo5.getTimeStamp()).thenReturn(750d); Mockito.when(packetInfo5.getPayloadLen()).thenReturn(0); List<PacketInfo> packetsList = new ArrayList<PacketInfo>(); packetsList.add(packetInfo1); packetsList.add(packetInfo2); packetsList.add(packetInfo3); packetsList.add(packetInfo4); packetsList.add(packetInfo5); ProfileLTE profile = Mockito.mock(ProfileLTE.class); Mockito.when(profile.getBurstTh()).thenReturn(50d); Mockito.when(profile.getLongBurstTh()).thenReturn(40.0d); Mockito.when(profile.getLargeBurstDuration()).thenReturn(150d); Mockito.when(profile.getLargeBurstSize()).thenReturn(50); Mockito.when(profile.getProfileType()).thenReturn(ProfileType.LTE); Mockito.when(profile.getBurstTh()).thenReturn(25.0d); Mockito.when(profile.getCarrier()).thenReturn("ATT"); Mockito.when(profile.getCloseSpacedBurstThreshold()).thenReturn(45d); Mockito.when(profile.getDrxLongPingPeriod()).thenReturn(50.0d); Mockito.when(profile.getDrxLongPingPower()).thenReturn(75d); Mockito.when(profile.getDrxLongTime()).thenReturn(75d); Mockito.when(profile.getDevice()).thenReturn("lg"); Mockito.when(profile.getDrxShortPingPeriod()).thenReturn(100d); Mockito.when(profile.getDrxShortPingPower()).thenReturn(200d); Mockito.when(profile.getDrxShortTime()).thenReturn(50d); Mockito.when(profile.getLargeBurstDuration()).thenReturn(500d); Mockito.when(profile.getLargeBurstSize()).thenReturn(1000); Mockito.when(profile.getLongBurstTh()).thenReturn(250d); Map<Integer, Integer> packetSizeToCountMap = new HashMap<Integer, Integer>(); packetSizeToCountMap.put(1001, 10); packetSizeToCountMap.put(2002, 20); packetSizeToCountMap.put(3003, 30); RrcStateRange rrcStateRange1 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange1.getBeginTime()).thenReturn(500d); Mockito.when(rrcStateRange1.getEndTime()).thenReturn(590d); Mockito.when(rrcStateRange1.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange2 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange2.getBeginTime()).thenReturn(8.30d); Mockito.when(rrcStateRange2.getEndTime()).thenReturn(12.30d); Mockito.when(rrcStateRange2.getState()).thenReturn(RRCState.PROMO_FACH_DCH); RrcStateRange rrcStateRange3 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange3.getBeginTime()).thenReturn(0.0d); Mockito.when(rrcStateRange3.getEndTime()).thenReturn(-2.0d); Mockito.when(rrcStateRange3.getState()).thenReturn(RRCState.TAIL_DCH); RrcStateRange rrcStateRange4 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange4.getBeginTime()).thenReturn(25d); Mockito.when(rrcStateRange4.getEndTime()).thenReturn(75d); Mockito.when(rrcStateRange4.getState()).thenReturn(RRCState.WIFI_TAIL); RrcStateRange rrcStateRange5 = Mockito.mock(RrcStateRange.class); Mockito.when(rrcStateRange5.getBeginTime()).thenReturn(105d); Mockito.when(rrcStateRange5.getEndTime()).thenReturn(95d); Mockito.when(rrcStateRange5.getState()).thenReturn(RRCState.PROMO_IDLE_DCH); List<RrcStateRange> rrcstaterangelist = new ArrayList<RrcStateRange>(); rrcstaterangelist.add(rrcStateRange1); rrcstaterangelist.add(rrcStateRange2); rrcstaterangelist.add(rrcStateRange3); rrcstaterangelist.add(rrcStateRange4); rrcstaterangelist.add(rrcStateRange5); UserEvent uEvent1 = Mockito.mock(UserEvent.class); Mockito.when(uEvent1.getEventType()).thenReturn(UserEventType.SCREEN_LANDSCAPE); Mockito.when(uEvent1.getPressTime()).thenReturn(503d); Mockito.when(uEvent1.getReleaseTime()).thenReturn(6d); UserEvent uEvent2 = Mockito.mock(UserEvent.class); Mockito.when(uEvent2.getEventType()).thenReturn(UserEventType.SCREEN_PORTRAIT); Mockito.when(uEvent2.getPressTime()).thenReturn(14d); Mockito.when(uEvent2.getReleaseTime()).thenReturn(2000d); UserEvent uEvent3 = Mockito.mock(UserEvent.class); Mockito.when(uEvent3.getEventType()).thenReturn(UserEventType.KEY_RED); Mockito.when(uEvent3.getPressTime()).thenReturn(497d); Mockito.when(uEvent3.getReleaseTime()).thenReturn(499d); UserEvent uEvent4 = Mockito.mock(UserEvent.class); Mockito.when(uEvent4.getEventType()).thenReturn(UserEventType.EVENT_UNKNOWN); Mockito.when(uEvent4.getPressTime()).thenReturn(25d); Mockito.when(uEvent4.getReleaseTime()).thenReturn(4d); UserEvent uEvent5 = Mockito.mock(UserEvent.class); Mockito.when(uEvent5.getEventType()).thenReturn(UserEventType.KEY_SEARCH); Mockito.when(uEvent5.getPressTime()).thenReturn(752d); Mockito.when(uEvent5.getReleaseTime()).thenReturn(30000d); List<UserEvent> uEventList = new ArrayList<UserEvent>(); uEventList.add(uEvent1); uEventList.add(uEvent2); uEventList.add(uEvent3); uEventList.add(uEvent4); uEventList.add(uEvent5); CpuActivity cActivity1 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity1.getTimeStamp()).thenReturn(23000d); Mockito.when(cActivity1.getTotalCpuUsage()).thenReturn(5000d); CpuActivity cActivity2 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity2.getTimeStamp()).thenReturn(24000d); Mockito.when(cActivity2.getTotalCpuUsage()).thenReturn(6000d); CpuActivity cActivity3 = Mockito.mock(CpuActivity.class); Mockito.when(cActivity3.getTimeStamp()).thenReturn(25000d); Mockito.when(cActivity3.getTotalCpuUsage()).thenReturn(6000d); List<CpuActivity> cpuActivityList = new ArrayList<CpuActivity>(); cpuActivityList.add(cActivity1); cpuActivityList.add(cActivity2); cpuActivityList.add(cActivity3); Session aSession = Mockito.mock(Session.class); List<Session> sessionList = new ArrayList<Session>(); sessionList.add(aSession); BurstCollectionAnalysisData bcaData = aBurstCollectionAnalysis.analyze(packetsList, profile, packetSizeToCountMap, rrcstaterangelist, uEventList, cpuActivityList, sessionList); if (bcaData != null) { assertEquals(3, bcaData.getBurstAnalysisInfo().size()); assertEquals(3, bcaData.getBurstCollection().size()); assertEquals(0, bcaData.getLongBurstCount()); assertEquals(0, (int) bcaData.getTotalEnergy()); } }
|
RrcStateMachineFactoryImpl implements IRrcStateMachineFactory { @Override public AbstractRrcStateMachine create(List<PacketInfo> packetlist, Profile profile, double packetDuration, double traceDuration, double totalBytes, TimeRange timerange) { List<RrcStateRange> staterangelist = staterange.create(packetlist, profile, traceDuration); if(timerange != null){ staterangelist = this.getRRCStatesForTheTimeRange(staterangelist, timerange.getBeginTime(), timerange.getEndTime()); } AbstractRrcStateMachine data = null; if(profile.getProfileType() == ProfileType.T3G){ data = run3GRRcStatistics(staterangelist, (Profile3G)profile, totalBytes, packetDuration, traceDuration); }else if(profile.getProfileType() == ProfileType.LTE){ data = runLTERRcStatistics(staterangelist, (ProfileLTE)profile, packetlist, totalBytes, packetDuration, traceDuration); }else if(profile.getProfileType() == ProfileType.WIFI){ data = runWiFiRRcStatistics(staterangelist, (ProfileWiFi)profile, totalBytes, packetDuration, traceDuration); } if(data != null){ data.setStaterangelist(staterangelist); } return data; } @Override AbstractRrcStateMachine create(List<PacketInfo> packetlist,
Profile profile, double packetDuration, double traceDuration, double totalBytes,
TimeRange timerange); }
|
@Test public void create_TimeRangeIsNotNull() { ProfileWiFi profile01 = mock(ProfileWiFi.class); when(profile01.getProfileType()).thenReturn(ProfileType.WIFI); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); TimeRange timeRange = mock(TimeRange.class); when(timeRange.getBeginTime()).thenReturn((double) date.getTime() - 3000.0); when(timeRange.getEndTime()).thenReturn((double) date.getTime() + 1000.0); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange rrc01 = mock(RrcStateRange.class); RrcStateRange rrc02 = mock(RrcStateRange.class); RrcStateRange rrc03 = mock(RrcStateRange.class); when(rrc01.getBeginTime()).thenReturn((double) date.getTime() - 3000.0); when(rrc01.getEndTime()).thenReturn((double) date.getTime() - 2000.0); when(rrc02.getBeginTime()).thenReturn((double) date.getTime() - 1000.0); when(rrc02.getEndTime()).thenReturn((double) date.getTime()); when(rrc03.getBeginTime()).thenReturn((double) date.getTime() + 1000.0); when(rrc03.getEndTime()).thenReturn((double) date.getTime() + 2000.0); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(2.0); when(rrc01.getState()).thenReturn(RRCState.TAIL_FACH); when(rrc02.getState()).thenReturn(RRCState.TAIL_FACH); when(rrc03.getState()).thenReturn(RRCState.TAIL_FACH); staterangelist.add(rrc01); staterangelist.add(rrc02); staterangelist.add(rrc03); when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); AbstractRrcStateMachine rrcStateMachinewifi = machineFactoryimpl.create(packetlist1, profile01, packetDuration, traceDuration, 0.0, timeRange); assertEquals(0.0, rrcStateMachinewifi.getJoulesPerKilobyte(), 0.0); }
@Test public void create_WIFIStateIsWIFI_ACTIVE() { ProfileWiFi profile02 = mock(ProfileWiFi.class); when(profile02.getProfileType()).thenReturn(ProfileType.WIFI); List<PacketInfo> packetlist2 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange rrc01 = mock(RrcStateRange.class); when(rrc01.getBeginTime()).thenReturn((double) date.getTime()); when(rrc01.getEndTime()).thenReturn(date.getTime() + 2000.0); when(profilefactory.energyWiFi(any(double.class), any(double.class), any(RRCState.class), any(ProfileWiFi.class))).thenReturn(2.0); when(rrc01.getState()).thenReturn(RRCState.WIFI_ACTIVE); staterangelist.add(rrc01); when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineWiFi rrcStateMachineWifi = (RrcStateMachineWiFi) machineFactoryimpl.create(packetlist2, profile02, packetDuration, traceDuration, totalBytes, null); assertEquals(20.0, rrcStateMachineWifi.getJoulesPerKilobyte(), 0.0); assertEquals(1000.0, rrcStateMachineWifi.getPacketsDuration(), 0.0); assertEquals(2.0, rrcStateMachineWifi.getTotalRRCEnergy(), 0.0); assertEquals(2000.0, rrcStateMachineWifi.getTraceDuration(), 0.0); }
@Test public void create_WIFIStateIsWIFI_TAIL() { ProfileWiFi profile17 = mock(ProfileWiFi.class); when(profile17.getProfileType()).thenReturn(ProfileType.WIFI); when(profilefactory.energyWiFi(any(double.class), any(double.class), any(RRCState.class), any(ProfileWiFi.class))).thenReturn(100.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.WIFI_TAIL); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 1000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineWiFi rrcStateMachineWifi = (RrcStateMachineWiFi) machineFactoryimpl.create(packetlist1, profile17, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50, rrcStateMachineWifi.getJoulesPerKilobyte(), 0.0); assertEquals(500, rrcStateMachineWifi.getWifiTailEnergy(), 0.0); assertEquals(5000, rrcStateMachineWifi.getWifiTailTime(), 0.0); }
@Test public void create_WIFIStateIsWIFI_IDLE() { ProfileWiFi profile18 = mock(ProfileWiFi.class); when(profile18.getProfileType()).thenReturn(ProfileType.WIFI); when(profilefactory.energyWiFi(any(double.class), any(double.class), any(RRCState.class), any(ProfileWiFi.class))).thenReturn(100.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.WIFI_IDLE); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 1000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineWiFi rrcStateMachineWifi = (RrcStateMachineWiFi) machineFactoryimpl.create(packetlist1, profile18, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50, rrcStateMachineWifi.getJoulesPerKilobyte(), 0.0); assertEquals(5000, rrcStateMachineWifi.getWifiIdleTime(), 0.0); assertEquals(500, rrcStateMachineWifi.getWifiIdleEnergy(), 0.0); }
@Test public void create_LTEStateIsLTE_IDLE() { ProfileLTE profile03 = mock(ProfileLTE.class); when(profile03.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(100.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_IDLE); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 1000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile03, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(500, rrcStateMachineLTE.getTotalRRCEnergy(), 0.0); assertEquals(5000, rrcStateMachineLTE.getLteIdleTime(), 0.0); }
@Test public void create_LTEStateIsLTE_PROMOTION() { ProfileLTE profile04 = mock(ProfileLTE.class); when(profile04.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(5.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_PROMOTION); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 2000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile04, packetDuration, traceDuration, totalBytes * 1000, null); assertEquals(0.25, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(25, rrcStateMachineLTE.getLteIdleToCRPromotionEnergy(), 0.0); assertEquals(30000, rrcStateMachineLTE.getLteIdleToCRPromotionTime(), 0.0); }
@Test public void create_LTEStateIsLTE_CONTINUOUS() { ProfileLTE profile05 = mock(ProfileLTE.class); when(profile05.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(4.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_CONTINUOUS); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 1000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile05, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(2, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(20, rrcStateMachineLTE.getLteCrEnergy(), 0.0); assertEquals(5000, rrcStateMachineLTE.getLteCrTime(), 0.0); }
@Test public void create_LTEStateIsLTE_CR_TAIL() { ProfileLTE profile06 = mock(ProfileLTE.class); when(profile06.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(5.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_CR_TAIL); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 1000); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 1000.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile06, packetDuration, traceDuration, totalBytes * 200, null); assertEquals(1.25, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(5000, rrcStateMachineLTE.getLteCrTailTime(), 0.0); assertEquals(25, rrcStateMachineLTE.getLteCrTailEnergy(), 0.0); }
@Test public void create_LTEStateIsLTE_DRX_SHORT() { ProfileLTE profile07 = mock(ProfileLTE.class); when(profile07.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(6.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_DRX_SHORT); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile07, packetDuration, traceDuration, totalBytes * 125, null); assertEquals(2.4, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachineLTE.getLteDrxShortTime(), 0.0); assertEquals(30, rrcStateMachineLTE.getLteDrxShortEnergy(), 0.0); }
@Test public void create_LTEStateIsLTE_DRX_LONG() { ProfileLTE profile08 = mock(ProfileLTE.class); when(profile08.getProfileType()).thenReturn(ProfileType.LTE); when(profilefactory.energyLTE(any(double.class), any(double.class), any(RRCState.class), any(ProfileLTE.class), any(ArrayList.class))).thenReturn(6.0); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.LTE_DRX_LONG); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile08, packetDuration, traceDuration, totalBytes * 125, null); assertEquals(2.4, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachineLTE.getLteDrxLongTime(), 0.0); assertEquals(30, rrcStateMachineLTE.getLteDrxLongEnergy(), 0.0); }
@Test public void create_LTEStateRrcStateRangeListIsEmpty() { ProfileLTE profile09 = mock(ProfileLTE.class); when(profile09.getProfileType()).thenReturn(ProfileType.LTE); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachineLTE rrcStateMachineLTE = (RrcStateMachineLTE) machineFactoryimpl.create(packetlist1, profile09, packetDuration, traceDuration, 0 * totalBytes, null); assertEquals(0.0, rrcStateMachineLTE.getJoulesPerKilobyte(), 0.0); assertEquals(1000, rrcStateMachineLTE.getPacketsDuration(), 0.0); assertEquals(2000, rrcStateMachineLTE.getTraceDuration(), 0.0); }
@Test public void create_T3GStateIsSTATE_IDLE() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile10 = mock(Profile3G.class); when(profile10.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.STATE_IDLE); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile10, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachine3G.getIdleTime(), 0.0); assertEquals(500, rrcStateMachine3G.getIdleEnergy(), 0.0); }
@Test public void create_T3GStateIsSTATE_DCH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile11 = mock(Profile3G.class); when(profile11.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.STATE_DCH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile11, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachine3G.getDchTime(), 0.0); assertEquals(500, rrcStateMachine3G.getDchEnergy(), 0.0); }
@Test public void create_T3GStateIsTAIL_DCH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile11 = mock(Profile3G.class); when(profile11.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.TAIL_DCH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile11, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachine3G.getDchTailTime(), 0.0); assertEquals(500, rrcStateMachine3G.getDchTailEnergy(), 0.0); }
@Test public void create_T3GStateIsSTATE_FACH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile12 = mock(Profile3G.class); when(profile12.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.STATE_FACH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile12, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachine3G.getFachTime(), 0.0); assertEquals(500, rrcStateMachine3G.getFachEnergy(), 0.0); }
@Test public void create_T3GStateIsTAIL_FACH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile13 = mock(Profile3G.class); when(profile13.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.TAIL_FACH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile13, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(2500, rrcStateMachine3G.getFachTailTime(), 0.0); assertEquals(500, rrcStateMachine3G.getFachTailEnergy(), 0.0); }
@Test public void create_T3GStateIsPROMO_IDLE_DCH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile14 = mock(Profile3G.class); when(profile14.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.PROMO_IDLE_DCH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile14, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(5, rrcStateMachine3G.getIdleToDch(), 0.0); assertEquals(2500, rrcStateMachine3G.getIdleToDchTime(), 0.0); assertEquals(500, rrcStateMachine3G.getIdleToDchEnergy(), 0.0); }
@Test public void create_T3GStateIsPROMO_FACH_DCH() { List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); when(profilefactory.energy3G(any(double.class), any(double.class), any(RRCState.class), any(Profile3G.class))) .thenReturn(100.0); Profile3G profile15 = mock(Profile3G.class); when(profile15.getProfileType()).thenReturn(ProfileType.T3G); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); RrcStateRange[] rrcStateRangeArray = new RrcStateRange[5]; for (int i = 0; i < 5; i++) { rrcStateRangeArray[i] = mock(RrcStateRange.class); when(rrcStateRangeArray[i].getState()).thenReturn(RRCState.PROMO_FACH_DCH); when(rrcStateRangeArray[i].getBeginTime()).thenReturn((double) date.getTime() + 2 * i * 500); when(rrcStateRangeArray[i].getEndTime()).thenReturn((double) date.getTime() + (2 * i + 1) * 500.0); } for (int i = 0; i < 5; i++) { staterangelist.add(rrcStateRangeArray[i]); } when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile15, packetDuration, traceDuration, totalBytes * 100, null); assertEquals(50.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(5, rrcStateMachine3G.getFachToDch(), 0.0); assertEquals(2500, rrcStateMachine3G.getFachToDchTime(), 0.0); assertEquals(500, rrcStateMachine3G.getFachToDchEnergy(), 0.0); }
@Test public void create_3GStateRrcStateRangeListIsEmpty() { Profile3G profile16 = mock(Profile3G.class); when(profile16.getProfileType()).thenReturn(ProfileType.T3G); List<PacketInfo> packetlist1 = new ArrayList<PacketInfo>(); List<RrcStateRange> staterangelist = new ArrayList<RrcStateRange>(); when(staterange.create(any(ArrayList.class), any(Profile.class), any(double.class))).thenReturn(staterangelist); RrcStateMachine3G rrcStateMachine3G = (RrcStateMachine3G) machineFactoryimpl.create(packetlist1, profile16, packetDuration, traceDuration, 0 * totalBytes, null); assertEquals(0.0, rrcStateMachine3G.getJoulesPerKilobyte(), 0.0); assertEquals(1000, rrcStateMachine3G.getPacketsDuration(), 0.0); assertEquals(2000, rrcStateMachine3G.getTraceDuration(), 0.0); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public Profile create(ProfileType typeParm, Properties prop) { Profile prof = null; ProfileType type = typeParm == null ? ProfileType.LTE : typeParm; switch(type){ case LTE: prof = createLTE(prop); break; case T3G: prof = create3G(prop); break; case WIFI: prof = createWiFi(prop); break; default: return null; } return prof; } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void create_profileTypeIsLTE(){ Properties property01 = Mockito.mock(Properties.class); Mockito.when(property01.getProperty(Profile.CARRIER)).thenReturn("AT&T"); Mockito.when(property01.getProperty(Profile.DEVICE)).thenReturn("Captivate - ad study"); ProfileLTE profileTest = (ProfileLTE) profilefactory.create(ProfileType.LTE, property01); assertEquals(0.26,profileTest.getPromotionTime(),0.0); }
@Test public void create_profileTypeIsWifi(){ Properties property01 = Mockito.mock(Properties.class); ProfileWiFi profileTest = (ProfileWiFi)profilefactory.create(ProfileType.WIFI, property01); assertEquals(0.25,profileTest.getWifiTailTime(),0.0); }
@Test public void create_profileTypeIs3G(){ Properties property01 = Mockito.mock(Properties.class); Profile3G profileTest = (Profile3G)profilefactory.create(ProfileType.T3G, property01); assertEquals(5,profileTest.getDchFachTimer(),0.0); }
|
RequestResponseBuilderImpl implements IRequestResponseBuilder { public List<HttpRequestResponseInfo> createRequestResponseInfo(Session session) throws IOException { Double sslNegotiationDuration = null; double contentDownloadDuration = 0; double requestDuration = 0; double timeToFirstByte = 0; result = new ArrayList<HttpRequestResponseInfo>(); this.session = session; extractHttpRequestResponseInfo(PacketDirection.UPLINK); extractHttpRequestResponseInfo(PacketDirection.DOWNLINK); Collections.sort(result); result.trimToSize(); if(!session.isUdpOnly() && !result.isEmpty()){ Double dns = null; if (session.getDnsRequestPacket() != null && session.getDnsResponsePacket() != null) { dns = session.getDnsRequestPacket().getTimeStamp(); } Double synTime = null; for (PacketInfo pinfo : session.getPackets()) { if (pinfo.getPacket() instanceof TCPPacket) { TCPPacket tcp = (TCPPacket) pinfo.getPacket(); if (tcp.isSYN()) { synTime = pinfo.getTimeStamp(); break; } } } Double sslNegTime = null; PacketInfo handshake = session.getLastSslHandshakePacket(); if (handshake != null) { sslNegTime = handshake.getTimeStamp(); } List<HttpRequestResponseInfo> reqs = new ArrayList<HttpRequestResponseInfo>(result.size()); for (HttpRequestResponseInfo rrinfo : result) { if (rrinfo.getDirection() == HttpDirection.REQUEST) { reqs.add(rrinfo); } else if (rrinfo.getDirection() == HttpDirection.RESPONSE && !reqs.isEmpty()) { rrinfo.setAssocReqResp(reqs.remove(0)); rrinfo.getAssocReqResp().setAssocReqResp(rrinfo); } } for (HttpRequestResponseInfo rrinfo : result) { if (rrinfo.getDirection() != HttpDirection.REQUEST || rrinfo.getAssocReqResp() == null || rrinfo.getFirstDataPacket() == null){ continue; } double startTime = -1; double firstReqPacket = rrinfo.getFirstDataPacket().getTimeStamp(); PacketInfo lastPkt = rrinfo.getLastDataPacket(); double lastReqPacket = lastPkt != null ? lastPkt.getTimeStamp() : -1; HttpRequestResponseInfo resp = rrinfo.getAssocReqResp(); if (resp == null || resp.getFirstDataPacket() == null || resp.getLastDataPacket() == null) { continue; } double firstRespPacket = resp.getFirstDataPacket().getTimeStamp(); double lastRespPacket = resp.getLastDataPacket().getTimeStamp(); Double dnsDuration = null; if (dns != null) { startTime = dns.doubleValue(); if (synTime != null) { dnsDuration = synTime.doubleValue() - dns.doubleValue(); } else { dnsDuration = firstReqPacket - dns.doubleValue(); } dns = null; } Double initConnDuration = null; if (synTime != null) { initConnDuration = firstReqPacket - synTime; if (startTime < 0.0) { startTime = synTime.doubleValue(); } synTime = null; } if (startTime < 0.0) { startTime = firstReqPacket; } if (sslNegTime != null && lastRespPacket >= sslNegTime) { sslNegotiationDuration = sslNegTime - firstReqPacket; contentDownloadDuration = lastRespPacket - sslNegTime; } else { if (firstRespPacket >= lastReqPacket && lastReqPacket != -1) { contentDownloadDuration = lastRespPacket - firstRespPacket; requestDuration = lastReqPacket - firstReqPacket; timeToFirstByte = firstRespPacket - lastReqPacket; } else { contentDownloadDuration = lastRespPacket - firstReqPacket; } } RequestResponseTimeline reqRespTimeline = new RequestResponseTimeline(startTime, dnsDuration, initConnDuration, sslNegotiationDuration, requestDuration, timeToFirstByte, contentDownloadDuration); rrinfo.setWaterfallInfos(reqRespTimeline); rrinfo.getWaterfallInfos().setLastRespPacketTime(lastRespPacket); } } return Collections.unmodifiableList(result); } RequestResponseBuilderImpl(); @Autowired void setByteArrayLineReader(IByteArrayLineReader reader); List<HttpRequestResponseInfo> createRequestResponseInfo(Session session); List<HttpRequestResponseInfo> getResult(); void extractHttpRequestResponseInfo(PacketDirection direction); }
|
@Test public void testSessionChunked() throws IOException { List<PacketInfo> packetList = null; packetList = getPacketListChunked(); InetAddress localIP = null; InetAddress remoteIP = null; int remotePort = 0; int localPort = 0; String key = ""; try { localIP = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, (byte) 1, (byte) 10 }); remoteIP = InetAddress.getByAddress(new byte[] { (byte) 157, (byte) 166, (byte) 239, 38 }); remotePort = 80; localPort = 48449; key = localIP.getHostAddress() + " " + localPort + " " + remotePort + " " + remoteIP.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } Session session = new Session(localIP, remoteIP, remotePort, localPort, key); session.setRemoteHostName("the.remote.host"); session.setPackets(packetList); Packet packet = packetList.get(3).getPacket(); session.setPacketOffsetsDl(dlPacketOffsets); session.setPacketOffsetsUl(ulPacketOffsets); List<HttpRequestResponseInfo> info = rrBuilder.createRequestResponseInfo(session); assertTrue(info.size() == 1); assertTrue(info.get(0).getAllHeaders().equals(" Server: nginx Date: Thu, 11 Dec 2014 00:56:39 GMT Content-Type: application/javascript Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding Last-Modified: Sat, 06 Dec 2014 01:19:23 GMT Cache-Control: max-age=10, public Content-Encoding: gzip")); }
@Test public void testSession1() throws IOException{ List<PacketInfo> packetList = null; packetList = getPacketList1(); InetAddress localIP = null; InetAddress remoteIP = null; int remotePort = 0; int localPort = 0; String key = ""; try { localIP = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 1, 10 }); remoteIP = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 1, 1 }); remotePort = 1234; localPort = 4321; key = localIP.getHostAddress() + " " + localPort + " " + remotePort + " " + remoteIP.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } Session session = new Session(localIP, remoteIP, remotePort, localPort, key); session.setRemoteHostName("the.remote.host"); session.setPackets(packetList); byte[] storageUl = packetList.get(0).getPacket().getData(); session.setStorageUl(storageUl); byte[] storageDl = packetList.get(2).getPacket().getData(); session.setStorageDl(storageDl); SortedMap<Integer, PacketInfo> dlPacketOffsets = new TreeMap<Integer, PacketInfo>(); SortedMap<Integer, PacketInfo> ulPacketOffsets = new TreeMap<Integer, PacketInfo>(); session.setPacketOffsetsDl(dlPacketOffsets); session.setPacketOffsetsUl(ulPacketOffsets); List<HttpRequestResponseInfo> result = rrBuilder.createRequestResponseInfo(session); assertTrue(result.size() == 2); assertTrue(result.get(0).getAllHeaders().equals(" Date: Tue, 04 Jun 2013 20:23:44 GMT P3P: policyref=\"http: }
@Test public void testSession2() throws IOException{ List<PacketInfo> packetList = null; packetList = getPacketList2(); InetAddress localIP = null; InetAddress remoteIP = null; int remotePort = 0; int localPort = 0; String key = ""; try { localIP = InetAddress.getByAddress(new byte[] { 24, 16, (byte) 97, (byte) 107 }); remoteIP = InetAddress.getByAddress(new byte[] { 24, 16, (byte) 97, (byte) 108 }); remotePort = 8080; localPort = 4321; key = localIP.getHostAddress() + " " + localPort + " " + remotePort + " " + remoteIP.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } Session session = new Session(localIP, remoteIP, remotePort, localPort, key); session.setRemoteHostName("the.remote.host"); session.setPackets(packetList); Packet packet = packetList.get(3).getPacket(); byte[] storageUl = Arrays.copyOfRange(packet.getData(), packet.getDataOffset(), packet.getLen()); session.setStorageUl(storageUl); packet = packetList.get(6).getPacket(); byte[] storageDl = Arrays.copyOfRange(packet.getData(), packet.getDataOffset(), packet.getLen()); session.setStorageDl(storageDl); SortedMap<Integer, PacketInfo> ulPacketOffsets = new TreeMap<Integer, PacketInfo>(); SortedMap<Integer, PacketInfo> dlPacketOffsets = new TreeMap<Integer, PacketInfo>(); ulPacketOffsets.put(0, packetList.get(3)); dlPacketOffsets.put(0, packetList.get(6)); session.setPacketOffsetsDl(dlPacketOffsets); session.setPacketOffsetsUl(ulPacketOffsets); List<HttpRequestResponseInfo> info = null; info = rrBuilder.createRequestResponseInfo(session); assertTrue(info.size() == 2); assertTrue(info.get(0).getAllHeaders().equals(" Accept: application/json Content-type: text/plain Content-Length: 229 Host: 24.16.97.108:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)")); }
|
RequestResponseBuilderImpl implements IRequestResponseBuilder { public void extractHttpRequestResponseInfo(PacketDirection direction) throws IOException { SortedMap<Integer, PacketInfo> packetOffsets; switch (direction) { case DOWNLINK: storageReader.init(session.getStorageDl()); packetOffsets = session.getPacketOffsetsDl(); break; case UPLINK: storageReader.init(session.getStorageUl()); packetOffsets = session.getPacketOffsetsUl(); break; default: throw new IllegalArgumentException("Direction argument invalid"); } HttpRequestResponseInfo rrInfo = findNextRequestResponse(direction, packetOffsets); String line; while ((line = storageReader.readLine()) != null && rrInfo != null) { if (line.length() == 0) { if (rrInfo.getContentLength() > 0) { rrInfo.setContentOffsetLength(new TreeMap<Integer, Integer>()); rrInfo.getContentOffsetLength().put(storageReader.getIndex(), rrInfo.getContentLength()); storageReader.skipContent(rrInfo.getContentLength()); } else if (rrInfo.isChunked()) { rrInfo.setContentOffsetLength(new TreeMap<Integer, Integer>()); while (true) { line = storageReader.readLine(); if (line != null) { String[] str = line.split(";"); int size = 0; try { String trim = str[0].trim(); size = Integer.parseInt(trim, 16); } catch (NumberFormatException e) { LOGGER.warn("Unexpected begin of the chunk format : " + line); } if (size > 0) { rrInfo.getContentOffsetLength().put(storageReader.getIndex(), size); rrInfo.setContentLength(rrInfo.getContentLength() + size); storageReader.skipForward(size); line = storageReader.readLine(); if (line != null && line.length() > 0) { LOGGER.warn("Unexpected end of chunk: " + line); } } else { rrInfo.setChunkModeFinished(true); line = storageReader.readLine(); if (line != null && line.length() > 0) { LOGGER.warn("Unexpected end of chunked data: " + line); } break; } } else { break; } } } mapPackets(packetOffsets, rrInfo.getRrStart(), storageReader.getIndex() - 1, direction, rrInfo); rrInfo.setRawSize(storageReader.getIndex() - rrInfo.getRrStart()); if (rrInfo.getObjUri() != null && !rrInfo.getObjUri().isAbsolute()) { try { int port = Integer.valueOf(rrInfo.getPort()).equals(wellKnownPorts.get(rrInfo.getScheme())) ? -1 : rrInfo.getPort(); rrInfo.setObjUri(new URI(rrInfo.getScheme().toLowerCase(), null, rrInfo.getHostName(), port, rrInfo.getObjUri().getPath(), rrInfo.getObjUri().getQuery(), rrInfo.getObjUri().getFragment())); } catch (URISyntaxException e) { LOGGER.info("Unexpected exception creating URI for request: " + e.getMessage() + ". Scheme=" + rrInfo.getScheme().toLowerCase() + ",Host name=" + rrInfo.getHostName() + ",Path=" + rrInfo.getObjUri().getPath() + ",Fragment=" + rrInfo.getObjUri().getFragment()); } } result.add(rrInfo); if (rrInfo.getDirection() == null) { LOGGER.warn("Request/response object has unknown direction"); } rrInfo = findNextRequestResponse(direction, packetOffsets); } else { parseHeaderLine.parseHeaderLine(line, rrInfo); } } } RequestResponseBuilderImpl(); @Autowired void setByteArrayLineReader(IByteArrayLineReader reader); List<HttpRequestResponseInfo> createRequestResponseInfo(Session session); List<HttpRequestResponseInfo> getResult(); void extractHttpRequestResponseInfo(PacketDirection direction); }
|
@Test public void testExtractHttpRequestResponseInfo() throws IOException{ Session session = Mockito.mock(Session.class); PacketInfo pi1 = Mockito.mock(PacketInfo.class); Mockito.when(pi1.getTimeStamp()).thenReturn(1000.0d); Mockito.when(pi1.getTcpFlagString()).thenReturn("F"); TCPPacket mTcpPacket = Mockito.mock(TCPPacket.class); PacketInfo pi2 = Mockito.mock(PacketInfo.class); Mockito.when(pi2.getPacket()).thenReturn(mTcpPacket); Mockito.when(pi2.getTcpFlagString()).thenReturn(""); Mockito.when(session.isUdpOnly()).thenReturn(false); TreeMap<Integer, PacketInfo> dlPacketOffsets = new TreeMap<Integer, PacketInfo>(); TreeMap<Integer, PacketInfo> ulPacketOffsets = new TreeMap<Integer, PacketInfo>(); dlPacketOffsets.put(14, pi1); ulPacketOffsets.put(14, pi2); List<PacketInfo> packets = new ArrayList<PacketInfo>(); packets.add(pi1); packets.add(pi2); String ulh = "\r\n" + "POST /com.nelsoft.areeba/Services/Login/RequestLoginUser HTTP/1.1" + "\r\n" + "Accept: application/json" + "\r\n" + "Content-type: text/plain" + "\r\n" + "Content-Length: 229" + "\r\n" + "Host: 24.16.97.108:8080" + "\r\n" + "Connection: Keep-Alive" + "\r\n" + "User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)" + "\r\n" + "\r\n" + "" + "\r\n" +"{\"accountID\":0,\"tokenID\":-5,\"userID\":-1,\"status\":\"\",\"serverHashKey\":\"\",\"deviceHash\":\"\",\"userPIN\":\"1234\",\"userName\":\"Barry\",\"deviceIMEI\":\"358239057521132 LGE Model Nexus 5 Version 4.4.2\",\"deviceIMSI\":\" \",\"versionNumber\":\"1.0.0.0\"}" ; Mockito.when(session.getStorageUl()).thenReturn(ulh.getBytes()); Mockito.when(session.getStorageDl()).thenReturn( ("HTTP/1.1 200 OK" + "\r\n" + "Server: Apache-Coyote/1.1" + "\r\n" + "Content-Length: 239" + "\r\n" + "Date: Thu, 22 Jan 2015 01:51:32 GMT" + "\r\n" + "" + "\r\n" +"{\"userName\":\"Barry\",\"userID\":12357,\"userPIN\":\"1234\",\"deviceIMSI\":\" \",\"deviceIMEI\":\"358239057521132 LGE Model Nexus 5 Version 4.4.2\",\"versionNumber\":\"1.0.0.0\",\"deviceHash\":\"\",\"status\":\"ok\",\"tokenID\":539,\"accountID\":4231,\"serverHashKey\":\"\"}" ).getBytes()); Mockito.when(session.getPacketOffsetsDl()).thenReturn(dlPacketOffsets); Mockito.when(session.getPacketOffsetsUl()).thenReturn(ulPacketOffsets); Mockito.when(session.getRemoteHostName()).thenReturn("remoteHostName"); Mockito.when(session.getDnsRequestPacket()).thenReturn(pi1); Mockito.when(session.getDnsResponsePacket()).thenReturn(pi2); Mockito.when(session.getPackets()).thenReturn(packets); Mockito.when(session.getLastSslHandshakePacket()).thenReturn(pi1); rrBuilder.createRequestResponseInfo(session); rrBuilder.extractHttpRequestResponseInfo(PacketDirection.DOWNLINK); List<HttpRequestResponseInfo> bResult = rrBuilder.getResult(); assertTrue(bResult.size() == 4); assertTrue(bResult.get(0).getAllHeaders().equals(" Accept: application/json Content-type: text/plain Content-Length: 229 Host: 24.16.97.108:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)")); Mockito.when(session.getStorageUl()).thenReturn( ("GET /cnn/dam/assets/141210153919-panono-tease-avatar.jpg HTTP/1.1\r\n" + "Host: i2.cdn.turner.com\r\n" + "Connection: keep-alive\r\n" + "Accept: image/webp,*/*;q=0.8\r\n" + "User-Agent: Mozilla/5.0 (Linux; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.59 Mobile Safari/537.36\r\n" + "Referer: http: + "Accept-Encoding: gzip, deflate, sdch\r\n" + "Accept-Language: en-US,en;q=0.8\r\n" + "\r\n").getBytes()); Mockito.when(session.getStorageDl()).thenReturn( ("HTTP/1.1 200 OK\r\n" + "Server: Apache-Coyote/1.1\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: 8443\r\n" + "Cache-Control: max-age=5014\r\n" + "Expires: Thu, 11 Dec 2014 02:20:13 GMT\r\n" + "Date: Thu, 11 Dec 2014 00:56:39 GMT\r\n" + "Connection: keep-alive\r\n").getBytes()); rrBuilder.extractHttpRequestResponseInfo(PacketDirection.DOWNLINK); List<HttpRequestResponseInfo> result = rrBuilder.getResult(); assertTrue(result.size() == 4); assertTrue(result.get(0).getAllHeaders().equals(" Accept: application/json Content-type: text/plain Content-Length: 229 Host: 24.16.97.108:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)")); rrBuilder.extractHttpRequestResponseInfo(PacketDirection.UPLINK); result = rrBuilder.getResult(); assertTrue(result.size() == 5); assertTrue(result.get(0).getAllHeaders().equals(" Accept: application/json Content-type: text/plain Content-Length: 229 Host: 24.16.97.108:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)")); }
|
ThroughputCalculatorImpl implements IThroughputCalculator { public List<Throughput> calculateThroughput(double startTime, double endTime, double window, List<PacketInfo> packets) { List<Throughput> result = new ArrayList<Throughput>(); List<PacketInfo> split = new ArrayList<>(); if(window < 0.00001 || endTime-startTime < 0.00001) { return Collections.emptyList(); } double splitStart = startTime; double splitEnd = startTime + window; for (PacketInfo packet : packets) { double stamp = packet.getTimeStamp(); if (stamp < startTime) { continue; } else if (stamp >= endTime) { result.add(getThroughput(splitStart, splitEnd, split)); break; } else if (stamp >= splitEnd) { while (stamp >= splitEnd) { result.add(getThroughput(splitStart, splitEnd, split)); splitStart = splitEnd; splitEnd = splitStart + window; split = new ArrayList<>(); } split.add(packet); } else if (stamp >= splitStart) { split.add(packet); } } do { result.add(getThroughput(splitStart, splitEnd, split)); splitStart = splitEnd; splitEnd = splitStart + window; split = new ArrayList<>(); } while (endTime >= splitStart); return result; } List<Throughput> calculateThroughput(double startTime, double endTime, double window,
List<PacketInfo> packets); }
|
@Test public void calculateThroughput_PacketListIsNull(){ List<PacketInfo> packets = new ArrayList<PacketInfo>(); List<Throughput> testResult = new ArrayList<Throughput>(); testResult = throughputCalculator.calculateThroughput(0.0, 0.0, 0.0, packets); assertEquals(true,testResult.isEmpty()); }
@Test public void calculateThroughput_a(){ Date date = new Date(); List<Throughput> testResult = new ArrayList<Throughput>(); List<PacketInfo> packets = new ArrayList<PacketInfo>(); PacketInfo pktInfo01 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo01.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo01.getTimeStamp()).thenReturn(date.getTime()+5000.0); packets.add(pktInfo01); PacketInfo pktInfo02 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo02.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(pktInfo02.getTimeStamp()).thenReturn(date.getTime()+8000.0); packets.add(pktInfo02); PacketInfo pktInfo03 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo03.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo03.getTimeStamp()).thenReturn(date.getTime()+22000.0); packets.add(pktInfo03); PacketInfo pktInfo04 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo04.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo04.getTimeStamp()).thenReturn(date.getTime()+23000.0); packets.add(pktInfo04); PacketInfo pktInfo05 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo05.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo05.getTimeStamp()).thenReturn(date.getTime()+70000.0); packets.add(pktInfo05); PacketInfo pktInfo06 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo06.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo06.getTimeStamp()).thenReturn(date.getTime()+72000.0); packets.add(pktInfo06); testResult = throughputCalculator.calculateThroughput(date.getTime()+0.0, date.getTime()+100000.0, 15000.0, packets); assertEquals(7,testResult.size()); }
@Test public void calculateThroughput_b(){ Date date = new Date(); List<Throughput> testResult = new ArrayList<Throughput>(); List<PacketInfo> packets = new ArrayList<PacketInfo>(); PacketInfo pktInfo01 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo01.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo01.getTimeStamp()).thenReturn(date.getTime()+20000.0); packets.add(pktInfo01); PacketInfo pktInfo02 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo02.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(pktInfo02.getTimeStamp()).thenReturn(date.getTime()+20400.0); packets.add(pktInfo02); PacketInfo pktInfo03 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo03.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(pktInfo03.getTimeStamp()).thenReturn(date.getTime()+20500.0); packets.add(pktInfo03); PacketInfo pktInfo04 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo04.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(pktInfo04.getTimeStamp()).thenReturn(date.getTime()+41000.0); packets.add(pktInfo04); PacketInfo pktInfo05 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo05.getDir()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(pktInfo05.getTimeStamp()).thenReturn(date.getTime()+71000.0); packets.add(pktInfo05); PacketInfo pktInfo06 = Mockito.mock(PacketInfo.class); Mockito.when(pktInfo06.getDir()).thenReturn(PacketDirection.UPLINK); Mockito.when(pktInfo06.getTimeStamp()).thenReturn(date.getTime()+72000.0); packets.add(pktInfo06); testResult = throughputCalculator.calculateThroughput(date.getTime()+0.0, date.getTime()+73000.0, 60000.0, packets); assertEquals(2,testResult.size()); }
|
HttpRequestResponseHelperImpl implements IHttpRequestResponseHelper { public byte[] getContent(HttpRequestResponseInfo request, Session session) throws Exception { LOG.debug("getContent(Req, Session) :" + request.toString()); String contentEncoding = request.getContentEncoding(); byte[] payload; ByteArrayOutputStream output; boolean logFlag = false; if(request.getAssocReqResp()==null) { logFlag = true; } payload = request.getPayloadData().toByteArray(); if (request.isChunked()) { storageReader.init(payload); String line; output = new ByteArrayOutputStream(); while (true) { line = storageReader.readLine(); if (line != null) { String[] str = line.split(";"); int size = 0; try { String trim = str[0].trim(); size = Integer.parseInt(trim, 16); } catch (NumberFormatException e) { LOG.warn("Unexpected begin of the chunk format : " + line); } if (size > 0) { output.write( Arrays.copyOfRange(payload, storageReader.getIndex(), storageReader.getIndex() + size)); storageReader.skipForward(size); line = storageReader.readLine(); if (line != null && line.length() > 0) { LOG.warn("Unexpected end of chunk: " + line); } } else { request.setChunkModeFinished(true); line = storageReader.readLine(); if (line != null && line.length() > 0) { LOG.warn("Unexpected end of chunked data: " + line); } break; } } else { break; } } if (request.isChunkModeFinished()) { payload = output.toByteArray(); } else { throw new Exception(String.format("Unexpected Chunk End at request time: %.3f, request.getAssocReqResp() is %s The content may be corrupted.", request.getTimeStamp(), logFlag?"N/A":request.getAssocReqResp().getObjNameWithoutParams())); } } else if (payload.length < request.getContentLength()) { request.setExtractable(false); int percentage = payload.length / request.getContentLength() * 100; throw new Exception(String.format("PayloadException At request time: %.3f, request.getAssocReqResp() is %s . The content may be corrupted. Buffer exceeded: only %d percent arrived", request.getTimeStamp(), logFlag?"N/A":request.getAssocReqResp().getObjNameWithoutParams(), percentage)); } if ("gzip".equals(contentEncoding) && payload != null) { GZIPInputStream gzip = null; output = new ByteArrayOutputStream(); gzip = new GZIPInputStream(new ByteArrayInputStream(payload)); try { byte[] buffer = new byte[2048]; int len; while ((len = gzip.read(buffer)) >= 0) { output.write(buffer, 0, len); } gzip.close(); } catch (IOException ioe) { LOG.error("Error Extracting Content from Request"); throw new Exception(String.format("Zip Extract Exception At request time: %.3f, request.getAssocReqResp() is %s. The content may be corrupted.", request.getTimeStamp(), logFlag?"N/A":request.getAssocReqResp())); } } else { return payload; } if (output.size() > 0) { return output.toByteArray(); } else { request.setExtractable(false); return new byte[0]; } } @Autowired void setByteArrayLineReader(IByteArrayLineReader reader); boolean isCss(String contentType); boolean isHtml(String contentType); boolean isJSON(String contentType); boolean isJavaScript(String contentType); String getContentString(HttpRequestResponseInfo req, Session session); byte[] getContent(HttpRequestResponseInfo request, Session session); boolean isSameContent(HttpRequestResponseInfo left, HttpRequestResponseInfo right, Session session, Session sessionRight); long getActualByteCount(HttpRequestResponseInfo item, Session session); }
|
@Test public void getContent() { Session session = null; session = mock(Session.class); HttpRequestResponseInfo req = null; req = mock(HttpRequestResponseInfo.class); String stringData = "this was compressed"; byte[] data = stringData.getBytes(); byte[] gzipped_data = null; try { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(data.length / 2); GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput); gzipOutput.write(data); gzipOutput.close(); gzipped_data = byteOutput.toByteArray(); } catch (IOException e1) { e1.printStackTrace(); } SortedMap<Integer, Integer> contentOffsetTreeMap = new TreeMap<Integer, Integer>(); contentOffsetTreeMap.put(0, gzipped_data == null ? 0 : gzipped_data.length); Mockito.when(req.getContentEncoding()).thenReturn("gzip"); Mockito.when(req.getContentOffsetLength()).thenReturn(contentOffsetTreeMap); Mockito.when(req.getPacketDirection()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(session.getStorageDl()).thenReturn(gzipped_data); Mockito.when(session.getStorageUl()).thenReturn(gzipped_data); try { assertEquals(stringData, httpRequestResponseHelper.getContentString(req, session)); Mockito.when(session.getStorageDl()).thenReturn(data); } catch (Exception e) { assertEquals(null, e.getMessage()); } assertNotNull(gzipped_data); gzipped_data[20] = 42; Mockito.when(session.getStorageDl()).thenReturn(gzipped_data); Mockito.when(session.getStorageUl()).thenReturn(gzipped_data); try { String thisWasFromCorruptedZip = httpRequestResponseHelper.getContentString(req, session); assertEquals("this was bwmpressed", thisWasFromCorruptedZip); } catch (Exception e) { } }
|
HttpRequestResponseHelperImpl implements IHttpRequestResponseHelper { public boolean isSameContent(HttpRequestResponseInfo left, HttpRequestResponseInfo right, Session session, Session sessionRight) { if (left.getContentLength() > 0 && left.getContentLength() != right.getContentLength()) { return false; } boolean yes = true; long leftcount = getActualByteCount(left, session); long rightcount = getActualByteCount(right, sessionRight); if (leftcount == rightcount) { if (leftcount == 0) { return true; } byte[] bufferLeft = left.getPayloadData().toByteArray(); byte[] bufferRight = right.getPayloadData().toByteArray(); Iterator<Map.Entry<Integer, Integer>> itleft = left.getContentOffsetLength().entrySet().iterator(); Iterator<Map.Entry<Integer, Integer>> itright = right.getContentOffsetLength().entrySet().iterator(); int indexLeft = 0; int stopLeft = 0; int indexRight = 0; int stopRight = 0; if (itleft.hasNext() && itright.hasNext()) { Map.Entry<Integer, Integer> entryLeft = itleft.next(); Map.Entry<Integer, Integer> entryRight = itright.next(); indexLeft = entryLeft.getKey(); stopLeft = indexLeft + entryLeft.getValue(); indexRight = entryRight.getKey(); stopRight = entryRight.getValue(); do { if (bufferLeft[indexLeft] != bufferRight[indexRight]) { return false; } ++indexLeft; ++indexRight; if (indexLeft >= bufferLeft.length || indexRight >= bufferRight.length) { break; } if (indexLeft >= stopLeft) { if (itleft.hasNext()) { entryLeft = itleft.next(); indexLeft = entryLeft.getKey(); stopLeft = indexLeft + entryLeft.getValue(); } else { break; } } if (indexRight >= stopRight) { if (itright.hasNext()) { entryRight = itright.next(); indexRight = entryRight.getKey(); stopRight = entryRight.getValue(); } else { break; } } } while (true); } yes = true; } else { yes = false; } return yes; } @Autowired void setByteArrayLineReader(IByteArrayLineReader reader); boolean isCss(String contentType); boolean isHtml(String contentType); boolean isJSON(String contentType); boolean isJavaScript(String contentType); String getContentString(HttpRequestResponseInfo req, Session session); byte[] getContent(HttpRequestResponseInfo request, Session session); boolean isSameContent(HttpRequestResponseInfo left, HttpRequestResponseInfo right, Session session, Session sessionRight); long getActualByteCount(HttpRequestResponseInfo item, Session session); }
|
@Ignore @Test public void isSameContent_resultIsTrue() { HttpRequestResponseInfo reqLeft = new HttpRequestResponseInfo(); HttpRequestResponseInfo reqRight = new HttpRequestResponseInfo(); SortedMap<Integer, Integer> testMap = new TreeMap<Integer, Integer>(); testMap.put(1, 1); testMap.put(2, 2); reqLeft.setContentLength(1); reqLeft.setContentOffsetLength(testMap); reqLeft.setPacketDirection(PacketDirection.DOWNLINK); reqRight.setContentLength(1); reqRight.setContentOffsetLength(testMap); reqRight.setPacketDirection(PacketDirection.DOWNLINK); Session sessionRight = new Session(null, null, 0, 0, ""); sessionRight.setStorageDl(storage); Session sessionLeft = new Session(null, null, 0, 0, ""); sessionLeft.setStorageDl(storage); boolean testResult = httpRequestResponseHelper.isSameContent(reqLeft, reqRight, sessionLeft, sessionRight); assertTrue(testResult); }
@Test public void isSameContent_resultIsFalse() { HttpRequestResponseInfo reqLeft = new HttpRequestResponseInfo(); HttpRequestResponseInfo reqRight = new HttpRequestResponseInfo(); SortedMap<Integer, Integer> testMap = new TreeMap<Integer, Integer>(); testMap.put(1, 1); testMap.put(2, 2); reqLeft.setContentLength(1); reqLeft.setContentOffsetLength(testMap); reqLeft.setPacketDirection(PacketDirection.DOWNLINK); reqRight.setContentLength(1); reqRight.setContentOffsetLength(testMap); reqRight.setPacketDirection(PacketDirection.UPLINK); Session sessionRight = new Session(null, null, 0, 0, ""); sessionRight.setStorageDl(storage); Session sessionLeft = new Session(null, null, 0, 0, ""); sessionLeft.setStorageDl(storage); httpRequestResponseHelper.isSameContent(reqLeft, reqRight, sessionLeft, sessionRight); boolean testResult = httpRequestResponseHelper.isSameContent(reqLeft, reqRight, sessionLeft, sessionRight); assertFalse(testResult); }
@Ignore @Test public void isSameContent() { String left = "<h1>The droids were just here 12 seconds ago.</h1>\n\n\n<h1>lastAccess = Thu Feb 20 10:45:01 PST 2014</h1>\n\n\n<h3>---------------------------------------</h3>\n<h3>lastEventSent = 12</h3>\n<h3>lastRemoteAddr = 166.137.185.60</h3>\n<h3>lastRemoteHost = 166.137.185.60</h3>\n<h3>lastRemoteUser = null</h3>"; String right = "<h1>The droids were just here 13 seconds ago.</h1>\n\n\n<h1>lastAccess = Thu Feb 20 10:45:00 PST 2014</h1>\n\n\n<h3>---------------------------------------</h3>\n<h3>lastEventSent = 12</h3>\n<h3>lastRemoteAddr = 166.137.185.60</h3>\n<h3>lastRemoteHost = 166.137.185.60</h3>\n<h3>lastRemoteUser = null</h3>"; Session session = mock(Session.class); HttpRequestResponseInfo reqLeft = mock(HttpRequestResponseInfo.class); HttpRequestResponseInfo reqRight = mock(HttpRequestResponseInfo.class); SortedMap<Integer, Integer> contentOffsetTreeMap = new TreeMap<Integer, Integer>(); contentOffsetTreeMap.put(1, 2); byte[] dataLeft = left.getBytes(); byte[] dataRight = right.getBytes(); Mockito.when(reqLeft.getContentOffsetLength()).thenReturn(contentOffsetTreeMap); Mockito.when(reqLeft.getPacketDirection()).thenReturn(PacketDirection.DOWNLINK); Mockito.when(reqRight.getContentOffsetLength()).thenReturn(contentOffsetTreeMap); Mockito.when(reqRight.getPacketDirection()).thenReturn(PacketDirection.UPLINK); Mockito.when(session.getStorageDl()).thenReturn(dataLeft); Mockito.when(session.getStorageUl()).thenReturn(dataRight); Mockito.when(session.getStorageUl()).thenReturn(dataLeft); }
|
TraceManager { public State download(String remoteSelectedTrace, String saveTo) { String path = repository.get(remoteSelectedTrace, saveTo); if(path == null) { return State.FAILURE; } String folderName = "RemoteTrace"; if(remoteSelectedTrace!=null && remoteSelectedTrace.length()>4) { folderName = remoteSelectedTrace.substring(0,remoteSelectedTrace.length()-4); } unZip(path,folderName); removeZip(path); return State.COMPLETE; } TraceManager(); TraceManager(Repository repository); State upload(String trace); String compress(String trace); State download(String remoteSelectedTrace, String saveTo); void unZip(String zipFile, String saveTo); void addListener(Listener l); void removeListener(Listener l); void setRepository(Repository repository); }
|
@Test public void testDownload() { manager.download("", ""); }
|
TraceManager { public State upload(String trace) { clean(trace); String zipFile = compress(trace); File file = new File(zipFile); TransferState state = repository.put(file); if(state ==TransferState.Completed) { removeZip(zipFile); return State.COMPLETE; }else { return State.FAILURE; } } TraceManager(); TraceManager(Repository repository); State upload(String trace); String compress(String trace); State download(String remoteSelectedTrace, String saveTo); void unZip(String zipFile, String saveTo); void addListener(Listener l); void removeListener(Listener l); void setRepository(Repository repository); }
|
@Test public void testUpload() { manager.upload(""); }
|
UserPreferencesFactory { public static UserPreferencesFactory getInstance() { return instance; } private UserPreferencesFactory(); static UserPreferencesFactory getInstance(); UserPreferences create(); }
|
@Test public void testGetInstance() { UserPreferencesFactory factory = UserPreferencesFactory.getInstance(); assertNotNull(factory); assertEquals(UserPreferencesFactory.class, factory.getClass()); }
|
UserPreferencesFactory { public UserPreferences create() { return UserPreferences.getInstance(); } private UserPreferencesFactory(); static UserPreferencesFactory getInstance(); UserPreferences create(); }
|
@Test public void testCreate() { UserPreferencesFactory factory = UserPreferencesFactory.getInstance(); UserPreferences userPrefs = factory.create(); assertNotNull(userPrefs); assertEquals(UserPreferences.class, userPrefs.getClass()); }
|
UserPreferences { static UserPreferences getInstance() { return instance; } private UserPreferences(); File getLastTraceDirectory(); void setLastTraceDirectory(File tdPath); String getLastProfile(); String getLastProfile(ProfileType profileType); void setLastProfile(Profile profile); File getLastProfileDirectory(); void setLastProfileDirectory(File profilePath); File getLastExportDirectory(); void setLastExportDirectory(File exportDir); List<PrivateDataInfo> getPrivateData(); void setPrivateData(List<PrivateDataInfo> privateData); }
|
@Test public void testGetInstance() { UserPreferences userPref = UserPreferences.getInstance(); assertNotNull(userPref); assertEquals(UserPreferences.class, userPref.getClass()); }
|
UserPreferences { public String getLastProfile() { return prefHandler.getPref(PROFILE); } private UserPreferences(); File getLastTraceDirectory(); void setLastTraceDirectory(File tdPath); String getLastProfile(); String getLastProfile(ProfileType profileType); void setLastProfile(Profile profile); File getLastProfileDirectory(); void setLastProfileDirectory(File profilePath); File getLastExportDirectory(); void setLastExportDirectory(File exportDir); List<PrivateDataInfo> getPrivateData(); void setPrivateData(List<PrivateDataInfo> privateData); }
|
@Test public void testGetLastProfile() { UserPreferences userPrefs = MockUserPreferencesFactory.getInstance().create(); IPreferenceHandler mockPrefHandler = userPrefs.getPreferenceHandler(); String expectedProfile = "testProfile"; mockPrefHandler.setPref(PROFILE, expectedProfile); String actualProfile = userPrefs.getLastProfile(); assertEquals(expectedProfile, actualProfile); }
|
UserPreferences { public File getLastProfileDirectory() { String path = prefHandler.getPref(PROFILE_PATH); return path != null ? new File(path) : null; } private UserPreferences(); File getLastTraceDirectory(); void setLastTraceDirectory(File tdPath); String getLastProfile(); String getLastProfile(ProfileType profileType); void setLastProfile(Profile profile); File getLastProfileDirectory(); void setLastProfileDirectory(File profilePath); File getLastExportDirectory(); void setLastExportDirectory(File exportDir); List<PrivateDataInfo> getPrivateData(); void setPrivateData(List<PrivateDataInfo> privateData); }
|
@Test public void testGetLastProfileDirectory() { UserPreferences userPrefs = MockUserPreferencesFactory.getInstance().create(); IPreferenceHandler mockPrefHandler = userPrefs.getPreferenceHandler(); String testProfilePath = VALID_DIR; mockPrefHandler.setPref(PROFILE_PATH, testProfilePath); File actualProfileDir = userPrefs.getLastProfileDirectory(); assertEquals(new File(VALID_DIR), actualProfileDir); }
|
UserPreferences { public void setPrivateData(List<PrivateDataInfo> privateData) { if (privateData == null) { throw new IllegalArgumentException("Private data must be non-null."); } StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < privateData.size(); i++) { strBuilder.append(privateData.get(i).getCategory()); strBuilder.append(TraceDataConst.PrivateData.COLUMN_DELIMITER); strBuilder.append(privateData.get(i).getType()); strBuilder.append(TraceDataConst.PrivateData.COLUMN_DELIMITER); strBuilder.append(privateData.get(i).getValue()); strBuilder.append(TraceDataConst.PrivateData.COLUMN_DELIMITER); strBuilder.append(privateData.get(i).isSelected()? TraceDataConst.PrivateData.YES_SELECTED : TraceDataConst.PrivateData.NO_SELECTED); if (i < privateData.size() - 1) { strBuilder.append(TraceDataConst.PrivateData.ITEM_DELIMITER); } } prefHandler.setPref(PRIVATE_DATA, strBuilder.toString()); } private UserPreferences(); File getLastTraceDirectory(); void setLastTraceDirectory(File tdPath); String getLastProfile(); String getLastProfile(ProfileType profileType); void setLastProfile(Profile profile); File getLastProfileDirectory(); void setLastProfileDirectory(File profilePath); File getLastExportDirectory(); void setLastExportDirectory(File exportDir); List<PrivateDataInfo> getPrivateData(); void setPrivateData(List<PrivateDataInfo> privateData); }
|
@Test public void testSetPrivateData() { PrivateDataInfo phoneNumber = new PrivateDataInfo(); phoneNumber.setCategory("KEYWORD"); phoneNumber.setType("Phone Number"); phoneNumber.setValue("123-123-1234"); phoneNumber.setSelected(true); PrivateDataInfo somePattern = new PrivateDataInfo(); somePattern.setCategory("PATTERN"); somePattern.setType("PATTERNNAME"); somePattern.setValue("PATTERNVALUE"); somePattern.setSelected(false); List<PrivateDataInfo> privateData = new ArrayList<PrivateDataInfo>(); privateData.add(phoneNumber); privateData.add(somePattern); UserPreferences userPrefs = MockUserPreferencesFactory.getInstance().create(); userPrefs.setPrivateData(privateData); IPreferenceHandler mockPrefHandler = userPrefs.getPreferenceHandler(); String actualPrivateDataPersisted = mockPrefHandler.getPref(PRIVATE_DATA); String expectedPrivateDataPersisted = "KEYWORD,Phone Number,123-123-1234,Y;PATTERN,PATTERNNAME,PATTERNVALUE,N"; assertEquals(expectedPrivateDataPersisted, actualPrivateDataPersisted); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public double energy3G(double time1, double time2, RRCState state, Profile3G prof) { double deltaTime = time2 - time1; switch (state) { case STATE_DCH: case TAIL_DCH: return deltaTime * prof.getPowerDch(); case STATE_FACH: case TAIL_FACH: return deltaTime * prof.getPowerFach(); case STATE_IDLE: return deltaTime * prof.getPowerIdle(); case PROMO_IDLE_DCH: return deltaTime * prof.getPowerIdleDch(); case PROMO_FACH_DCH: return deltaTime * prof.getPowerFachDch(); default: assert (true); } return 0.0f; } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void energy3G_RRCStateIsTAIL_DCH(){ Profile3G profile3g = Mockito.mock(Profile3G.class); Mockito.when(profile3g.getPowerDch()).thenReturn(0.7); double testResult = profilefactory .energy3G(date.getTime()+0.0, date.getTime()+1000.0, RRCState.TAIL_DCH, profile3g); assertEquals(700.0,testResult,0.0); }
@Test public void energy3G_RRCStateIsTAIL_FACH(){ Profile3G profile3g = Mockito.mock(Profile3G.class); Mockito.when(profile3g.getPowerFach()).thenReturn(0.35); double testResult = profilefactory .energy3G(date.getTime()+0.0, date.getTime()+1000.0, RRCState.TAIL_FACH, profile3g); assertEquals(350.0,testResult,0.0); }
@Test public void energy3G_RRCStateIsSTATE_FACH(){ Profile3G profile3g = Mockito.mock(Profile3G.class); double testResult = profilefactory .energy3G(date.getTime()+0.0, date.getTime()+1000.0, RRCState.STATE_FACH, profile3g); assertEquals(0.0f,testResult,0.0); }
@Test public void energy3G_RRCStateIsSTATE_IDLE(){ Profile3G profile3g = Mockito.mock(Profile3G.class); Mockito.when(profile3g.getPowerIdle()).thenReturn(0.2); double testResult = profilefactory .energy3G(date.getTime()+0.0, date.getTime()+1000.0, RRCState.STATE_IDLE, profile3g); assertEquals(200.0,testResult,0.0); }
@Test public void energy3G_RRCStateIsPROMO_FACH_DCH(){ Profile3G profile3g = Mockito.mock(Profile3G.class); Mockito.when(profile3g.getPowerFachDch()).thenReturn(0.3); double testResult = profilefactory .energy3G(date.getTime()+0.0, date.getTime()+1000.0, RRCState.PROMO_FACH_DCH, profile3g); assertEquals(300.0,testResult,0.0); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public void save3G(String filepath, Profile3G prof) throws IOException { OutputStream output = filemanager.getFileOutputStream(filepath); this.save3G(output, prof); } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void save3G_Profile3g() throws IOException{ OutputStream output = Mockito.mock(OutputStream.class); Profile3G profile3g = Mockito.mock(Profile3G.class); when(profile3g.getCarrier()).thenReturn("AT&T"); when(profile3g.getDevice()).thenReturn("Captivate - ad study"); when(profile3g.getProfileType()).thenReturn(ProfileType.T3G); when(profile3g.getUserInputTh()).thenReturn(1.0); when(profile3g.getPowerGpsActive()).thenReturn(1.0); when(profile3g.getPowerGpsStandby()).thenReturn(0.5); when(profile3g.getPowerCameraOn()).thenReturn(0.3); when(profile3g.getPowerBluetoothActive()).thenReturn(1.0); when(profile3g.getPowerBluetoothStandby()).thenReturn(0.5); when(profile3g.getPowerScreenOn()).thenReturn(0.3); when(profile3g.getBurstTh()).thenReturn(1.5); when(profile3g.getLongBurstTh()).thenReturn(5.0); when(profile3g.getPeriodMinCycle()).thenReturn(10.0); when(profile3g.getPeriodCycleTol()).thenReturn(1.0); when(profile3g.getLargeBurstDuration()).thenReturn(5.0); when(profile3g.getLargeBurstSize()).thenReturn(100000); when(profile3g.getCloseSpacedBurstThreshold()).thenReturn(10.0); when(profile3g.getThroughputWindow()).thenReturn(0.5); profilefactory.save3G(output, profile3g); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public void saveLTE(String filepath, ProfileLTE prof) throws IOException{ OutputStream output = filemanager.getFileOutputStream(filepath); this.saveLTE(output, prof); } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void saveLTE_ProfileLTE() throws IOException{ OutputStream output = Mockito.mock(OutputStream.class); ProfileLTE profileLte = Mockito.mock(ProfileLTE.class); when(profileLte.getCarrier()).thenReturn("AT&T"); when(profileLte.getDevice()).thenReturn("Captivate - ad study"); when(profileLte.getProfileType()).thenReturn(ProfileType.LTE); when(profileLte.getUserInputTh()).thenReturn(1.0); when(profileLte.getPowerGpsActive()).thenReturn(1.0); when(profileLte.getPowerGpsStandby()).thenReturn(0.5); when(profileLte.getPowerCameraOn()).thenReturn(0.3); when(profileLte.getPowerBluetoothActive()).thenReturn(1.0); when(profileLte.getPowerBluetoothStandby()).thenReturn(0.5); when(profileLte.getPowerScreenOn()).thenReturn(0.3); when(profileLte.getBurstTh()).thenReturn(1.5); when(profileLte.getLongBurstTh()).thenReturn(5.0); when(profileLte.getPeriodMinCycle()).thenReturn(10.0); when(profileLte.getPeriodCycleTol()).thenReturn(1.0); when(profileLte.getLargeBurstDuration()).thenReturn(5.0); when(profileLte.getLargeBurstSize()).thenReturn(100000); when(profileLte.getCloseSpacedBurstThreshold()).thenReturn(10.0); when(profileLte.getThroughputWindow()).thenReturn(0.5); profilefactory.saveLTE(output, profileLte); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public void saveWiFi(String filepath, ProfileWiFi prof) throws IOException{ OutputStream output = filemanager.getFileOutputStream(filepath); this.saveWiFi(output, prof); } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void saveWiFi_() throws IOException{ OutputStream output = Mockito.mock(OutputStream.class); ProfileWiFi profileWifi = Mockito.mock(ProfileWiFi.class); when(profileWifi.getCarrier()).thenReturn("AT&T"); when(profileWifi.getDevice()).thenReturn("Captivate - ad study"); when(profileWifi.getProfileType()).thenReturn(ProfileType.LTE); when(profileWifi.getUserInputTh()).thenReturn(1.0); when(profileWifi.getPowerGpsActive()).thenReturn(1.0); when(profileWifi.getPowerGpsStandby()).thenReturn(0.5); when(profileWifi.getPowerCameraOn()).thenReturn(0.3); when(profileWifi.getPowerBluetoothActive()).thenReturn(1.0); when(profileWifi.getPowerBluetoothStandby()).thenReturn(0.5); when(profileWifi.getPowerScreenOn()).thenReturn(0.3); when(profileWifi.getBurstTh()).thenReturn(1.5); when(profileWifi.getLongBurstTh()).thenReturn(5.0); when(profileWifi.getPeriodMinCycle()).thenReturn(10.0); when(profileWifi.getPeriodCycleTol()).thenReturn(1.0); when(profileWifi.getLargeBurstDuration()).thenReturn(5.0); when(profileWifi.getLargeBurstSize()).thenReturn(100000); when(profileWifi.getCloseSpacedBurstThreshold()).thenReturn(10.0); when(profileWifi.getThroughputWindow()).thenReturn(0.5); profilefactory.saveWiFi(output, profileWifi); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets) { double deltaTime = time2 - time1; double result = 0.0; switch (state) { case LTE_PROMOTION : return deltaTime * prof.getLtePromotionPower(); case LTE_CR_TAIL: return deltaTime * prof.getLteBeta(); case LTE_CONTINUOUS: for (Throughput throughput : throughputcalculator.calculateThroughput(time1, time2, prof.getThroughputWindow(), packets)) { result += (((prof.getLteAlphaUp() / 1000.0) * throughput.getUploadMbps()) + ((prof.getLteAlphaDown() / 1000.0) * throughput.getDownloadMbps()) + prof.getLteBeta()) * throughput.getSamplePeriod(); } break; case LTE_DRX_SHORT : return (deltaTime / prof.getDrxShortPingPeriod()) * ((prof.getDrxPingTime() * prof.getDrxShortPingPower()) + ((prof.getDrxShortPingPeriod() - prof.getDrxPingTime()) * prof.getLteTailPower())); case LTE_DRX_LONG : return (deltaTime / prof.getDrxLongPingPeriod()) * ((prof.getDrxPingTime() * prof.getDrxLongPingPower()) + ((prof.getDrxLongPingPeriod() - prof.getDrxPingTime()) * prof.getLteTailPower())); case LTE_IDLE : result = ((int) (deltaTime / prof.getIdlePingPeriod())) * ((prof.getIdlePingTime() * prof.getLteIdlePingPower()) + ((prof.getIdlePingPeriod() - prof.getIdlePingTime()) * prof.getLteIdlePower())); double tres = deltaTime % prof.getIdlePingPeriod(); result += tres <= prof.getIdlePingTime() ? tres * prof.getLteIdlePingPower() : ((prof.getIdlePingTime() * prof.getLteIdlePingPower()) + ((tres - prof.getIdlePingTime()) * prof.getLteIdlePingPower())); break; default: break; } return result; } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void energyLTE_RRCStateIsLTE_DRX_SHORT(){ ProfileLTE profileLte01 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte01.getDrxShortPingPeriod()).thenReturn(5.0); when(profileLte01.getDrxShortPingPower()).thenReturn(1.0); when(profileLte01.getLteTailPower()).thenReturn(2.0); when(profileLte01.getDrxPingTime()).thenReturn(1.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+1000.0, RRCState.LTE_DRX_SHORT, profileLte01,packets); assertEquals(1800.0,testResult,0.0); }
@Test public void energyLTE_RRCStateIsLTE_DRX_LONG(){ ProfileLTE profileLte05 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte05.getDrxLongPingPeriod()).thenReturn(5.0); when(profileLte05.getDrxLongPingPower()).thenReturn(1.0); when(profileLte05.getLteTailPower()).thenReturn(2.0); when(profileLte05.getDrxPingTime()).thenReturn(1.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+1000.0, RRCState.LTE_DRX_LONG, profileLte05,packets); assertEquals(1800.0,testResult,0.0); }
@Test public void energyLTE_RRCStateIsLTE_IDLE(){ ProfileLTE profileLte02 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte02.getIdlePingTime()).thenReturn(1.0); when(profileLte02.getLteIdlePingPower()).thenReturn(1.0); when(profileLte02.getIdlePingPeriod()).thenReturn(2.0); when(profileLte02.getLteIdlePower()).thenReturn(1.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+1000.0, RRCState.LTE_IDLE, profileLte02,packets); assertEquals(1000.0,testResult,0.0); }
@Test public void energyLTE_RRCStateIsLTE_IDLE_a(){ ProfileLTE profileLte03 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte03.getIdlePingTime()).thenReturn(1.0); when(profileLte03.getLteIdlePingPower()).thenReturn(1.0); when(profileLte03.getIdlePingPeriod()).thenReturn(9.0); when(profileLte03.getLteIdlePower()).thenReturn(1.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+14750.0, RRCState.LTE_IDLE, profileLte03,packets); assertEquals(14750.0,testResult,0.0); }
@Test public void energyLTE_RRCStateIsLTE_CR_TAIL(){ ProfileLTE profileLte04 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte04.getIdlePingTime()).thenReturn(1.0); when(profileLte04.getLteIdlePingPower()).thenReturn(1.0); when(profileLte04.getIdlePingPeriod()).thenReturn(2.0); when(profileLte04.getLteIdlePower()).thenReturn(1.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+1000.0, RRCState.LTE_CR_TAIL, profileLte04,packets); assertEquals(0.0,testResult,0.0); }
@Test public void energyLTE_RRCStateIsLTE_PROMOTION(){ ProfileLTE profileLte06 = Mockito.mock(ProfileLTE.class); List<PacketInfo> packets = new ArrayList<PacketInfo>(); when(profileLte06.getLtePromotionPower()).thenReturn(3.0); double testResult = profilefactory.energyLTE(date.getTime()+0.0, date.getTime()+1000.0, RRCState.LTE_PROMOTION, profileLte06,packets); assertEquals(3000.0,testResult,0.0); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public String getName() { return "Rooted Android Data Collector"; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testgetName_noError() { String testResult = rootedAndroidCollectorImpl.getName(); assertEquals("Rooted Android Data Collector", testResult); }
|
ProfileFactoryImpl implements IProfileFactory { @Override public double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof) { double deltaTime = time2 - time1; if(state == RRCState.WIFI_ACTIVE || state == RRCState.WIFI_TAIL){ return deltaTime * prof.getWifiActivePower(); }else if(state == RRCState.WIFI_IDLE){ return deltaTime * prof.getWifiIdlePower(); } return 0; } @Override Profile create(ProfileType typeParm, Properties prop); @Override double energy3G(double time1, double time2, RRCState state, Profile3G prof); @Override Profile create3Gdefault(); @Override Profile create3GFromDefaultResourceFile(); @Override Profile create3GFromFilePath(String filepath); @Override Profile create3G(InputStream input); @Override Profile create3G(Properties properties); @Override void save3G(String filepath, Profile3G prof); @Override void save3G(OutputStream output, Profile3G prof); @Override double energyLTE(double time1, double time2, RRCState state, ProfileLTE prof, List<PacketInfo> packets); @Override Profile createLTEdefault(); @Override Profile createLTEFromDefaultResourceFile(); @Override Profile createLTEFromFilePath(String filepath); @Override Profile createLTE(InputStream input); @Override Profile createLTE(Properties properties); @Override void saveLTE(String filepath, ProfileLTE prof); @Override void saveLTE(OutputStream output, ProfileLTE prof); @Override double energyWiFi(double time1, double time2, RRCState state , ProfileWiFi prof); @Override Profile createWiFidefault(); @Override Profile createWiFiFromFilePath(String filepath); @Override Profile createWiFiFromDefaultResourceFile(); @Override Profile createWiFi(InputStream input); @Override Profile createWiFi(Properties properties); @Override void saveWiFi(String filepath, ProfileWiFi prof); @Override void saveWiFi(OutputStream output, ProfileWiFi prof); }
|
@Test public void energyWifi_RRCStateIsWIFI_ACTIVE(){ ProfileWiFi profileWifi = Mockito.mock(ProfileWiFi.class); when(profileWifi.getWifiActivePower()).thenReturn(2.0); double testResult = profilefactory.energyWiFi(date.getTime()+0.0, date.getTime()+1000.0, RRCState.WIFI_ACTIVE, profileWifi); assertEquals(2000.0,testResult,0.0); }
@Test public void energyWifi_RRCStateIsWIFI_IDLE(){ ProfileWiFi profileWifi02 = Mockito.mock(ProfileWiFi.class); when(profileWifi02.getWifiActivePower()).thenReturn(3.0); double testResult = profilefactory.energyWiFi(date.getTime()+0.0, date.getTime()+1000.0, RRCState.WIFI_IDLE, profileWifi02); assertEquals(0.0,testResult,0.0); }
|
NetmonPacketReaderImpl implements IPacketReader, INetmonPacketSubscriber { @Override public void readPacket(String packetfile, IPacketListener listener) throws IOException { if(netmon == null){ netmon = new NetmonAdapter(); netmon.loadNativeLibs(); } LOGGER.info("Creating Netmon Adapter..."); if (listener == null) { LOGGER.error("PacketListener cannot be null"); throw new IllegalArgumentException("PacketListener cannot be null"); } this.packetlistener = listener; int retval = netmon.parseTraceFile(packetfile); switch (retval) { case NETMON_PARSING_SUCCESS: return; case NETMON_TRACE_FILE_LOAD_ERROR: case NETMON_ERROR: default: LOGGER.error("NetMon error code: " + retval); throw new IOException("NetMon error code: " + retval); } } void setNetmon(NetmonAdapter netmon); @Override void readPacket(String packetfile, IPacketListener listener); @Override void receiveNetmonPacket(int datalink, long seconds,
long microSeconds, int len, byte[] data, String appName); static final int NETMON_ERROR; static final int NETMON_TRACE_FILE_LOAD_ERROR; static final int NETMON_PARSING_SUCCESS; }
|
@Test public void readPacket() throws IOException{ reader = (IPacketReader) context.getBean("netmonPacketReader"); netmonreader = (NetmonPacketReaderImpl)reader; netmonreader.setNetmon(netmon); netmonreader.readPacket(file.getAbsolutePath(), listener); byte[] data = new byte[20]; netmonreader.receiveNetmonPacket(12, 1, 1, 1, data, "test"); netmonreader.receiveNetmonPacket(0xf000, 1, 1, 1, data, "test"); }
|
PacketReaderImpl implements IPacketReader, INativePacketSubscriber { public void setAroJpcapLibName(String osname, String osarch) { LOGGER.info("OS: " + osname); LOGGER.info("OS Arch: " + osarch); if (osname != null && osarch != null) { if (osname.contains(windowsOS) && osarch.contains("64")) { aroJpcapLibName = "jpcap64"; aroJpcapLibFileName = aroJpcapLibName + windowsExtn; } else if (osname.contains(windowsOS)) { aroJpcapLibName = "jpcap"; aroJpcapLibFileName = aroJpcapLibName + windowsExtn; } else if (osname.contains(linuxOS) && osarch.contains("amd64")) { aroJpcapLibName = "jpcap64"; aroJpcapLibFileName = "lib" + aroJpcapLibName + unixExtn; } else if (osname.contains(linuxOS) && osarch.contains("i386")) { aroJpcapLibName = "jpcap32"; aroJpcapLibFileName = "lib" + aroJpcapLibName + unixExtn; } else { aroJpcapLibName = "jpcap"; aroJpcapLibFileName = "lib" + aroJpcapLibName + ".jnilib"; } } LOGGER.info("ARO Jpcap DLL lib file name: " + aroJpcapLibFileName); } PacketReaderImpl(); void setAdapter(PCapAdapter adapter); @Override void readPacket(String packetfile, IPacketListener listener); void setVOLibName(); void setAroJpcapLibName(String osname, String osarch); String getAroJpcapLibFileName(); String getAroWebPLibName(); void setAroWebPLib(String osname, String osarch); String getAroWebPLibFileName(); @Override void receive(int datalink, long seconds, long microSeconds, int len, byte[] data); public String windowsOS; public String windowsExtn; public String linuxOS; }
|
@Test public void setAroJpcapLibNameTest() { reader.setAroJpcapLibName("Windows", "64"); String libname = reader.getAroJpcapLibFileName(); assertEquals("jpcap64.dll", libname); reader.setAroJpcapLibName("Windows", "86"); libname = reader.getAroJpcapLibFileName(); assertEquals("jpcap.dll", libname); reader.setAroJpcapLibName("Linux", "amd64"); libname = reader.getAroJpcapLibFileName(); assertEquals("libjpcap64.so", libname); reader.setAroJpcapLibName("Linux", "i386"); libname = reader.getAroJpcapLibFileName(); assertEquals("libjpcap32.so", libname); reader.setAroJpcapLibName("MacOS", "64"); libname = reader.getAroJpcapLibFileName(); assertEquals("libjpcap.jnilib", libname); reader.setAroJpcapLibName(null, null); }
|
PacketReaderImpl implements IPacketReader, INativePacketSubscriber { public void setAroWebPLib(String osname, String osarch) { LOGGER.info("OS: " + osname); LOGGER.info("OS Arch: " + osarch); if (osname != null && osarch != null) { if (osname.contains(windowsOS) && osarch.contains("64")) { aroWebPLibName = "webp-imageio"; aroWebPLibFileName = aroWebPLibName + windowsExtn ; } else if (osname.contains(windowsOS)) { aroWebPLibName = "webp-imageio32"; aroWebPLibFileName = aroWebPLibName + windowsExtn; } else if (osname.contains(linuxOS) && osarch.contains("amd64")) { aroWebPLibName = "libwebp-imageio"; aroWebPLibFileName = aroWebPLibName + unixExtn; } else if (osname.contains(linuxOS) && osarch.contains("i386")) { aroWebPLibName = "libwebp-imageio32"; aroWebPLibFileName = aroWebPLibName + unixExtn; } else { aroWebPLibName = "libwebp-imageio"; aroWebPLibFileName = aroWebPLibName + ".dylib"; } } LOGGER.debug("ARO WebP DLL lib file name: " + aroWebPLibFileName); } PacketReaderImpl(); void setAdapter(PCapAdapter adapter); @Override void readPacket(String packetfile, IPacketListener listener); void setVOLibName(); void setAroJpcapLibName(String osname, String osarch); String getAroJpcapLibFileName(); String getAroWebPLibName(); void setAroWebPLib(String osname, String osarch); String getAroWebPLibFileName(); @Override void receive(int datalink, long seconds, long microSeconds, int len, byte[] data); public String windowsOS; public String windowsExtn; public String linuxOS; }
|
@Test public void setAroWebPLib() { reader.setAroWebPLib("Windows", "64"); String libname = reader.getAroWebPLibFileName(); assertEquals("webp-imageio.dll", libname); reader.setAroWebPLib("Windows", "86"); libname = reader.getAroWebPLibFileName(); assertEquals("webp-imageio32.dll", libname); reader.setAroWebPLib("Linux", "amd64"); libname = reader.getAroWebPLibFileName(); assertEquals("libwebp-imageio.so", libname); reader.setAroWebPLib("Linux", "i386"); libname = reader.getAroWebPLibFileName(); assertEquals("libwebp-imageio32.so", libname); reader.setAroWebPLib("MacOS", "64"); libname = reader.getAroWebPLibFileName(); assertEquals("libwebp-imageio.dylib", libname); reader.setAroWebPLib(null, null); libname = reader.getAroWebPLibFileName(); assertEquals("libwebp-imageio.dylib", libname); }
|
PacketReaderImpl implements IPacketReader, INativePacketSubscriber { @Override public void readPacket(String packetfile, IPacketListener listener) throws IOException { if (aroJpcapLibName == null || aroWebPLibName==null) { setVOLibName(); } currentPacketfile = packetfile; provisionalPcapConversion(packetfile); if (listener == null) { LOGGER.error("PacketListener cannot be null"); throw new IllegalArgumentException("PacketListener cannot be null"); } this.packetlistener = listener; if (adapter == null) { adapter = new PCapAdapter(); adapter.loadAroLib(aroWebPLibFileName, aroWebPLibName); adapter.loadAroLib(aroJpcapLibFileName, aroJpcapLibName); } adapter.setSubscriber(this); String result = adapter.readData(packetfile); if (result != null) { LOGGER.debug("Result from executing all pcap packets: " + result); throw new IOException(result); } LOGGER.debug("Created PCapAdapter"); } PacketReaderImpl(); void setAdapter(PCapAdapter adapter); @Override void readPacket(String packetfile, IPacketListener listener); void setVOLibName(); void setAroJpcapLibName(String osname, String osarch); String getAroJpcapLibFileName(); String getAroWebPLibName(); void setAroWebPLib(String osname, String osarch); String getAroWebPLibFileName(); @Override void receive(int datalink, long seconds, long microSeconds, int len, byte[] data); public String windowsOS; public String windowsExtn; public String linuxOS; }
|
@Test public void readPacket() throws IOException { listener = Mockito.mock(IPacketListener.class); reader.setAdapter(adapter); ReflectionTestUtils.setField(reader, "filemanager", mockFileManager); ReflectionTestUtils.setField(reader, "pcapngHelper", pcapNgHelper); ReflectionTestUtils.setField(reader, "extrunner", extrunner); Mockito.when(extrunner.executeCmd(Mockito.anyString())).thenReturn("mocked shell response"); Mockito.when(pcapNgHelper.isApplePcapng(Mockito.any(File.class))).thenReturn(false); Mockito.when(mockFileManager.createFile(Mockito.anyString(), Mockito.anyString())).thenReturn(backupCap); Mockito.when(mockFileManager.createFile("mypath:test")).thenReturn(tempFile); Mockito.when(mockFileManager.renameFile(Mockito.any(File.class), Mockito.anyString())).thenReturn(true); Mockito.when(file.getAbsolutePath()).thenReturn("mypath:test"); Mockito.when(tempFile.getAbsolutePath()).thenReturn("myPath/test"); Mockito.when(tempFile.getName()).thenReturn("test"); Mockito.when(tempFile.delete()).thenReturn(true); Mockito.when(tempFile.exists()).thenReturn(true); Mockito.when(backupCap.getAbsolutePath()).thenReturn("myPath/test2"); Mockito.when(backupCap.getName()).thenReturn("test2"); Mockito.when(backupCap.delete()).thenReturn(true); Mockito.when(backupCap.exists()).thenReturn(false); reader.readPacket(file.getAbsolutePath(), new IPacketListener() { @Override public void packetArrived(String appName, Packet packet) { tPacket = packet; } }); String nativeLibname = reader.getAroJpcapLibFileName(); byte[] data = new byte[20]; reader.receive(12, 1, 2, 3, data); assertNotEquals(tPacket, null); assertEquals(tPacket.getMicroSeconds(), 2L); assertNotEquals(nativeLibname, null); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public void addVideoImageSubscriber(IVideoImageSubscriber subscriber) { videocapture.addSubscriber(subscriber); } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testaddVideoImageSubscriber_returnIsTrue() { IVideoImageSubscriber mockSubscriber = mock(IVideoImageSubscriber.class); rootedAndroidCollectorImpl.addVideoImageSubscriber(mockSubscriber); }
|
PacketServiceImpl implements IPacketService { @Override public Packet createPacketFromPcap(int datalink, long seconds, long microSeconds, int len, byte[] data, String pcapfile) { short network = 0; int hdrLen = 0; ByteBuffer bytes = ByteBuffer.wrap(data); try { switch (datalink) { case DLT_RAW: network = IPV4; break; case DLT_EN10MB: network = bytes.getShort(12); hdrLen = 14; break; case DLT_LINUX_SLL: network = bytes.getShort(14); hdrLen = 16; break; default: if (pcapfile != null) { try { if (pcapngHelper.isApplePcapng(pcapfile) || pcapngHelper.isNoLinkLayer(pcapfile)) { network = IPV4; hdrLen = 4; } } catch (IOException e) { LOGGER.error(e.getMessage()); } } break; } } catch (IndexOutOfBoundsException e) { LOGGER.error(e.getMessage()); } return createPacket(network, seconds, microSeconds, len, hdrLen, data); } @Override Packet createPacketFromPcap(int datalink, long seconds, long microSeconds, int len, byte[] data, String pcapfile); @Override Packet createPacketFromNetmon(int datalink, long seconds, long microSeconds, int len, byte[] data); @Override Packet createPacket(short network, long seconds, long microSeconds, int len, int datalinkHdrLen, byte[] data); }
|
@Test public void createPacketFromPcapTest(){ ReflectionTestUtils.setField(service, "pcapngHelper", helper); byte[] data = new byte[64]; data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 0; data[4] = 12; data[5] = 15; Packet packet = service.createPacketFromPcap(13, 1, 1, 1, data, "abcde"); assertNotNull(packet); assertEquals(packet.getData()[5], 15); }
|
PacketServiceImpl implements IPacketService { @Override public Packet createPacket(short network, long seconds, long microSeconds, int len, int datalinkHdrLen, byte[] data) { Packet packet = null; ByteBuffer bytes = ByteBuffer.wrap(data); if (network == IPV6 && data.length >= datalinkHdrLen + 40) { byte protocol = bytes.get(datalinkHdrLen + 6); switch (protocol) { case 6: packet = new TCPPacket(seconds, microSeconds, len, datalinkHdrLen, data); break; case 17: packet = createUDPPacket(seconds, microSeconds, len, datalinkHdrLen, data); break; default: packet = new IPPacket(seconds, microSeconds, len, datalinkHdrLen, data); break; } } else if (network == IPV4 && data.length >= datalinkHdrLen + 20) { byte iphlen = (byte) ((bytes.get(datalinkHdrLen) & 0x0f) << 2); if (data.length < datalinkHdrLen + iphlen) { packet = new Packet(seconds, microSeconds, len, datalinkHdrLen, data); } else { byte protocol = bytes.get(datalinkHdrLen + 9); switch (protocol) { case 6: if (data.length >= datalinkHdrLen + iphlen + 20) { packet = new TCPPacket(seconds, microSeconds, len, datalinkHdrLen, data); } else { packet = new Packet(seconds, microSeconds, len, datalinkHdrLen, data); } break; case 17: if (data.length >= datalinkHdrLen + iphlen + 6) { packet = createUDPPacket(seconds, microSeconds, len, datalinkHdrLen, data); } else { packet = new Packet(seconds, microSeconds, len, datalinkHdrLen, data); } break; default: packet = new IPPacket(seconds, microSeconds, len, datalinkHdrLen, data); } } } else { packet = new Packet(seconds, microSeconds, len, datalinkHdrLen, data); } return packet; } @Override Packet createPacketFromPcap(int datalink, long seconds, long microSeconds, int len, byte[] data, String pcapfile); @Override Packet createPacketFromNetmon(int datalink, long seconds, long microSeconds, int len, byte[] data); @Override Packet createPacket(short network, long seconds, long microSeconds, int len, int datalinkHdrLen, byte[] data); }
|
@Test public void createPacketTest(){ service = (PacketServiceImpl) context.getBean(IPacketService.class); ReflectionTestUtils.setField(service, "pcapngHelper", helper); byte[] data = new byte[64]; data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 0; ByteBuffer buffer = ByteBuffer.allocate(2); short network = 0x0800; buffer.putShort(network); buffer.flip(); byte[] netarr = buffer.array(); data[12] = netarr[0]; data[13] = netarr[1]; data[14] = netarr[0]; data[15] = netarr[1]; ByteBuffer datawrap = ByteBuffer.wrap(data); short value = datawrap.getShort(12); assertEquals(network, value); Packet packet = service.createPacketFromPcap(12, 1, 1, 1, data, null); packet = service.createPacketFromPcap(1, 1, 1, 1, data, null); packet = service.createPacketFromPcap(113, 1, 1, 1, data, null); packet = service.createPacketFromPcap(0, 1, 1, 1, data, file.getAbsolutePath()); packet = service.createPacketFromNetmon(0xe000, 1, 1, 1, data); packet = service.createPacketFromNetmon(9, 1, 1, 1, data); packet = service.createPacketFromNetmon(8, 1, 1, 1, data); packet = service.createPacketFromNetmon(1, 1, 1, 1, data); packet = service.createPacketFromNetmon(6, 1, 1, 1, data); data[1] = 0x2; data[2] = 0x8; packet = service.createPacketFromNetmon(6, 1, 1, 1, data); data[6] = 0x6; packet = service.createPacket((short) 0x86DD, 1, 1, 1, 0, data); boolean ok = false; if(packet instanceof TCPPacket){ ok = true; } assertEquals(true, ok); data[6] = 0x11; packet = service.createPacket((short) 0x86DD, 1, 1, 1, 0, data); if(packet instanceof UDPPacket){ ok = true; } assertEquals(true, ok); data[6] = 0x8; packet = service.createPacket((short) 0x86DD, 1, 1, 1, 0, data); data[9] = 0x6; packet = service.createPacket((short) 0x0800, 1, 1, 1, 0, data); data[9] = 0x11; packet = service.createPacket((short) 0x0800, 1, 1, 1, 0, data); data[9] = 0x8; packet = service.createPacket((short) 0x0800, 1, 1, 1, 0, data); assertNotNull(packet); }
|
DomainNameParserImpl implements IDomainNameParser { @Override public DomainNameSystem parseDomainName(UDPPacket packet) { DomainNameSystem domain = new DomainNameSystem(); domain.setPacket(packet); start = packet.getDataOffset(); data = packet.getData(); bytes = ByteBuffer.wrap(data); bytes.position(start); bytes.getShort(); short flags = bytes.getShort(); boolean response = (flags & 0x80) != 0; domain.setResponse(response); short queries = bytes.getShort(); if (queries != 1) { LOGGER.warn("DNS packet with more than one query"); return null; } short answers = bytes.getShort(); bytes.getShort(); bytes.getShort(); String domainName = readDomainName(); short qtype = bytes.getShort(); short qclass = bytes.getShort(); if ((qtype != TYPE_A && qtype != TYPE_AAAA) || qclass != 1) { return null; } domain.setDomainName(domainName); if (response) { Set<InetAddress> ipAddresses = new HashSet<InetAddress>(); String cname = domainName; for (int i = 0; i < answers; ++i) { String domainname = readDomainName(); qtype = bytes.getShort(); qclass = bytes.getShort(); bytes.getInt(); short len = bytes.getShort(); if (!domainname.equals(domainName) && !domainname.equals(cname)) { LOGGER.warn("Unexpected answer domain: " + domainname); bytes.position(bytes.position() + len); continue; } if (qclass != 1) { LOGGER.warn("Unrecognized DNS answer class:" + qclass); bytes.position(bytes.position() + len); continue; } switch (qtype) { case TYPE_A : case TYPE_AAAA : byte[] bdata = new byte[len]; bytes.get(bdata, 0, len); try { ipAddresses.add(InetAddress.getByAddress(bdata)); } catch (UnknownHostException e) { LOGGER.warn("Unexpected exception reading IP address from DNS response"); } break; case TYPE_CNAME : cname = readDomainName(); break; default : LOGGER.warn("Unhandled DNS answer type:" + qtype); bytes.position(bytes.position() + len); } } domain.setCname(cname); domain.setIpAddresses(ipAddresses); } return domain; } @Override DomainNameSystem parseDomainName(UDPPacket packet); }
|
@Test public void parseDomain(){ parser = (DomainNameParserImpl) context.getBean(IDomainNameParser.class); UDPPacket packet = new UDPPacket(1393515429, 547730, 288, 16, dnsresponsedata); DomainNameSystem dns = parser.parseDomainName(packet); assertNotNull(dns); }
|
AndroidDeviceImpl implements IAndroidDevice { @Override public boolean isAndroidRooted(IDevice device) throws Exception { if (device == null) { throw new Exception("device is null"); } DeviceState state = device.getState(); if (state.equals(DeviceState.UNAUTHORIZED)) { return false; } for (String cmd : new String[] { "su -c id", "id" }) { String[] res = android.getShellReturn(device, cmd); for (String string : res) { if (string.contains("uid=0(root) gid=0(root)")) { return true; } } } return false; } @Autowired void setAndroid(IAndroid android); RootCheckOutputReceiver makeRootCheckOutputReceiver(); @Override boolean isSeLinuxEnforced(IDevice device); @Override boolean isAndroidRooted(IDevice device); }
|
@Test public void mockUnauthorized() throws Exception { IDevice device = Mockito.mock(IDevice.class); AndroidDeviceImpl spied = Mockito.spy(new AndroidDeviceImpl()); Mockito.when(device.getState()).thenReturn(IDevice.DeviceState.UNAUTHORIZED); boolean rooted = spied.isAndroidRooted(device); rooted = spied.isAndroidRooted(device); assertTrue(rooted == false); }
@Test(expected = Exception.class) public void nullDevice() throws Exception { boolean rooted = androidDeviceImpl.isAndroidRooted(null); assertTrue(rooted == false); }
|
AndroidDeviceImpl implements IAndroidDevice { @Override public boolean isSeLinuxEnforced(IDevice device) throws Exception { if (device == null) { throw new Exception("device is null"); } ShellOutputReceiver shSELinux = new ShellOutputReceiver(); device.executeShellCommand("getenforce", shSELinux); boolean seLinuxEnforced = shSELinux.isSELinuxEnforce(); LOGGER.info("--->seLinuxEnforced:" + seLinuxEnforced); return seLinuxEnforced; } @Autowired void setAndroid(IAndroid android); RootCheckOutputReceiver makeRootCheckOutputReceiver(); @Override boolean isSeLinuxEnforced(IDevice device); @Override boolean isAndroidRooted(IDevice device); }
|
@Test(expected = Exception.class) public void isSeLinuxEnforced_null() throws Exception { IDevice device = null; AndroidDeviceImpl androidDeviceImpl = (AndroidDeviceImpl)context.getBean(IAndroidDevice.class); boolean enforcement = androidDeviceImpl.isSeLinuxEnforced(device); assertTrue(enforcement == true); }
@Test public void isSeLinuxEnforced_yes() throws Exception { IDevice device = Mockito.mock(IDevice.class); AndroidDeviceImpl androidDeviceImpl = (AndroidDeviceImpl) context.getBean(IAndroidDevice.class); ShellOutputReceiver shellOutputReceiver = Mockito.spy( new ShellOutputReceiver()); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { isSeLinux = true; return null; } }).when(device).executeShellCommand("getenforce", shellOutputReceiver); Mockito.when(shellOutputReceiver.isSELinuxEnforce()).thenReturn(isSeLinux); boolean enforcement = androidDeviceImpl.isSeLinuxEnforced(device); assertTrue(enforcement == false); }
|
VideoWriterImpl implements IVideoWriter { @Override public void setTimeScale(int value) { qtOutputStream.setTimeScale(value); } @Autowired void setFileManager(IFileManager fileManager); @Override void init(String videoOutputFile, VideoFormat format); @Override void init(String videoOutputFile, VideoFormat format, float compressionQuality, int timeUnits); @Override void setVideoCompressionQuality(float value); @Override void setTimeScale(int value); @Override void writeFrame(BufferedImage bufferedImage, int duration); @Override void close(); VideoFormat getFormat(); void setFormat(VideoFormat format); File getVideoOutputFile(); void setVideoOutputFile(File videoOutputFile); float getCompressionQuality(); void setCompressionQuality(float compressionQuality); int getTimeUnits(); void setTimeUnits(int timeUnits); }
|
@Test public void mockery() { QuickTimeOutputStream qts = Mockito.mock(QuickTimeOutputStream.class); Mockito.doNothing().when(qts).setTimeScale(Mockito.anyInt()); }
|
Util { public static boolean isMacOS() { return Util.OS_NAME.contains("Mac OS"); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isMacOS(){ boolean ismac = Util.isMacOS(); String os = System.getProperty("os.name"); boolean hasmac = os.contains("Mac"); assertEquals(hasmac, ismac); }
|
Util { public static boolean isWindowsOS() { return Util.OS_NAME.contains("Windows"); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isWindowsOS(){ boolean iswin = Util.isWindowsOS(); String os = System.getProperty("os.name"); boolean haswin = os.contains("Windows"); assertEquals(haswin, iswin); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public int getMajorVersion() { return 1; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testgetMajorVersion_returnIsCorrect() { int testResult = rootedAndroidCollectorImpl.getMajorVersion(); assertEquals(1, testResult); }
|
Util { public static boolean isWindows32OS() { return Util.OS_NAME.contains("Windows") && !isWindows64OS(); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isWindows32OS(){ boolean iswin = Util.isWindows32OS(); String os = System.getProperty("os.name"); boolean haswin32 = os.contains("Windows") && !Util.isWindows64OS(); assertEquals(haswin32, iswin); }
|
Util { public static boolean isWindows64OS() { String arch = System.getenv("PROCESSOR_ARCHITECTURE"); String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); return (arch != null && arch.endsWith("64")) || (wow64Arch != null && wow64Arch.endsWith("64")); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isWindows64OS(){ boolean iswin = Util.isWindows64OS(); String os = System.getProperty("os.name"); String arch = System.getProperty("os.arch"); boolean haswin64 = os.contains("Windows") && arch.contains("64"); assertEquals(haswin64, iswin); }
|
Util { public static boolean isLinuxOS() { return Util.OS_NAME.contains("Linux") || Util.OS_NAME.contains("LINUX"); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isLinuxOS(){ boolean iswin = Util.isLinuxOS(); String os = System.getProperty("os.name"); boolean haswinLinux = os.contains("Linux"); assertEquals(haswinLinux, iswin); }
|
Util { public static String getAppPath() { return System.getProperty("user.dir"); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getAppPath(){ String getAppPath = Util.getAppPath(); String appPath = System.getProperty("user.dir"); assertEquals(appPath, getAppPath); }
|
Util { public static String getAROTraceDirIOS() { return System.getProperty("user.home") + FILE_SEPARATOR + "VideoOptimizerTraceIOS"; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getAROTraceDirIOS(){ String dirname = Util.getAROTraceDirIOS(); boolean hasname = dirname.contains("VideoOptimizerTraceIOS"); assertTrue(hasname); }
|
Util { public static String getAROTraceDirAndroid() { return System.getProperty("user.home") + FILE_SEPARATOR + "VideoOptimizerAndroid"; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getAROTraceDirAndroid(){ String dirname = Util.getAROTraceDirAndroid(); boolean hasname = dirname.contains("VideoOptimizerAndroid"); assertTrue(hasname); }
|
Util { public static String getVideoOptimizerLibrary() { return System.getProperty("user.home") + FILE_SEPARATOR + "VideoOptimizerLibrary"; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getVideoOptimizerLibrary(){ String dirname = Util.getVideoOptimizerLibrary(); boolean hasname = dirname.contains("VideoOptimizerLibrary"); assertTrue(hasname); }
|
Util { public static String getCurrentRunningDir() { String dir = ""; File filepath = new File(Util.class.getProtectionDomain().getCodeSource().getLocation().getPath()); dir = filepath.getParent(); return dir; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getCurrentRunningDir(){ String dir = Util.getCurrentRunningDir(); assertNotNull(dir); }
|
Util { public static String escapeRegularExpressionChar(String str) { String token = str.replace("$", "\\$"); token = token.replace("^", "\\^"); token = token.replace("*", "\\*"); token = token.replace(".", "\\."); token = token.replace("?", "\\?"); return token; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void escapeRegularExpressionChar(){ String str = "string with regex . char $ % *"; String newstr = Util.escapeRegularExpressionChar(str); boolean hasspecialchar = newstr.contains("\\$"); assertEquals(true, hasspecialchar); }
|
Util { public static String getDefaultAppName(String appName) { return getDefaultString(appName, "unknown"); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getDefaultAppName(){ String name = Util.getDefaultAppName(""); assertEquals("unknown", name); name = Util.getDefaultAppName("test"); assertEquals("test",name); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public String getMinorVersion() { return "0.0"; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testgetMinorVersion_returnIsCorrect() { String testResult = rootedAndroidCollectorImpl.getMinorVersion(); assertEquals("0.0", testResult); }
|
Util { public static String getDefaultString(String str, String defaultStr) { return isEmptyIsBlank(str) ? defaultStr : str; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getDefaultString(){ String name = Util.getDefaultString("", "default"); assertEquals("default",name); name = Util.getDefaultString(null, "default"); assertEquals("default",name); }
|
Util { public static Boolean isEmptyIsBlank(String str) { return (str == null || str.trim().isEmpty()); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void isEmptyIsBlank(){ boolean isemptyorblank = Util.isEmptyIsBlank(null); assertTrue(isemptyorblank); isemptyorblank = Util.isEmptyIsBlank(" "); assertTrue(isemptyorblank); }
|
Util { public static double normalizeTime(double time, double pcapTime) { double tmpTime; tmpTime = time > TIME_CORRECTION ? time - pcapTime : time; if (tmpTime < 0) { tmpTime = 0.0; } return tmpTime; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void normalizeTime(){ double value = Util.normalizeTime(-0.00, 1.2); assertNotNull(value > 0); }
|
Util { public static String makeLibFilesFromJar(String filename) { String targetLibFolder = getVideoOptimizerLibrary(); ClassLoader aroClassloader = Util.class.getClassLoader(); try { InputStream is = aroClassloader.getResourceAsStream(filename); if (is != null) { File libfolder = new File(targetLibFolder); targetLibFolder = makeLibFolder(filename, libfolder); if (targetLibFolder != null) { makeLibFile(filename, targetLibFolder, is); } else { return null; } } return targetLibFolder; } catch (Exception e) { logger.error("Failed to extract " + filename + " ," + e.getMessage()); return null; } } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void makeLibFilesFromJar(){ String foldername = Util.makeLibFilesFromJar(aroJpcapLibFileName); assertNotNull(foldername); foldername = Util.makeLibFilesFromJar(null); assertNull(foldername); }
|
Util { public static String makeLibFolder(String filename, File libFolder) { String targetLibFolder = libFolder.toPath().toString(); Path currentRelativePath = Paths.get(""); try { Files.createDirectories(libFolder.toPath()); } catch (IOException ioe1) { targetLibFolder = currentRelativePath.toAbsolutePath().toString() + File.separator + "AROLibrary"; try { Files.createDirectories(libFolder.toPath()); } catch (IOException ioe2) { return null; } } return targetLibFolder; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void makeLibFolder(){ String libfolder = Util.makeLibFolder(aroJpcapLibFileName, new File(aroJpcapLibName)); assertNotNull(libfolder); libfolder = Util.makeLibFolder(aroJpcapLibFileName, new File("")); assertTrue(libfolder.equals("")); libfolder = Util.makeLibFolder("", new File("")); assertTrue(libfolder.equals("")); }
|
Util { public static boolean makeLibFile(String filename, String targetLibFolder, InputStream is) { try { File result = new File(targetLibFolder, filename); result.delete(); OutputStream os = null; if (result.createNewFile()) { os = new FileOutputStream(result); byte[] buffer = new byte[4096]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } try { is.close(); os.close(); } catch (IOException ioe2) { } } return true; } catch (Exception ioe) { return false; } } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void makeLibFile() { boolean result = Util.makeLibFile(aroJpcapLibFileName, aroJpcapLibFileName, null); assertFalse(result); result = Util.makeLibFile(null, null, null); assertFalse(result); }
|
Util { public static Comparator<String> getDomainSorter() { if (comparator == null) { comparator = new Comparator<String>() { Pattern pattern = Pattern.compile("([0-9]*)\\.([0-9]*)\\.([0-9]*)\\.([0-9]*)"); @Override public int compare(String o1, String o2) { if (pattern != null && pattern.matcher(o1).find() && pattern.matcher(o2).find()) { return getDomainVal(o1).compareTo(getDomainVal(o2)); } return o1.compareTo(o2); } private Double getDomainVal(String domain) { Double val = 0D; String[] temp = domain.split("\\."); if (temp != null) { try { for (int idx = 0; idx < temp.length; idx++) { val = (val * 256) + Integer.valueOf(temp[idx]); } } catch (NumberFormatException e) { val = 0D; } } return val; } }; } return comparator; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testComparator() { Comparator<String> result = Util.getDomainSorter(); assertNotNull(result); assertNotNull(result.compare("", "")); assertNotEquals(0,result.compare("100.100.100.100", "100.100.100.101")); assertEquals(0,result.compare("100.100.100.100", "100.100.100.100")); }
|
Util { public static Comparator<String> getFloatSorter() { if (floatValComparator == null) { floatValComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { return Double.compare(Double.parseDouble(o1), Double.parseDouble(o2)); } }; } return floatValComparator; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testFloatComparator() { Comparator<String> result = Util.getFloatSorter(); assertNotNull(result); assertNotEquals(0,result.compare("22.13", "1.02")); assertEquals(0,result.compare("3.19", "3.19")); }
|
Util { public static Comparator<Integer> getDomainIntSorter() { intComparator = new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { if (a.compareTo(b) > 0) { return -1; } else if (a.compareTo(b) < 0) { return 1; } else { return 0; } } }; return intComparator; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testIntComparator() { Comparator<Integer> result = Util.getDomainIntSorter(); assertNotNull(result); assertNotEquals(0,result.compare(1, 2)); assertEquals(0,result.compare(1,1)); }
|
Util { public static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail) { BPResultType bpResultType = BPResultType.PASS; if (resultSize >= warning) { if (resultSize >= fail) { bpResultType = BPResultType.FAIL; } else { bpResultType = BPResultType.WARNING; } } return bpResultType; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void test_intCheckPassFailorWarning() { BPResultType bpResultType = Util.checkPassFailorWarning(2, 1, 4); assertEquals(bpResultType, BPResultType.WARNING); }
@Test public void test_checkPassFailorWarning() { BPResultType bpResultType = Util.checkPassFailorWarning(0.2, 0.1, 0.4); assertEquals(bpResultType, BPResultType.WARNING); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public DataCollectorType getType() { return DataCollectorType.ROOTED_ANDROID; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testDataCoolectorType_returnIsCorrect() { DataCollectorType testResult = rootedAndroidCollectorImpl.getType(); assertEquals(DataCollectorType.ROOTED_ANDROID, testResult); }
|
Util { public static Level getLoggingLvl(String loggingLvl) { Level level = Level.ERROR; if (loggingLvl != null) { if (loggingLvl.equalsIgnoreCase("INFO")) { level = Level.INFO; } else if (loggingLvl.equalsIgnoreCase("DEBUG")) { level = Level.DEBUG; } } return level; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testGetLogLvl() { assertNotNull(Util.getLoggingLvl("INFO")); assertEquals(Level.INFO, Util.getLoggingLvl("INFO")); }
@Test public void testGetLoggingLvl() { assertNotNull(Util.getLoggingLvl("ERROR")); SettingsImpl.getInstance().setAttribute("LOG_LEVEL", "ERROR"); assertEquals("ERROR", Util.getLoggingLevel()); }
|
Util { public static String validateInputLink(String inputValue) { if (StringUtils.isNotBlank(inputValue) && Util.isWindowsOS()) { inputValue = wrapText(inputValue); } return inputValue; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void test_EmptySpace() { String adblink = "C:\\Program Files\\test\\adbfolder"; String validatedLink = Util.validateInputLink(adblink); assertNotNull(validatedLink); assertTrue(validatedLink.contains(" ")); }
|
Util { public static String getEditCap() { return getBinPath() + "editcap"; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getEditCap(){ String editCap = Util.getEditCap(); assertNotNull(editCap); }
|
Util { public static String getFFPROBE() { String config = SettingsImpl.getInstance().getAttribute(FFPROBE); if (StringUtils.isNotBlank(config)) { return validateInputLink(config); } String ffprobe; if (isWindowsOS()) { ffprobe = ("ffprobe.exe"); } else { ffprobe = getBinPath() + "ffprobe"; } return ffprobe; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getFFPROBE(){ String editCap = Util.getFFPROBE(); assertNotNull(editCap); }
|
Util { public static String getFFMPEG() { String config = SettingsImpl.getInstance().getAttribute(FFMPEG); if (StringUtils.isNotBlank(config)) { return validateInputLink(config); } String ffmpeg; if (isWindowsOS()) { ffmpeg = "ffmpeg.exe"; } else { ffmpeg = getBinPath() + "ffmpeg"; } return ffmpeg; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void getFFMPEG(){ String editCap = Util.getFFMPEG(); assertNotNull(editCap); }
|
Util { public static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits) { DecimalFormat df = new DecimalFormat(); df.setGroupingUsed(false); df.setMaximumFractionDigits(maxFractionDigits); df.setMinimumFractionDigits(minFractionDigits); return df.format(number); } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testFormatDecimal_NegativeMaxFractionDigitReplacedByZero() { BigDecimal number = new BigDecimal("19801.1").setScale(2, RoundingMode.HALF_UP); String formattedNumber = Util.formatDecimal(number, -1, 0); assertEquals("19801", formattedNumber); }
|
Util { public static long parseForUTC(String creationTime, String sdFormatStr) { long milli = 0; long mSec = 0; if (creationTime != null) { int msecPos = creationTime.indexOf('.') + 1; if (creationTime.indexOf("Z") == msecPos + 3) { creationTime = creationTime.replaceAll("Z", ""); } SimpleDateFormat sdf = new SimpleDateFormat(sdFormatStr); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = null; try { mSec = msecPos > 0 ? Long.valueOf(creationTime.substring(msecPos).replaceAll("\\d{3}Z", "")): 0; while (mSec > 1000) { mSec /= 10; } creationTime = creationTime.replaceAll("\\d{3}Z", ""); date = sdf.parse(creationTime.replace('T', ' ')); milli = date.getTime() + mSec; } catch (Exception e) { logger.error("Date parsing error :" + e.getMessage()); } } return milli; } static boolean isMacOS(); static boolean isWindowsOS(); static boolean isWindows32OS(); static boolean isWindows64OS(); static boolean isLinuxOS(); static String getAppPath(); static String getMethod(); static String getAROTraceDirIOS(); @Deprecated static String getAroLibrary(); static String getVideoOptimizerLibrary(); static String getExtractedDrivers(); static String getAROTraceDirAndroid(); static String getCurrentRunningDir(); static String escapeRegularExpressionChar(String str); static String getDefaultAppName(String appName); static String getDefaultString(String str, String defaultStr); static Boolean isEmptyIsBlank(String str); static double normalizeTime(double time, double pcapTime); static long parseForUTC(String creationTime, String sdFormatStr); static long parseForUTC(String creationTime); static String formatYMD(long timestamp); static String formatHHMMSS(int seconds); static double convertTime(String time); static String byteArrayToString(byte[] recPayload); static String byteArrayToString(byte[] recPayload, int len); static String condenseStringArray(String[] stringArray); static String byteArrayToHex(byte[] bArray); static Date readHttpDate(String value, boolean defaultForExpired); static String makeLibFilesFromJar(String filename); static String makeLibFolder(String filename, File libFolder); static boolean makeLibFile(String filename, String targetLibFolder, InputStream is); static boolean loadSystemLibrary(String filename); static boolean loadLibrary(String filename, String targetLibFolder); static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits); static String getBinPath(); static String getDumpCap(); static String getFFMPEG(); static String getFFPROBE(); static String getIfuse(); static String getEditCap(); static boolean isJPG(File imgfile, String imgExtn); static double doubleFileSize(double mdataSize); static String extractFullNameFromRequest(HttpRequestResponseInfo hrri); static Comparator<String> getDomainSorter(); static Comparator<Integer> getDomainIntSorter(); static BPResultType checkPassFailorWarning(int resultSize, int warning, int fail); static BPResultType checkPassFailorWarning(double resultValue, double warning, double fail); static BPResultType checkPassFailorWarning(double resultValue, double warning); static Level getLoggingLvl(String loggingLvl); static void setLoggingLevel(String logginglevel); static void setLoggingLevel(Level loggingLevel); static String getLoggingLevel(); static boolean isTestMode(); static Comparator<String> getFloatSorter(); static String getIdeviceScreenshot(); static String percentageFormat(double inputValue); static String extractFullNameFromLink(String objName); static String parseImageName(String originalImage, HttpRequestResponseInfo reqResp); static String extractFrameToPNG(double timestamp, String videoPath, String ximagePath); static String validateInputLink(String inputValue); static String escapeChars(String inputValue); static Map<String, String> getRecentOpenMenuItems(); static String[] getRecentlyOpenedTraces(); static String wrapPasswordForEcho(String password); static String wrapText(String path); static void updateRecentItem(String traceDirectory); static boolean isFilesforAnalysisAvailable(File folderPath); static boolean hasTrafficFile(File traceFile); static String formatDouble(double toFormat); static String formatDoubleToMicro(double toFormat); static final String DUMPCAP; static final String FFMPEG; static final String RECENT_TRACES; static final String FFPROBE; static final String IDEVICESCREENSHOT; static final String OS_NAME; static final String OS_VERSION; static final String OS_ARCHITECTURE; static final String FILE_SEPARATOR; static final String LINE_SEPARATOR; static final String TEMP_DIR; }
|
@Test public void testParseForUTC_when_no_dashes_or_colons() { long result; result = Util.parseForUTC("20191101T0243301975739"); assertEquals(1572576210198L, result); result = Util.parseForUTC("20191101T024330197"); assertEquals(1572576210197L, result); result = Util.parseForUTC("20191101T024330197"); assertEquals(1572576210197L, result); result = Util.parseForUTC("20180111T221459"); assertEquals(1515708899000L, result); result = Util.parseForUTC("20180111T221459456"); assertEquals(1515708899456L, result); result = Util.parseForUTC("2018-01-11T22:14:59"); assertEquals(1515708899000L, result); result = Util.parseForUTC("20180111T221459000"); assertEquals(1515708899000L, result); result = Util.parseForUTC("20180111T221459"); assertEquals(1515708899000L, result); result = Util.parseForUTC("20191106T172805265"); assertEquals(1573061285265L, result); result = Util.parseForUTC("20161122T223027123"); assertEquals(1479853827123L, result); }
@Test public void testParseForUTC() { long result; long result1 = Util.parseForUTC("2020-01-16T20:28:00.405Z"); long result2 = Util.parseForUTC("2020-01-16T20:28:08.413Z"); assertEquals(8008L, result2-result1); result = Util.parseForUTC("2020-01-16T20:41:37.221"); assertEquals(1579207297221L, result); result = Util.parseForUTC("2020-01-16T20:41:37.221Z"); assertEquals(1579207297221L, result); result = Util.parseForUTC("2016-11-22T22:30:27.000000Z"); assertEquals(1479853827000L, result); result = Util.parseForUTC("2016-11-22T22:30:27.591"); assertEquals(1479853827591L, result); result = Util.parseForUTC("2016-11-22T22:30:27.59100"); assertEquals(1479853827591L, result); result = Util.parseForUTC("2016-11-22T22:30:27.591000Z"); assertEquals(1479853827591L, result); result = Util.parseForUTC("2016-11-22T22:30:27.123999Z"); assertEquals(1479853827123L, result); result = Util.parseForUTC("2018-01-11T22:14:59.000000Z"); assertEquals(1515708899000L, result); result = Util.parseForUTC("2018-01-11T22:14:59"); assertEquals(1515708899000L, result); result = Util.parseForUTC("2018-01-11 22:14:59"); assertEquals(1515708899000L, result); }
|
RootedAndroidCollectorImpl implements IDataCollector, IVideoImageSubscriber { @Override public boolean isRunning() { return running; } int getMilliSecondsForTimeout(); @Override String getName(); @Override void addDeviceStatusSubscriber(IDeviceStatus devicestatus); @Override void addVideoImageSubscriber(IVideoImageSubscriber subscriber); @Override int getMajorVersion(); @Override String getMinorVersion(); @Override DataCollectorType getType(); @Override boolean isRunning(); @Override String[] getLog(); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, String password); @Override StatusResult startCollector(boolean isCommandLine, String folderToSaveTrace, VideoOption videoOption_old, boolean isLiveViewVideo, String deviceId, Hashtable<String, Object> extraParams, String password); @Override void timeOutShutdown(); @Override void haltCollectorInDevice(); @Override boolean isTrafficCaptureRunning(int seconds); void startVideoCapture(); @Override StatusResult stopCollector(); @Override void receiveImage(BufferedImage videoimage); @Override String getPassword(); @Override boolean setPassword(String requestPassword); @Override String[] getDeviceSerialNumber(StatusResult status); @Override IAroDevice[] getDevices(StatusResult status); @Override boolean isDeviceDataPulled(); }
|
@Test public void testIsRunning_returnIsFalse() { boolean testResult = rootedAndroidCollectorImpl.isRunning(); assertEquals(false, testResult); }
|
PluginManager implements ApplicationContextAware { public PluginManager() { init(); } PluginManager(); PluginManager(String baseDirectory); String getBaseDirectory(); void refresh(); Collection<Plugin> list(); boolean disable(String name); boolean upload(String filename, InputStream in); void uninstallAll(boolean deleteFiles); boolean uninstall(String name); boolean uninstall(String name, boolean deleteFile); Plugin getPlugin(String name); Object execute(String name, Map properties); void shutdown(); @Override void finalize(); void testPlugin(String name, String location, Map properties, boolean override); static void main(String[] args); Object getBean(String beanName); void setApplicationContext(ApplicationContext appContext); }
|
@Test public void testPluginManager() { Assert.notNull(pluginManager); }
|
PluginManager implements ApplicationContextAware { public Collection<Plugin> list() { Collection<Plugin> list = new ArrayList<Plugin>(); BundleContext context = felix.getBundleContext(); Bundle[] bundles = context.getBundles(); for (Bundle b : bundles) { ServiceReference[] refs = b.getRegisteredServices(); if (refs != null) { for (ServiceReference sr : refs) { LogUtil.debug(PluginManager.class.getName(), " bundle service: " + sr); Object obj = context.getService(sr); if (obj instanceof Plugin) { list.add((Plugin) obj); } context.ungetService(sr); } } } return list; } PluginManager(); PluginManager(String baseDirectory); String getBaseDirectory(); void refresh(); Collection<Plugin> list(); boolean disable(String name); boolean upload(String filename, InputStream in); void uninstallAll(boolean deleteFiles); boolean uninstall(String name); boolean uninstall(String name, boolean deleteFile); Plugin getPlugin(String name); Object execute(String name, Map properties); void shutdown(); @Override void finalize(); void testPlugin(String name, String location, Map properties, boolean override); static void main(String[] args); Object getBean(String beanName); void setApplicationContext(ApplicationContext appContext); }
|
@Test public void testList() { LogUtil.info(getClass().getName(), " ===testList=== "); Collection<Plugin> list = pluginManager.list(); for (Plugin p : list) { LogUtil.info(getClass().getName(), " plugin: " + p.getName() + "; " + p.getClass().getName()); } }
|
PluginManager implements ApplicationContextAware { public void testPlugin(String name, String location, Map properties, boolean override) { LogUtil.info(PluginManager.class.getName(), "====testPlugin===="); Plugin plugin = getPlugin(name); boolean existing = (plugin != null); boolean install = (location != null && location.trim().length() > 0); if (install && (!existing || override)) { InputStream in = null; try { LogUtil.info(PluginManager.class.getName(), " ===install=== "); File file = new File(location); if (file.exists()) { in = new FileInputStream(file); upload(file.getName(), in); } } catch (Exception ex) { LogUtil.error(PluginManager.class.getName(), ex, ""); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { LogUtil.error(PluginManager.class.getName(), ex, ""); } } } LogUtil.info(PluginManager.class.getName(), " ===execute=== "); Object result = execute(name, properties); LogUtil.info(PluginManager.class.getName(), " result: " + result); if (install && (!existing || override)) { LogUtil.info(PluginManager.class.getName(), " ===uninstall=== "); uninstall(name); } LogUtil.info(PluginManager.class.getName(), "====testPlugin end===="); } PluginManager(); PluginManager(String baseDirectory); String getBaseDirectory(); void refresh(); Collection<Plugin> list(); boolean disable(String name); boolean upload(String filename, InputStream in); void uninstallAll(boolean deleteFiles); boolean uninstall(String name); boolean uninstall(String name, boolean deleteFile); Plugin getPlugin(String name); Object execute(String name, Map properties); void shutdown(); @Override void finalize(); void testPlugin(String name, String location, Map properties, boolean override); static void main(String[] args); Object getBean(String beanName); void setApplicationContext(ApplicationContext appContext); }
|
@Test public void testPluginTest() { LogUtil.info(getClass().getName(), " ===testPluginTest=== "); pluginManager.testPlugin(getSamplePlugin(), getSamplePluginFile(), null, true); }
|
DepartmentVariablePlugin extends DefaultFormVariablePlugin { public String getName() { return "DepartmentVariablePlugin"; } String getName(); String getVersion(); String getDescription(); PluginProperty[] getPluginProperties(); Map getVariableOptions(Map props); }
|
@Test public void testList() { System.out.println(" ===testList=== "); Collection<Plugin> list = pluginManager.list(); for (Plugin p : list) { System.out.println(" plugin: " + p.getName() + "; " + p.getClass().getName()); } }
|
BeanShellPlugin extends DefaultPlugin implements ApplicationPlugin, FormVariablePlugin, ParticipantPlugin { public String getName() { return "BeanShell Plugin"; } String getName(); String getVersion(); String getDescription(); PluginProperty[] getPluginProperties(); Object execute(Map properties); Map getVariableOptions(Map properties); Collection<String> getActivityAssignments(Map properties); }
|
@Test public void testList() { System.out.println(" ===testList=== "); Collection<Plugin> list = pluginManager.list(); for (Plugin p : list) { System.out.println(" plugin: " + p.getName() + "; " + p.getClass().getName()); } }
|
PosTagger { public synchronized List<Conll> tagging(List<String> tokens, FragmentationType fragmentationType) throws ClassifierModelNotFoundException, IncorrectTokenException { AdvancedTokenHandler<Conll> tokenHandler = new StatefulTokenHandler(fragmentationType); try { this.tt.setHandler(tokenHandler); this.tt.process(tokens); } catch (IOException e) { throw new ClassifierModelNotFoundException("The classifier's model \'" + this.modelFilePath + "\' isn't found.", e); } catch (TreeTaggerException e) { throw new IncorrectTokenException("There is an incorrect token.", e); } return tokenHandler.getTokens(); } PosTagger(String modelFilePath, String treeTaggerHome); synchronized List<Conll> tagging(List<String> tokens, FragmentationType fragmentationType); void destroy(); }
|
@Test public void taggingTest() throws IncorrectTokenException, ClassifierModelNotFoundException { String text = "Отменить подписку на канал \"ByDaniel \u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\"?"; List<String> tokens = this.tokenizer.tokenization(text); List<Conll> conlls = this.tagger.tagging(tokens, FragmentationType.NO_FRAGMENTATION); Assert.assertFalse(conlls.isEmpty()); }
@Test public void taggingTest2() throws IncorrectTokenException, ClassifierModelNotFoundException { String text = "Политологи прогнозируют завинчивание гаек в качестве реакции властей Фото \u200B"; List<String> tokens = this.tokenizer.tokenization(text); List<Conll> conlls = this.tagger.tagging(tokens, FragmentationType.NO_FRAGMENTATION); Assert.assertFalse(conlls.isEmpty()); }
|
Shortbread { @TargetApi(25) public static void create(@NonNull Context context) { if (Build.VERSION.SDK_INT < 25) { return; } if (generated == null) { try { generated = Class.forName("shortbread.ShortbreadGenerated"); createShortcuts = generated.getMethod("createShortcuts", Context.class); callMethodShortcut = generated.getMethod("callMethodShortcut", Activity.class); } catch (ClassNotFoundException e) { Log.i(Shortbread.class.getSimpleName(), "No shortcuts found"); } catch (NoSuchMethodException e) { e.printStackTrace(); } } Context applicationContext = context.getApplicationContext(); if (!shortcutsSet) { setShortcuts(applicationContext); } if (!activityLifecycleCallbacksSet) { setActivityLifecycleCallbacks(applicationContext); } if (context instanceof Activity) { callMethodShortcut((Activity) context); } } private Shortbread(); @TargetApi(25) static void create(@NonNull Context context); }
|
@Test @Config(sdk = 24) public void doesNothingBeforeApi25() { Shortbread.create(activity); verifyNoMoreInteractions(activity); }
@Test public void usesApplicationContext() { Shortbread.create(activity); verify(activity).getApplicationContext(); verify(application).getSystemService(ShortcutManager.class); }
@Test public void registersActivityLifecycleCallbacksOnce() { Shortbread.create(activity); verify(application).registerActivityLifecycleCallbacks(any(Application.ActivityLifecycleCallbacks.class)); Shortbread.create(activity); verify(application, times(1)).registerActivityLifecycleCallbacks(any(Application.ActivityLifecycleCallbacks.class)); }
@Test public void setsEnabledShortcutsOnce() { final List<ShortcutInfo> enabledShortcuts = ShortbreadGenerated.createShortcuts(activity).get(0); Shortbread.create(activity); verify(shortcutManager).setDynamicShortcuts(enabledShortcuts); Shortbread.create(activity); verify(shortcutManager, times(1)).setDynamicShortcuts(enabledShortcuts); }
@Test public void setsDisabledShortcutsOnce() { final List<ShortcutInfo> disabledShortcuts = ShortbreadGenerated.createShortcuts(activity).get(1); Shortbread.create(activity); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); verify(shortcutManager).disableShortcuts(captor.capture()); assertEquals(disabledShortcuts.size(), captor.getValue().size()); Shortbread.create(activity); verify(shortcutManager, times(1)).disableShortcuts(any(List.class)); }
@Test public void intentHasExtra_callsMethodShortcut() { when(intent.hasExtra("shortbread_method")).thenReturn(true); ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut = null; Shortbread.create(activity); assertEquals(activity, ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); }
@Test public void intentDoesNotHaveExtra_doesNotCallMethodShortcut() { when(intent.hasExtra("shortbread_method")).thenReturn(false); ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut = null; Shortbread.create(activity); assertNull(ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); }
@Test public void activityLifecycleListenerCallsMethodShortcut() { when(intent.hasExtra("shortbread_method")).thenReturn(true); Shortbread.create(application); ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut = null; ArgumentCaptor<Application.ActivityLifecycleCallbacks> captor = ArgumentCaptor.forClass( Application.ActivityLifecycleCallbacks.class); verify(application).registerActivityLifecycleCallbacks(captor.capture()); Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = captor.getValue(); activityLifecycleCallbacks.onActivityCreated(activity, null); assertNull(ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); activityLifecycleCallbacks.onActivityStarted(activity); assertEquals(activity, ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut = null; activityLifecycleCallbacks.onActivityStarted(activity); assertNull(ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); }
|
JobConfigManager { public Boolean save(JobConfig config){ if (jobConfigDao.save(config)){ if (jobConfigDao.bindJob(config.getJobId(), config.getId())){ return Boolean.TRUE; } else { jobConfigDao.delete(config.getId()); } } return Boolean.FALSE; } Boolean save(JobConfig config); Boolean delete(Long jobConfigId); Boolean delete(JobConfig cfg); Boolean deleteByJobId(Long jobId); }
|
@Test public void testSave(){ JobConfig config = new JobConfig(); config.setJobId(1L); config.setMisfire(Boolean.TRUE); config.setShardCount(4); config.setShardParams("0=0;1=1;2=2;3=3"); assertTrue(jobConfigManager.save(config)); }
|
JobConfigManager { public Boolean delete(Long jobConfigId){ JobConfig cfg = jobConfigDao.findById(jobConfigId); if (cfg == null){ return Boolean.TRUE; } if (jobConfigDao.unbindJob(cfg.getJobId(), cfg.getId())){ return jobConfigDao.delete(jobConfigId); } return Boolean.FALSE; } Boolean save(JobConfig config); Boolean delete(Long jobConfigId); Boolean delete(JobConfig cfg); Boolean deleteByJobId(Long jobId); }
|
@Test public void testDelete(){ assertTrue(jobConfigManager.delete(1L)); }
|
JobInstanceManager { public Boolean create(JobInstance instance){ if (jobInstanceDao.save(instance)){ if (jobInstanceDao.bindJob(instance.getJobId(), instance.getId())){ return Boolean.TRUE; } else { jobInstanceDao.delete(instance.getId()); } } return Boolean.FALSE; } Boolean create(JobInstance instance); Boolean deleteById(Long jobInstanceId); Boolean deleteByJobId(Long jobId); }
|
@Test public void testCreate(){ JobInstance instance = new JobInstance(); instance.setJobId(1L); instance.setStatus(JobInstanceStatus.NEW.value()); instance.setStartTime(new Date()); instance.setServer("127.0.0.1:1122"); assertTrue(jobInstanceManager.create(instance)); }
|
AppManager { public Boolean save(App app) { if (appDao.save(app)){ return appDao.index(app); } return Boolean.FALSE; } Boolean delete(Long appId); Boolean save(App app); }
|
@Test public void testSave(){ App app = new App(); app.setAppName("test_app"); app.setAppKey("123456"); app.setAppDesc("测试应用"); assertTrue(appManager.save(app)); assertNotNull(appDao.findByName(app.getAppName())); }
|
AppManager { public Boolean delete(Long appId){ App app = appDao.findById(appId); if (app == null){ return Boolean.TRUE; } if(appDao.unIndex(app)){ return appDao.delete(app.getId()); } return Boolean.FALSE; } Boolean delete(Long appId); Boolean save(App app); }
|
@Test public void testDelete(){ assertTrue(appManager.delete(4L)); assertTrue(appManager.delete(404L)); }
|
JobManager { public Boolean save(Job job){ boolean isCreate = job.getId() == null; boolean success = jobDao.save(job); if (success){ if (isCreate){ if(jobDao.bindApp(job.getAppId(), job.getId())){ success = jobDao.indexJobClass(job.getAppId(), job.getId(), job.getClazz()); } else { success = false; } if (!success){ delete(job.getId()); } } } return success; } Boolean save(Job job); Boolean delete(Long jobId); }
|
@Test public void testSave(){ Job job = new Job(); job.setAppId(1L); job.setClazz("me.hao0.antares.client.job.HelloJob"); job.setCron("0/30 * * * * ?"); job.setStatus(JobStatus.ENABLE.value()); job.setType(JobType.DEFAULT.value()); assertTrue(jobManager.save(job)); }
|
JobManager { public Boolean delete(Long jobId){ Job job = jobDao.findById(jobId); if (job == null){ return Boolean.TRUE; } if (jobDao.unbindApp(job.getAppId(), jobId)){ return jobDao.delete(jobId) && jobDao.unIndexJobClass(job.getAppId(), job.getClazz()); } return Boolean.FALSE; } Boolean save(Job job); Boolean delete(Long jobId); }
|
@Test public void testDelete(){ }
|
CrudService { public T fetchById(UUID id) { T item = db.find(type, id); if (item == null) { throw new NotFoundException(id); } return item; } @Inject CrudService(Class<T> type, EbeanServer db); T fetchById(UUID id); List<T> fetchByFilter(ListFiltering filter); T create(T item); T update(UUID id, T item); void delete(UUID id); }
|
@Test public void fetchShouldFindInDatabase() { UUID id = UUID.randomUUID(); TestItem item = new TestItem(); when(db.find(TestItem.class, id)).thenReturn(item); assertThat(service.fetchById(id)).isEqualTo(item); }
@Test(expected = NotFoundException.class) public void fetchShouldThrowWhenIdNotFound() { service.fetchById(UUID.randomUUID()); }
|
FunctionConsumer extends DefaultConsumer { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); Stopwatch stopwatch = Stopwatch.createStarted(); try { T message = MAPPER.readValue(body, type); if (log.isTraceEnabled()) { log.trace("Received message '{}' with data '{}'.", deliveryTag, new String(body)); } processor.apply(message); getChannel().basicAck(deliveryTag, false); stopwatch.stop(); successCount.mark(); successDuration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); log.info("Processed {} message '{}' succesfully in {} ms.", type.getSimpleName(), deliveryTag, stopwatch.elapsed(TimeUnit.MILLISECONDS)); } catch (Exception e) { getChannel().basicNack(deliveryTag, false, true); stopwatch.stop(); failureCount.mark(); failureDuration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); log.error("Processing {} message '{}' failed with exception:", type.getSimpleName(), deliveryTag, e); } } FunctionConsumer(Channel channel, Function<T, Void> processor, Class<T> type, String name, MetricRegistry metrics); @Override void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body); }
|
@Test public void shouldRejectMessageOnException() throws IOException { FunctionConsumer<TestMsg> consumer = new FunctionConsumer<>(channel, msg -> { throw new RuntimeException("Message processing failed on purpose."); }, TestMsg.class, "name", metrics); consumer.handleDelivery(null, envelope, null, message); verify(channel).basicNack(1L, false, true); }
@Test public void shouldRecordConsumeSuccessMetrics() throws IOException { FunctionConsumer<TestMsg> consumer = new FunctionConsumer<>(channel, msg -> null, TestMsg.class, "name", metrics); consumer.handleDelivery(null, envelope, null, message); assertThat(metrics.meter("queue.TestMsg.name.consume.success.count").getCount()).isEqualTo(1); assertThat(metrics.timer("queue.TestMsg.name.consume.success.duration").getCount()).isEqualTo(1); }
@Test public void shouldRecordConsumeFailureMetrics() throws IOException { FunctionConsumer<TestMsg> consumer = new FunctionConsumer<>(channel, msg -> { throw new RuntimeException("Message processing failed on purpose."); }, TestMsg.class, "name", metrics); consumer.handleDelivery(null, envelope, null, message); assertThat(metrics.meter("queue.TestMsg.name.consume.failure.count").getCount()).isEqualTo(1); assertThat(metrics.timer("queue.TestMsg.name.consume.failure.duration").getCount()).isEqualTo(1); }
@Test public void shouldMapMessageToType() throws IOException { FunctionConsumer<TestMsg> consumer = new FunctionConsumer<>(channel, msg -> { assertThat(msg.getName()).isEqualTo("test"); assertThat(msg.getCount()).isEqualTo(2); return null; }, TestMsg.class, "name", metrics); consumer.handleDelivery(null, envelope, null, message); }
@Test public void shouldAcknowledgeMessage() throws IOException { FunctionConsumer<TestMsg> consumer = new FunctionConsumer<>(channel, msg -> null, TestMsg.class, "name", metrics); consumer.handleDelivery(null, envelope, null, message); verify(channel).basicAck(1L, false); }
|
RabbitMQMessageQueue implements MessageQueue<T> { @Override public void publish(T message) { try { channel.basicPublish("", name, MessageProperties.PERSISTENT_TEXT_PLAIN, MAPPER.writeValueAsBytes(message)); publish.mark(); if (log.isTraceEnabled()) { log.trace("Published to '{}' with data '{}'.", name, MAPPER.writeValueAsString(message)); } } catch (IOException e) { throw new MessageQueueException("Unable to publish to queue.", e); } } RabbitMQMessageQueue(Channel channel, String name, Class<T> type, MetricRegistry metrics); @Override void publish(T message); @Override Closeable consume(Function<T, Void> processor); @Override T consumeNext(); }
|
@Test public void shouldPublishPersistentMessageToQueue() throws IOException { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); TestMsg message = new TestMsg("blah", 5); byte[] messageBytes = Jackson.newObjectMapper().writeValueAsBytes(message); queue.publish(message); verify(channel).basicPublish(Matchers.eq(""), Matchers.eq(QUEUE_NAME), Matchers.eq(MessageProperties.PERSISTENT_TEXT_PLAIN), Matchers.eq(messageBytes)); }
@Test public void shouldRecordPublishMetrics() { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); queue.publish(new TestMsg("blah", 5)); assertThat(metrics.meter("queue.TestMsg.test.publish").getCount()).isEqualTo(1); }
|
RabbitMQMessageQueue implements MessageQueue<T> { @Override public Closeable consume(Function<T, Void> processor) { Consumer consumer = new FunctionConsumer<>(channel, processor, type, name, metrics); try { String tag = channel.basicConsume(name, false, consumer); log.info("Set up consumer '{}' for queue '{}'.", tag, name); return () -> channel.basicCancel(tag); } catch (IOException e) { throw new MessageQueueException("Unable to set up consumer.", e); } } RabbitMQMessageQueue(Channel channel, String name, Class<T> type, MetricRegistry metrics); @Override void publish(T message); @Override Closeable consume(Function<T, Void> processor); @Override T consumeNext(); }
|
@Test public void shouldConsumeByAttachingConsumerToQueue() throws IOException { RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics); queue.consume(msg -> null); verify(channel).basicConsume(Matchers.eq(QUEUE_NAME), Matchers.eq(false), Matchers.any(FunctionConsumer.class)); }
|
HashedValue { public boolean equalsPlaintext(String plaintext) { return BCrypt.checkpw(plaintext, hashedValue); } HashedValue(String plaintext); boolean equalsPlaintext(String plaintext); }
|
@Test public void shouldEqualOriginalPlaintext() { HashedValue hashed = new HashedValue("test"); assertThat(hashed.equalsPlaintext("test")).isTrue(); }
@Test public void shouldNotEqualDifferentPlaintext() { HashedValue hashed = new HashedValue("test"); assertThat(hashed.equalsPlaintext("nottest")).isFalse(); }
|
EmailServiceFactory implements Factory<EmailService> { @Override public EmailService provide() { if (!config.getEmail().isEnabled() || config.getSendGrid() == null) { log.info("Email sending disabled, logging them to console instead."); return new LoggerEmailService(); } else { log.info("Email sending enabled with SendGrid username {}.", config.getSendGrid().getUsername()); return locator.getService(SendGridEmailService.class); } } @Inject EmailServiceFactory(HasSendGridConfiguration config, ServiceLocator locator); @Override EmailService provide(); @Override void dispose(EmailService instance); }
|
@Test public void shouldCreateLoggerServiceWhenEmailsAreDisabled() { TestConfiguration config = new TestConfiguration(); config.getEmail().setEnabled(false); EmailService email = new EmailServiceFactory(config, null).provide(); assertThat(email).isInstanceOf(LoggerEmailService.class); }
|
BasicAuthFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header != null && header.startsWith("Basic ")) { String decoded = new String(BaseEncoding.base64().decode(header.substring(header.indexOf(" ") + 1))); if (decoded.contains(":")) { String username = decoded.substring(0, decoded.indexOf(":")); String password = decoded.substring(decoded.indexOf(":") + 1, decoded.length()); if (username.equals(this.username) && password.equals(this.password)) { chain.doFilter(request, response); return; } else { log.info("Incorrect admin login with username '{}'.", username); } } } response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Administration\""); response.sendError(Response.SC_UNAUTHORIZED); } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); @Override void destroy(); static void addToAdmin(Environment env, String username, String password); }
|
@Test public void shouldAllowRequestsWithCorrectCredentials() throws IOException, ServletException { when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(getHeader("testuser", "testpass")); new BasicAuthFilter("testuser", "testpass").doFilter(request, response, chain); verify(chain).doFilter(request, response); }
@Test public void shouldRejectRequestsWithIncorrectCredentials() throws IOException, ServletException { when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(getHeader("testuser", "WRONGpass")); new BasicAuthFilter("testuser", "testpass").doFilter(request, response, chain); verify(response).setHeader(Matchers.eq(HttpHeaders.WWW_AUTHENTICATE), Matchers.contains("Basic")); verify(response).sendError(401); }
@Test public void shouldRejectRequestsWithoutCredentials() throws IOException, ServletException { new BasicAuthFilter("testuser", "testpass").doFilter(request, response, chain); verify(response).setHeader(Matchers.eq(HttpHeaders.WWW_AUTHENTICATE), Matchers.contains("Basic")); verify(response).sendError(401); }
@Test public void shouldRejectRequestsWithInvalidHeader() throws IOException, ServletException { when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("blah"); new BasicAuthFilter("testuser", "testpass").doFilter(request, response, chain); verify(response).setHeader(Matchers.eq(HttpHeaders.WWW_AUTHENTICATE), Matchers.contains("Basic")); verify(response).sendError(401); }
|
QueueWorker implements Runnable { @Override public void run() { cancel = queue.consume(this::process); } QueueWorker(MessageQueue<T> queue); @Override void run(); void cancel(); }
|
@Test public void shouldConsumeProcessingFunctionWhenRun() { @SuppressWarnings("unchecked") MessageQueue<String> queue = mock(MessageQueue.class); new TestWorker(queue).run(); verify(queue).consume(Matchers.any()); }
|
LintRegistry extends IssueRegistry { @Override public List<Issue> getIssues() { return ImmutableList.of(AndroidLogDetector.ISSUE, HardcodedColorsDetector.ISSUE, DirectMaterialPaletteColorUsageDetector.ISSUE, NonMaterialColorsDetector.ISSUE); } @Override List<Issue> getIssues(); }
|
@Test public void number_of_issues_registered() { int size = lintRegistry.getIssues().size(); assertThat(size).isEqualTo(NUMBER_OF_EXISTING_DETECTORS); }
@Test public void issues_verification() { List<Issue> actual = lintRegistry.getIssues(); assertThat(actual).contains(AndroidLogDetector.ISSUE); assertThat(actual).contains(HardcodedColorsDetector.ISSUE); assertThat(actual).contains(DirectMaterialPaletteColorUsageDetector.ISSUE); assertThat(actual).contains(NonMaterialColorsDetector.ISSUE); }
|
SupportActivityUtils { @SuppressWarnings("WeakerAccess") public static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager, @NonNull final Fragment fragment, @NonNull final String tag) { checkNotNull(fragmentManager, "fragmentManager must not be null!"); checkNotNull(fragment, "fragment must not be null!"); checkNotNull(tag, "tag must not be null!"); checkArgument(!tag.isEmpty(), "tag string must not be empty!"); removeSupportFragment(fragmentManager, tag); final FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(fragment, tag); transaction.commitAllowingStateLoss(); } private SupportActivityUtils(); @SuppressWarnings("WeakerAccess") static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager,
@NonNull final Fragment fragment,
@NonNull final String tag); @NonNull static Fragment findOrCreateSupportFragment(@NonNull final FragmentManager fragmentManager, @NonNull final String tag); @SuppressWarnings("WeakerAccess") static void removeSupportFragment(@NonNull final FragmentManager fragmentManager,
@NonNull final String tag); }
|
@Test public void addSupportFragmentToActivity_AddsNewFragment() { SupportActivityUtils.addSupportFragmentToActivity(mFragmentManager, mFragment, TEST_TAG); then(mFragmentTransaction).should().add(mFragment, TEST_TAG); }
@Test public void addSupportFragmentToActivity_WhenFragmentWithGivenTagExists_ThenRemovesDuplicate() { given(mFragmentManager.findFragmentByTag(TEST_TAG)).willReturn(mFragment); SupportActivityUtils.addSupportFragmentToActivity(mFragmentManager, mFragment, TEST_TAG); then(mFragmentTransaction).should().remove(mFragment); }
|
DiffRequestManagerHolder { void recycle() { for (DiffRequestManager manager : mDiffRequestManagers.values()) { manager.releaseResources(); } mDiffRequestManagers.clear(); } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }
|
@Test public void recycle_ReleasesResourcesOfEachManager() { mDiffRequestManagerHolder.recycle(); then(mDiffRequestManager).should().releaseResources(); }
|
DiffRequestManagerHolder { void configurationChanged() { for (DiffRequestManager manager : mDiffRequestManagers.values()) { manager.swapAdapter(null); } } DiffRequestManagerHolder(@NonNull final Map<String, DiffRequestManager> managers); @NonNull static DiffRequestManagerHolder create(); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter); @NonNull DiffRequestManager<D, A> with(@NonNull final A adapter, @NonNull final String tag); @NonNull DiffRequestManager getDefaultManager(); @NonNull DiffRequestManager getManager(@NonNull final String tag); }
|
@Test public void configurationChanged_ClearsCurrentAdapters() { mDiffRequestManagerHolder.configurationChanged(); then(mDiffRequestManager).should().swapAdapter(null); }
|
DiffRequest { @Override public String toString() { return "DiffRequest{" + "mDiffCallback=" + mDiffCallback + ", mTag='" + mTag + '\'' + ", mNewData=" + mNewData + ", mDetectMoves=" + mDetectMoves + '}'; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void toString_IsCorrect() { assertThat(new DiffRequest<String>(true, Constants.DIFF_REQUEST_MANAGER_DEFAULT_TAG, null, mDataComparable).toString(), startsWith("DiffRequest")); }
|
DiffRequest { @NonNull public DiffUtil.Callback getDiffCallback() { return mDiffCallback; } @SuppressWarnings("WeakerAccess") DiffRequest(final boolean detectMoves, @NonNull final String tag, @Nullable final List<D> newData, @NonNull final DiffUtil.Callback diffCallback); @NonNull DiffUtil.Callback getDiffCallback(); @NonNull String getTag(); @SuppressWarnings("WeakerAccess") boolean isDetectingMoves(); @Nullable List<D> getNewData(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void getDiffCallback_ReturnsCorrectCallback() { assertThat(mDiffRequest.getDiffCallback(), equalTo(mDataComparable)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.