src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
JsonRpcInvoker { public <T> T get(final JsonRpcClientTransport transport, final String handle, final Class<T>... classes) { for (Class<T> clazz : classes) { typeChecker.isValidInterface(clazz); } return (T) Proxy.newProxyInstance(JsonRpcInvoker.class.getClassLoader(), classes, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return JsonRpcInvoker.this.invoke(handle, transport, method, args); } }); } JsonRpcInvoker(); JsonRpcInvoker(Gson gson); JsonRpcInvoker(TypeChecker typeChecker); JsonRpcInvoker(TypeChecker typeChecker, Gson gson); T get(final JsonRpcClientTransport transport, final String handle, final Class<T>... classes); }
@Test public void testErrorWithPrimitiveData() { final String errorMessage = "some error message"; JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); resp.addProperty("error", errorMessage); TestInterface handle = invoker.get(getTransport(resp), "someHandler", TestInterface.class); try { handle.call(1); fail("should throw exception"); } catch (JsonRpcRemoteException e) { assertNull(e.getCode()); assertEquals(e.getMsg(), errorMessage); assertNull(e.getData()); } } @Test public void testIssue0002() throws Exception { JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); JsonObject error = new JsonObject(); error.addProperty("code", -32002); error.addProperty("message", "service.invalid-parameters"); error.add("data", new JsonParser().parse("{\"email\":[\"'email' is no valid email address in the basic format local-part@hostname\"]}")); resp.add("error", error); TestInterface handle = invoker.get(getTransport(resp), "someHandler", TestInterface.class); try { handle.call(1); } catch (UnsupportedOperationException e) { e.printStackTrace(); fail("issue 0002 is not resolved"); } catch (Exception e) { } } @Test(dataProvider = "testErrorData") public void testError(Integer errorCode, String errorMessage, String errorData) { JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); JsonObject error = new JsonObject(); if (errorCode != null) { error.addProperty("code", errorCode); } if (errorMessage != null) { error.addProperty("message", errorMessage); } if (errorData != null) { error.addProperty("data", errorData); } resp.add("error", error); TestInterface handle = invoker.get(getTransport(resp), "someHandler", TestInterface.class); try { handle.call(1); fail("should throw exception"); } catch (JsonRpcRemoteException e) { if (errorCode == null) { assertNull(errorCode); } else { assertEquals(e.getCode(), errorCode); } if (errorMessage == null) { assertNull(e.getMsg()); } else { assertEquals(e.getMsg(), errorMessage); } if (errorData == null) { assertNull(e.getData()); } else { assertEquals(e.getData(), errorData); } } } @Test public void testErrorArray() { JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); JsonArray error = new JsonArray(); resp.add("error", error); TestInterface handle = invoker.get(getTransport(resp), "someHandler", TestInterface.class); try { handle.call(1); fail("should throw exception"); } catch (JsonRpcRemoteException e) { assertNull(e.getCode()); assertNull(e.getData()); } } @Test public void testResultVoid() { JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); TestInterface handle = invoker.get(getTransport(resp), "someHandler", TestInterface.class); handle.call(); }
CrashesViewModel { public ViewState getCrashNotFoundViewState() { return new ViewState.Builder().withVisible(crashViewModels.isEmpty()).build(); } CrashesViewModel(List<CrashViewModel> crashViewModels); List<CrashViewModel> getCrashViewModels(); ViewState getCrashNotFoundViewState(); }
@Test public void shouldReturnCrashNotFoundVisibilityAsVISBILEWhenThereAreNoCrashes() throws Exception { CrashesViewModel viewModel = new CrashesViewModel(new ArrayList<CrashViewModel>()); assertThat(viewModel.getCrashNotFoundViewState().getVisibility(), is(View.VISIBLE)); } @Test public void shouldReturnCrashNotFoundVisibilityAsGONEWhenThereAreCrashes() throws Exception { CrashesViewModel viewModel = new CrashesViewModel(asList(mock(CrashViewModel.class))); assertThat(viewModel.getCrashNotFoundViewState().getVisibility(), is(View.GONE)); }
ViewState { public int getVisibility() { return visibility; } private ViewState(int visibility); int getVisibility(); }
@Test public void shouldReturnViewStateBasedOnVisibilityCriteria() throws Exception { assertThat(new ViewState.Builder().withVisible(true).build().getVisibility(), is(View.VISIBLE)); assertThat(new ViewState.Builder().withVisible(false).build().getVisibility(), is(View.GONE)); }
CrashAnalyzer { public Crash getAnalysis() { StringBuilder factsBuilder = new StringBuilder(); String placeOfCrash; factsBuilder.append(throwable.getLocalizedMessage()); factsBuilder.append("\n"); factsBuilder.append(stackTrace(throwable.getStackTrace())); factsBuilder.append("\n"); if (throwable.getCause() != null) { factsBuilder.append("Caused By: "); StackTraceElement[] stackTrace = throwable.getCause().getStackTrace(); placeOfCrash = getCrashOriginatingClass(stackTrace); factsBuilder.append(stackTrace(stackTrace)); } else { placeOfCrash = getCrashOriginatingClass(throwable.getStackTrace()); } return new Crash(placeOfCrash, throwable.getLocalizedMessage(), factsBuilder.toString()); } CrashAnalyzer(Throwable throwable); Crash getAnalysis(); }
@Test public void shouldBuildStackTrace() throws Exception { Throwable throwable = mock(Throwable.class); when(throwable.getLocalizedMessage()).thenReturn("Full Message"); StackTraceElement stackTraceElement1 = new StackTraceElement("Class1", "method1", "file1", 1); StackTraceElement stackTraceElement2 = new StackTraceElement("Class2", "method2", "file2", 2); StackTraceElement[] stackTraceElements = {stackTraceElement1, stackTraceElement2}; Throwable appThrowable = mock(Throwable.class); StackTraceElement[] actualStackTraceElements = {stackTraceElement2, stackTraceElement1, stackTraceElement2}; when(appThrowable.getStackTrace()).thenReturn(actualStackTraceElements); when(throwable.getCause()).thenReturn(appThrowable); when(throwable.getStackTrace()).thenReturn(stackTraceElements); CrashAnalyzer investigator = new CrashAnalyzer(throwable); Crash crash = investigator.getAnalysis(); assertThat(crash.getStackTrace(), containsString("Full Message\n" + "at Class1.method1(file1:1)\n" + "at Class2.method2(file2:2)\n\n" + "Caused By: at Class2.method2(file2:2)\n" + "at Class1.method1(file1:1)\n" + "at Class2.method2(file2:2)\n") ); assertThat(crash.getPlace(), containsString("Class2:2")); } @Test public void shouldBuildStackTraceWhenCauseIsNotPresentInsideThrowable() throws Exception { Throwable throwable = mock(Throwable.class); when(throwable.getLocalizedMessage()).thenReturn("Full Message"); StackTraceElement stackTraceElement1 = new StackTraceElement("Class1", "method1", "file1", 1); StackTraceElement stackTraceElement2 = new StackTraceElement("Class2", "method2", "file2", 2); StackTraceElement[] stackTraceElements = {stackTraceElement1, stackTraceElement2}; when(throwable.getCause()).thenReturn(null); when(throwable.getStackTrace()).thenReturn(stackTraceElements); CrashAnalyzer investigator = new CrashAnalyzer(throwable); Crash crash = investigator.getAnalysis(); assertThat(crash.getStackTrace(), containsString("Full Message\n" + "at Class1.method1(file1:1)\n" + "at Class2.method2(file2:2)\n\n") ); assertThat(crash.getPlace(), containsString("Class1:1")); }
CrashViewModel { public String getPlace() { String[] placeTrail = crash.getPlace().split("\\."); return placeTrail[placeTrail.length - 1]; } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }
@Test public void shouldReturnPlaceOfCrash() throws Exception { Crash crash = mock(Crash.class); when(crash.getPlace()).thenReturn("com.singhajit.sherlock.core.Crash:20"); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getPlace(), is("Crash:20")); }
CrashViewModel { public String getDate() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a EEE, MMM d, yyyy"); return simpleDateFormat.format(crash.getDate()); } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }
@Test public void shouldReturnDateOfCrash() throws Exception { Crash crash = mock(Crash.class); Calendar calendar = Calendar.getInstance(); calendar.set(2017, 4, 15, 10, 50, 55); when(crash.getDate()).thenReturn(calendar.getTime()); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getDate(), is("10:50 AM Mon, May 15, 2017")); }
CrashViewModel { public int getIdentifier() { return crash.getId(); } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }
@Test public void shouldReturnIdentifier() throws Exception { Crash crash = mock(Crash.class); when(crash.getId()).thenReturn(1); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getIdentifier(), is(1)); }
BazelExternalIdGenerator { public List<BazelExternalId> generate(final BazelExternalIdExtractionFullRule xPathRule) { final List<BazelExternalId> projectExternalIds = new ArrayList<>(); final List<String> dependencyListQueryArgs = deriveDependencyListQueryArgs(xPathRule); Optional<String[]> rawDependencies = executeDependencyListQuery(xPathRule, dependencyListQueryArgs); if (!rawDependencies.isPresent()) { return projectExternalIds; } for (final String rawDependency : rawDependencies.get()) { String bazelExternalId = transformRawDependencyToBazelExternalId(xPathRule, rawDependency); final List<String> dependencyDetailsQueryArgs = deriveDependencyDetailsQueryArgs(xPathRule, bazelExternalId); final Optional<String> xml = executeDependencyDetailsQuery(xPathRule, dependencyDetailsQueryArgs); if (!xml.isPresent()) { return projectExternalIds; } final Optional<List<String>> artifactStrings = parseArtifactStringsFromXml(xPathRule, xml.get()); if (!artifactStrings.isPresent()) { return projectExternalIds; } for (String artifactString : artifactStrings.get()) { BazelExternalId externalId = BazelExternalId.fromBazelArtifactString(artifactString, xPathRule.getArtifactStringSeparatorRegex()); projectExternalIds.add(externalId); } } return projectExternalIds; } BazelExternalIdGenerator(final ExecutableRunner executableRunner, final String bazelExe, final BazelQueryXmlOutputParser parser, final File workspaceDir, final String bazelTarget); List<BazelExternalId> generate(final BazelExternalIdExtractionFullRule xPathRule); boolean isErrors(); String getErrorMessage(); }
@Test public void test() throws ExecutableRunnerException { final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class); final String bazelExe = "notUsed"; final XPathParser xPathParser = new XPathParser(); final BazelQueryXmlOutputParser parser = new BazelQueryXmlOutputParser(xPathParser); final File workspaceDir = new File("notUsed"); final String bazelTarget = " BazelExternalIdGenerator generator = new BazelExternalIdGenerator(executableRunner, bazelExe, parser, workspaceDir, bazelTarget); BazelExternalIdExtractionSimpleRule simpleRule = new BazelExternalIdExtractionSimpleRule("@.*:jar", "maven_jar", "artifact", ":"); BazelExternalIdExtractionFullRule xPathRule = RuleConverter.simpleToFull(simpleRule); final BazelVariableSubstitutor targetOnlyVariableSubstitutor = new BazelVariableSubstitutor(bazelTarget); ExecutableOutput executableOutputQueryForDependencies = new ExecutableOutput(0, "@org_apache_commons_commons_io Mockito.when(executableRunner.executeQuietly(workspaceDir, bazelExe, targetOnlyVariableSubstitutor.substitute(xPathRule.getTargetDependenciesQueryBazelCmdArguments()))).thenReturn(executableOutputQueryForDependencies); final BazelVariableSubstitutor dependencyVariableSubstitutorCommonsIo = new BazelVariableSubstitutor(bazelTarget, " final BazelVariableSubstitutor dependencyVariableSubstitutorGuava = new BazelVariableSubstitutor(bazelTarget, " ExecutableOutput executableOutputQueryCommonsIo = new ExecutableOutput(0, commonsIoXml, ""); ExecutableOutput executableOutputQueryGuava = new ExecutableOutput(0, guavaXml, ""); Mockito.when(executableRunner.executeQuietly(workspaceDir, bazelExe, dependencyVariableSubstitutorCommonsIo.substitute(xPathRule.getDependencyDetailsXmlQueryBazelCmdArguments()))).thenReturn(executableOutputQueryCommonsIo); Mockito.when(executableRunner.executeQuietly(workspaceDir, bazelExe, dependencyVariableSubstitutorGuava.substitute(xPathRule.getDependencyDetailsXmlQueryBazelCmdArguments()))).thenReturn(executableOutputQueryGuava); List<BazelExternalId> bazelExternalIds = generator.generate(xPathRule); assertEquals(2, bazelExternalIds.size()); assertEquals("org.apache.commons", bazelExternalIds.get(0).getGroup()); assertEquals("commons-io", bazelExternalIds.get(0).getArtifact()); assertEquals("1.3.2", bazelExternalIds.get(0).getVersion()); assertEquals("com.google.guava", bazelExternalIds.get(1).getGroup()); assertEquals("guava", bazelExternalIds.get(1).getArtifact()); assertEquals("18.0", bazelExternalIds.get(1).getVersion()); }
MavenCodeLocationPackager { boolean isLineRelevant(final String line) { final String editableLine = line; if (!doesLineContainSegmentsInOrder(line, "[", "INFO", "]")) { return false; } final int index = indexOfEndOfSegments(line, "[", "INFO", "]"); final String trimmedLine = editableLine.substring(index); if (StringUtils.isBlank(trimmedLine) || trimmedLine.contains("Downloaded") || trimmedLine.contains("Downloading")) { return false; } return true; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testIsLineRelevant() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertTrue(mavenCodeLocationPackager.isLineRelevant("weird garbage 3525356 [thingsINFO 346534623465] stuff")); assertTrue(mavenCodeLocationPackager.isLineRelevant("[thingsINFO 346534623465]stuff")); assertTrue(mavenCodeLocationPackager.isLineRelevant("[thingsINFO] stuff")); assertFalse(mavenCodeLocationPackager.isLineRelevant(" [INFO] ")); assertFalse(mavenCodeLocationPackager.isLineRelevant("weird garbage 3525356 [thingsINFO 346534623465]")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[thingsINFO 346534623465]")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[thingsINFO]")); assertFalse(mavenCodeLocationPackager.isLineRelevant(" [INFO]")); assertFalse(mavenCodeLocationPackager.isLineRelevant(" ")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[INFO] Downloaded")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[INFO] stuff and thingsDownloaded stuff and things")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[INFO] Downloading")); assertFalse(mavenCodeLocationPackager.isLineRelevant("[INFO] stuff and things Downloadingstuff and things")); }
MavenCodeLocationPackager { String trimLogLevel(final String line) { final String editableLine = line; final int index = indexOfEndOfSegments(line, "[", "INFO", "]"); String trimmedLine = editableLine.substring(index); if (trimmedLine.startsWith(" ")) { trimmedLine = trimmedLine.substring(1); } return trimmedLine; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testTrimLogLevel() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); String actualLine = ""; final String expectedValue = "thing"; actualLine = mavenCodeLocationPackager.trimLogLevel("weird garbage 3525356 [thingsINFO 346534623465]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel("[thingsINFO 346534623465]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel("[thingsINFO]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel(" [INFO] " + expectedValue); assertEquals(expectedValue, actualLine); }
MavenCodeLocationPackager { boolean isProjectSection(final String line) { return doesLineContainSegmentsInOrder(line, "---", "dependency", ":", "tree"); } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testIsProjectSection() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertFalse(mavenCodeLocationPackager.isProjectSection(" ")); assertFalse(mavenCodeLocationPackager.isProjectSection(" ")); assertFalse(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:")); assertFalse(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:other stuff")); assertFalse(mavenCodeLocationPackager.isProjectSection("maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("things --- stuff maven-dependency-plugin garbage:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("things --- stuff maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:tree")); assertTrue(mavenCodeLocationPackager.isProjectSection(" --- maven-dependency-plugin : tree")); }
MavenCodeLocationPackager { boolean isDependencyTreeUpdates(final String line) { if (line.contains("checking for updates")) { return true; } else { return false; } } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testIsDependencyTreeUpdates() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates("artifact com.google.guava:guava:jar:15.0:compile checking for updates from")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates(" artifact com.google.guava:guava: checking for updates")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates(" checking for updates artifact com.google.guava:guava: ")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates("checking for updates")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("com.google.guava:guava:jar:15.0:compile")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("+- com.google.guava:guava:jar:15.0:compile")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("| \\- com.google.guava:guava:jar:15.0:compile")); }
MavenCodeLocationPackager { boolean isGav(final String componentText) { final String debugMessage = String.format("%s does not look like a GAV we recognize", componentText); final String[] gavParts = componentText.split(":"); if (gavParts.length >= 4) { for (final String part : gavParts) { if (StringUtils.isBlank(part)) { logger.debug(debugMessage); return false; } } return true; } logger.debug(debugMessage); return false; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testIsGav() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertFalse(mavenCodeLocationPackager.isGav(" ")); assertFalse(mavenCodeLocationPackager.isGav(" ")); assertFalse(mavenCodeLocationPackager.isGav("::::")); assertFalse(mavenCodeLocationPackager.isGav(" : : : : ")); assertFalse(mavenCodeLocationPackager.isGav("group")); assertFalse(mavenCodeLocationPackager.isGav("group:artifact")); assertFalse(mavenCodeLocationPackager.isGav("group:artifact:version")); assertFalse(mavenCodeLocationPackager.isGav("group-artifact:type-classifier-version:scope-garbage")); assertFalse(mavenCodeLocationPackager.isGav("group:artifact::classifier:version: :garbage")); assertTrue(mavenCodeLocationPackager.isGav("group:artifact:type:version")); assertTrue(mavenCodeLocationPackager.isGav("group:artifact:type:classifier:version")); assertTrue(mavenCodeLocationPackager.isGav("group:artifact:type:classifier:version:scope")); assertTrue(mavenCodeLocationPackager.isGav("group:artifact:type:classifier:version:scope:garbage")); }
MavenCodeLocationPackager { int indexOfEndOfSegments(final String line, final String... segments) { int endOfSegments = -1; if (segments.length > 0) { endOfSegments = 0; } String editableLine = line; for (final String segment : segments) { final int index = editableLine.indexOf(segment); if (index == -1) { endOfSegments = -1; break; } endOfSegments += (index + segment.length()); editableLine = editableLine.substring(index + segment.length()); } return endOfSegments; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testIndexOfEndOfSegments() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertEquals(-1, mavenCodeLocationPackager.indexOfEndOfSegments("")); assertEquals(-1, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things")); assertEquals(-1, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "things", "and")); assertEquals(-1, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "things", "and", "stuff")); assertEquals(5, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "stuff")); assertEquals(9, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "stuff", "and")); assertEquals(16, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "stuff", "and", "things")); assertEquals(9, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "and")); assertEquals(16, mavenCodeLocationPackager.indexOfEndOfSegments("stuff and things", "things")); }
MavenCodeLocationPackager { boolean doesLineContainSegmentsInOrder(final String line, final String... segments) { Boolean lineContainsSegments = true; final int index = indexOfEndOfSegments(line, segments); if (index == -1) { lineContainsSegments = false; } return lineContainsSegments; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testDoesLineContainSegmentsInOrder() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things", "and")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things", "and", "stuff")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff", "and")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff", "and", "things")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "and")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things")); }
GoVendorExtractor { public Extraction extract(final File directory, final File vendorJsonFile) { try { final GoVendorJsonParser vendorJsonParser = new GoVendorJsonParser(externalIdFactory); final String vendorJsonContents = FileUtils.readFileToString(vendorJsonFile, StandardCharsets.UTF_8); logger.debug(vendorJsonContents); final DependencyGraph dependencyGraph = vendorJsonParser.parseVendorJson(gson, vendorJsonContents); final ExternalId externalId = externalIdFactory.createPathExternalId(Forge.GOLANG, directory.toString()); final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.GO_VENDOR, directory.toString(), externalId, dependencyGraph).build(); return new Extraction.Builder().success(codeLocation).build(); } catch (final Exception e) { return new Extraction.Builder().exception(e).build(); } } GoVendorExtractor(final Gson gson, final ExternalIdFactory externalIdFactory); Extraction extract(final File directory, final File vendorJsonFile); }
@Test public void test() { GoVendorExtractor extractor = new GoVendorExtractor(new Gson(), new ExternalIdFactory()); Extraction extraction = extractor.extract(new File("src/test/resources/go"), new File("src/test/resources/go/vendor/vendor.json")); DependencyGraph graph = extraction.codeLocations.get(0).getDependencyGraph(); assertEquals(2, graph.getRootDependencies().size()); boolean foundErrorsPkg = false; boolean foundMathPkg = false; for (Dependency dep : graph.getRootDependencies()) { if ("github.com/pkg/errors".equals(dep.name)) { foundErrorsPkg = true; assertEquals("github.com/pkg/errors", dep.externalId.name); assertEquals("059132a15dd08d6704c67711dae0cf35ab991756", dep.externalId.version); } if ("github.com/pkg/math".equals(dep.name)) { foundMathPkg = true; assertEquals("github.com/pkg/math", dep.externalId.name); assertEquals("f2ed9e40e245cdeec72c4b642d27ed4553f90667", dep.externalId.version); } } assertTrue(foundErrorsPkg); assertTrue(foundMathPkg); }
GoVendorJsonParser { public DependencyGraph parseVendorJson(final Gson gson, final String vendorJsonContents) { final MutableDependencyGraph graph = new MutableMapDependencyGraph(); GoVendorJsonData vendorJsonData = gson.fromJson(vendorJsonContents, GoVendorJsonData.class); logger.trace(String.format("vendorJsonData: %s", vendorJsonData)); for (GoVendorJsonPackageData pkg : vendorJsonData.getPackages()) { if (StringUtils.isNotBlank(pkg.getPath()) && StringUtils.isNotBlank(pkg.getRevision())) { final ExternalId dependencyExternalId = externalIdFactory.createNameVersionExternalId(Forge.GOLANG, pkg.getPath(), pkg.getRevision()); final Dependency dependency = new Dependency(pkg.getPath(), pkg.getRevision(), dependencyExternalId); logger.trace(String.format("dependency: %s", dependency.externalId.toString())); graph.addChildToRoot(dependency); } else { logger.debug(String.format("Omitting package path:'%s', revision:'%s' (one or both of path, revision is/are missing)", pkg.getPath(), pkg.getRevision())); } } return graph; } GoVendorJsonParser(final ExternalIdFactory externalIdFactory); DependencyGraph parseVendorJson(final Gson gson, final String vendorJsonContents); }
@Test public void test() throws IOException { ExternalIdFactory externalIdFactory = new ExternalIdFactory(); GoVendorJsonParser parser = new GoVendorJsonParser(externalIdFactory); File vendorJsonFile = new File("src/test/resources/go/vendor/vendor.json"); String vendorJsonContents = FileUtils.readFileToString(vendorJsonFile, StandardCharsets.UTF_8); DependencyGraph graph = parser.parseVendorJson(new Gson(), vendorJsonContents); assertEquals(2, graph.getRootDependencies().size()); boolean foundErrorsPkg = false; boolean foundMathPkg = false; for (Dependency dep : graph.getRootDependencies()) { if ("github.com/pkg/errors".equals(dep.name)) { foundErrorsPkg = true; assertEquals("github.com/pkg/errors", dep.externalId.name); assertEquals("059132a15dd08d6704c67711dae0cf35ab991756", dep.externalId.version); } if ("github.com/pkg/math".equals(dep.name)) { foundMathPkg = true; assertEquals("github.com/pkg/math", dep.externalId.name); assertEquals("f2ed9e40e245cdeec72c4b642d27ed4553f90667", dep.externalId.version); } } assertTrue(foundErrorsPkg); assertTrue(foundMathPkg); }
GopkgLockParser { public DependencyGraph parseDepLock(final String depLockContents) { final MutableDependencyGraph graph = new MutableMapDependencyGraph(); final GopkgLock gopkgLock = new Toml().read(depLockContents).to(GopkgLock.class); for (final Project project : gopkgLock.getProjects()) { if (project != null) { final NameVersion projectNameVersion = createProjectNameVersion(project); project.getPackages().stream() .map(packageName -> createDependencyName(projectNameVersion.getName(), packageName)) .map(dependencyName -> createGoDependency(dependencyName, projectNameVersion.getVersion())) .forEach(graph::addChildToRoot); } } return graph; } GopkgLockParser(final ExternalIdFactory externalIdFactory); DependencyGraph parseDepLock(final String depLockContents); }
@Test public void gopkgParserTest() throws IOException { final GopkgLockParser gopkgLockParser = new GopkgLockParser(new ExternalIdFactory()); final String gopkgLockContents = IOUtils.toString(getClass().getResourceAsStream("/go/Gopkg.lock"), StandardCharsets.UTF_8); final DependencyGraph dependencyGraph = gopkgLockParser.parseDepLock(gopkgLockContents); Assert.assertNotNull(dependencyGraph); DependencyGraphResourceTestUtil.assertGraph("/go/Go_GopkgExpected_graph.json", dependencyGraph); }
BazelVariableSubstitutor { public List<String> substitute(final List<String> origStrings) { final List<String> modifiedStrings = new ArrayList<>(origStrings.size()); for (String origString : origStrings) { modifiedStrings.add(substitute(origString)); } return modifiedStrings; } BazelVariableSubstitutor(final String bazelTarget); BazelVariableSubstitutor(final String bazelTarget, final String bazelTargetDependencyId); List<String> substitute(final List<String> origStrings); }
@Test public void testTargetOnly() { BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor(" final List<String> origArgs = new ArrayList<>(); origArgs.add("query"); origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))"); final List<String> adjustedArgs = substitutor.substitute(origArgs); assertEquals(2, adjustedArgs.size()); assertEquals("query", adjustedArgs.get(0)); assertEquals("filter(\"@.*:jar\", deps( } @Test public void testBoth() { BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor(" final List<String> origArgs = new ArrayList<>(); origArgs.add("query"); origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))"); origArgs.add("kind(maven_jar, ${detect.bazel.target.dependency})"); final List<String> adjustedArgs = substitutor.substitute(origArgs); assertEquals(3, adjustedArgs.size()); assertEquals("query", adjustedArgs.get(0)); assertEquals("filter(\"@.*:jar\", deps( assertEquals("kind(maven_jar, }
VndrParser { public VndrParser(final ExternalIdFactory externalIdFactory) { this.externalIdFactory = externalIdFactory; } VndrParser(final ExternalIdFactory externalIdFactory); DependencyGraph parseVendorConf(final List<String> vendorConfContents); public ExternalIdFactory externalIdFactory; }
@Test public void vndrParserTest() throws IOException { final TestUtil testUtil = new TestUtil(); final VndrParser vndrParser = new VndrParser(new ExternalIdFactory()); final String text = testUtil.getResourceAsUTF8String("/go/vendor.conf"); final List<String> vendorConfContents = Arrays.asList(text.split("\r?\n")); final DependencyGraph dependencyGraph = vndrParser.parseVendorConf(vendorConfContents); Assert.assertNotNull(dependencyGraph); DependencyGraphResourceTestUtil.assertGraph("/go/Go_VndrExpected_graph.json", dependencyGraph); }
BitbakeListTasksParser { public Optional<String> parseTargetArchitecture(final String standardOutput) { return Arrays.stream(standardOutput.split(System.lineSeparator())) .filter(this::lineContainsArchitecture) .map(this::getArchitectureFromLine) .findFirst(); } Optional<String> parseTargetArchitecture(final String standardOutput); }
@Test public void parseTargetArchitectureTest() { final TestUtil testUtil = new TestUtil(); final String listtaskOutput = testUtil.getResourceAsUTF8String("/bitbake/listtasks_output.txt"); final BitbakeListTasksParser bitbakeListTasksParser = new BitbakeListTasksParser(); final Optional<String> architecture = bitbakeListTasksParser.parseTargetArchitecture(listtaskOutput); assert architecture.isPresent(); System.out.println(architecture.get()); assert architecture.get().equals("i586-poky-linux"); }
GraphParserTransformer { public DependencyGraph transform(final GraphParser graphParser, final String targetArchitecture) { final Map<String, GraphNode> nodes = graphParser.getNodes(); final Map<String, GraphEdge> edges = graphParser.getEdges(); final LazyExternalIdDependencyGraphBuilder graphBuilder = new LazyExternalIdDependencyGraphBuilder(); for (final GraphNode graphNode : nodes.values()) { final String name = getNameFromNode(graphNode); final DependencyId dependencyId = new NameDependencyId(name); final Optional<String> version = getVersionFromNode(graphNode); if (version.isPresent()) { final ExternalId externalId = new ExternalId(Forge.YOCTO); externalId.name = name; externalId.version = version.get(); externalId.architecture = targetArchitecture; graphBuilder.setDependencyInfo(dependencyId, name, version.get(), externalId); } graphBuilder.addChildToRoot(dependencyId); } for (final GraphEdge graphEdge : edges.values()) { final DependencyId node1 = new NameDependencyId(getNameFromNode(graphEdge.getNode1())); final DependencyId node2 = new NameDependencyId(getNameFromNode(graphEdge.getNode2())); graphBuilder.addParentWithChild(node1, node2); } return graphBuilder.build(); } DependencyGraph transform(final GraphParser graphParser, final String targetArchitecture); }
@Test public void transform() throws IOException { final GraphParserTransformer graphParserTransformer = new GraphParserTransformer(); final InputStream inputStream = new ClassPathResource("/bitbake/recipe-depends.dot").getInputStream(); final GraphParser graphParser = new GraphParser(inputStream); final DependencyGraph dependencyGraph = graphParserTransformer.transform(graphParser, "i586-poky-linux"); assert dependencyGraph.getRootDependencies().size() == 480; }
YarnListParser extends BaseYarnParser { public DependencyGraph parseYarnList(final List<String> yarnLockText, final List<String> yarnListAsList) { final MutableDependencyGraph graph = new MutableMapDependencyGraph(); final DependencyHistory history = new DependencyHistory(); final Map<String, String> yarnLockVersionMap = yarnLockParser.getYarnLockResolvedVersionMap(yarnLockText); for (final String line : yarnListAsList) { final String lowerCaseLine = line.toLowerCase().trim(); final String cleanedLine = line.replaceAll(NTH_DEPENDENCY_PREFIX, "").replaceAll(INNER_LEVEL_CHARACTER, "").replaceAll(LAST_DEPENDENCY_PREFIX, ""); if (!cleanedLine.contains("@") || lowerCaseLine.startsWith("yarn list") || lowerCaseLine.startsWith("done in") || lowerCaseLine.startsWith("warning")) { continue; } final Dependency dependency = parseDependencyFromLine(cleanedLine, yarnLockVersionMap); final int lineLevel = getLineLevel(cleanedLine); try { history.clearDependenciesDeeperThan(lineLevel); } catch (final IllegalStateException e) { logger.warn(String.format("Problem parsing line '%s': %s", line, e.getMessage())); } if (history.isEmpty()) { graph.addChildToRoot(dependency); } else { graph.addChildWithParents(dependency, history.getLastDependency()); } history.add(dependency); } return graph; } YarnListParser(final ExternalIdFactory externalIdFactory, final YarnLockParser yarnLockParser); DependencyGraph parseYarnList(final List<String> yarnLockText, final List<String> yarnListAsList); Dependency parseDependencyFromLine(final String cleanedLine, final Map<String, String> yarnLockVersionMap); static final String LAST_DEPENDENCY_PREFIX; static final String NTH_DEPENDENCY_PREFIX; static final String INNER_LEVEL_CHARACTER; }
@Test public void parseYarnListTest() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("async@~0.9.0:"); designedYarnLock.add(" version \"0.9.2\""); designedYarnLock.add(" resolved \"http: designedYarnLock.add(" dependencies:"); designedYarnLock.add(" minimist \"0.0.8\""); designedYarnLock.add(""); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"0.0.8\""); designedYarnLock.add(" resolved \"http: final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final String yarnListText = testUtil.getResourceAsUTF8String("/yarn/yarn.list.txt"); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, Arrays.asList(yarnListText.split(System.lineSeparator()))); DependencyGraphResourceTestUtil.assertGraph("/yarn/list_expected_graph.json", dependencyGraph); } @Test public void parseYarnListWithResolvableVersions() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(" resolved \"http: designedYarnLock.add(" dependencies:"); designedYarnLock.add(" co \"^4.6.0\""); designedYarnLock.add(" tr46 \"~0.0.3\""); designedYarnLock.add(" cssstyle \">= 0.2.37 < 0.3.0\""); designedYarnLock.add(""); designedYarnLock.add("co@^4.6.0:"); designedYarnLock.add(" version \"4.6.0\""); designedYarnLock.add(" resolved \"http: designedYarnLock.add(" dependencies:"); designedYarnLock.add(" hoek \"4.x.x\""); designedYarnLock.add(""); designedYarnLock.add("tr46@~0.0.3:"); designedYarnLock.add(" version \"0.0.3\""); designedYarnLock.add(" resolved \"http: designedYarnLock.add(""); designedYarnLock.add("\"cssstyle@>= 0.2.37 < 0.3.0\":"); designedYarnLock.add(" version \"0.2.37\""); designedYarnLock.add(" resolved \"http: designedYarnLock.add(" dependencies:"); designedYarnLock.add(" cssom \"0.3.x\""); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"4.2.1\""); designedYarnLock.add(" resolved \"http: final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final String yarnListText = testUtil.getResourceAsUTF8String("/yarn/yarn.list.res.txt"); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, Arrays.asList(yarnListText.split(System.lineSeparator()))); DependencyGraphResourceTestUtil.assertGraph("/yarn/list_expected_graph_2.json", dependencyGraph); } @Test public void testDependencyInYarnListAndNotInLock() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); final List<String> testLines = new ArrayList<>(); testLines.add("yarn list v1.5.1"); testLines.add("├─ [email protected]"); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, testLines); final List<ExternalId> tempList = new ArrayList<>(dependencyGraph.getRootDependencyExternalIds()); assertEquals(1, tempList.size()); assertListContainsDependency("abab", "1.0.4", tempList); } @Test public void testThatYarnListLineAtBeginningIsIgnored() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); final List<String> testLines = new ArrayList<>(); testLines.add("yarn list v1.5.1"); testLines.add("├─ [email protected]"); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, testLines); final List<ExternalId> tempList = new ArrayList<>(dependencyGraph.getRootDependencyExternalIds()); assertNotNull(tempList.get(0)); assertEquals(1, tempList.size()); } @Test public void testThatYarnListWithOnlyTopLevelDependenciesIsParsedCorrectly() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); final List<String> testLines = new ArrayList<>(); testLines.add("├─ [email protected]"); testLines.add("└─ [email protected]"); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, testLines); final List<ExternalId> tempList = new ArrayList<>(dependencyGraph.getRootDependencyExternalIds()); assertListContainsDependency("esprima", "3.1.3", tempList); assertListContainsDependency("extsprintf", "1.3.0", tempList); } @Test public void testThatYarnListWithGrandchildIsParsedCorrectly() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); designedYarnLock.add("camelcase@^3.0.0:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); final List<String> testLines = new ArrayList<>(); testLines.add("├─ [email protected]"); testLines.add("│ └─ camelcase@^3.0.0"); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, testLines); final List<ExternalId> tempList = new ArrayList<>(dependencyGraph.getRootDependencyExternalIds()); List<ExternalId> kidsList = new ArrayList<>(); for (int i = 0; i < tempList.size(); i++) { if ("yargs-parser".equals(tempList.get(i).name)) { kidsList = new ArrayList<>(dependencyGraph.getChildrenExternalIdsForParent(tempList.get(i))); } } assertListContainsDependency("yargs-parser", "4.2.1", tempList); assertListContainsDependency("camelcase", "5.5.2", kidsList); } @Test public void testThatYarnListWithGreatGrandchildrenIsParsedCorrectly() { final List<String> designedYarnLock = new ArrayList<>(); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); designedYarnLock.add("camelcase@^3.0.0:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); designedYarnLock.add("[email protected]:"); designedYarnLock.add(" version \"5.5.2\""); designedYarnLock.add(""); final List<String> testLines = new ArrayList<>(); testLines.add("├─ [email protected]"); testLines.add("│ └─ camelcase@^3.0.0"); testLines.add("│ │ └─ [email protected]"); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final YarnLockParser yarnLockParser = new YarnLockParser(); final YarnListParser yarnListParser = new YarnListParser(externalIdFactory, yarnLockParser); final DependencyGraph dependencyGraph = yarnListParser.parseYarnList(designedYarnLock, testLines); final List<ExternalId> rootDependencies = new ArrayList<>(dependencyGraph.getRootDependencyExternalIds()); assertListContainsDependency("yargs-parser", "4.2.1", rootDependencies); final List<ExternalId> childDependencies = new ArrayList<>(dependencyGraph.getChildrenExternalIdsForParent(rootDependencies.get(0))); assertListContainsDependency("camelcase", "5.5.2", childDependencies); final List<ExternalId> grandchildDependencies = new ArrayList<>(dependencyGraph.getChildrenExternalIdsForParent(childDependencies.get(0))); assertListContainsDependency("ms", "0.7.2", grandchildDependencies); }
YarnLockParser extends BaseYarnParser { public Map<String, String> getYarnLockResolvedVersionMap(final List<String> yarnLockFileAsList) { final Map<String, String> yarnLockResolvedVersions = new HashMap<>(); final List<String> fuzzyIds = new ArrayList<>(); for (final String line : yarnLockFileAsList) { if (StringUtils.isBlank(line) || line.trim().startsWith(COMMENT_PREFIX)) { continue; } final String trimmedLine = line.trim(); final int level = getLineLevel(line); if (level == 0) { fuzzyIds.addAll(getFuzzyIdsFromLine(line)); } else if (level == 1 && trimmedLine.startsWith(VERSION_PREFIX)) { final String resolvedVersion = trimmedLine.substring(VERSION_PREFIX.length(), trimmedLine.lastIndexOf(VERSION_SUFFIX)); fuzzyIds.stream().forEach(fuzzyId -> yarnLockResolvedVersions.put(fuzzyId, resolvedVersion)); fuzzyIds.clear(); } } return yarnLockResolvedVersions; } Map<String, String> getYarnLockResolvedVersionMap(final List<String> yarnLockFileAsList); static final String COMMENT_PREFIX; static final String VERSION_PREFIX; static final String VERSION_SUFFIX; }
@Test public void testThatYarnLockIsParsedCorrectlyToMap() { final List<String> yarnLockText = new ArrayList<>(); yarnLockText.add("# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY."); yarnLockText.add("# yarn lockfile v1"); yarnLockText.add(""); yarnLockText.add(""); yarnLockText.add("[email protected]:"); yarnLockText.add(" version \"0.9.0\""); yarnLockText.add(" resolved \"http: yarnLockText.add("[email protected]:"); yarnLockText.add(" version \"1.0.3\""); yarnLockText.add(" resolved \"http: final YarnLockParser yarnLockParser = new YarnLockParser(); final Map<String, String> lockResolvedVersions = yarnLockParser.getYarnLockResolvedVersionMap(yarnLockText); assertEquals("0.9.0", lockResolvedVersions.get("[email protected]")); assertEquals("1.0.3", lockResolvedVersions.get("[email protected]")); } @Test public void testThatYarnLockVersionsResolveAsExpected() { final List<String> yarnLockText = new ArrayList<>(); yarnLockText.add("http-proxy@^1.8.1:"); yarnLockText.add(" version \"1.16.2\""); yarnLockText.add(" resolved \"http: yarnLockText.add(" dependencies:"); yarnLockText.add(" eventemitter3 \"1.x.x\""); yarnLockText.add(" requires-port \"1.x.x\""); yarnLockText.add("http-server@^0.9.0:"); yarnLockText.add(" version \"0.9.0\""); yarnLockText.add(" resolved \"http: final YarnLockParser yarnLockParser = new YarnLockParser(); final Map<String, String> lockResolvedVersions = yarnLockParser.getYarnLockResolvedVersionMap(yarnLockText); assertEquals("1.16.2", lockResolvedVersions.get("http-proxy@^1.8.1")); assertEquals("0.9.0", lockResolvedVersions.get("http-server@^0.9.0")); } @Test public void testThatMultipleDepsPerLineCanBeHandledCorrectly() { final List<String> yarnLockText = new ArrayList<>(); yarnLockText.add("debug@2, [email protected], debug@^2.2.0, debug@^2.3.3, debug@~2.6.4, debug@~2.6.6:"); yarnLockText.add(" version \"2.6.9\""); yarnLockText.add(" resolved \"http: yarnLockText.add(" dependencies:"); yarnLockText.add(" ms \"2.0.0\""); final YarnLockParser yarnLockParser = new YarnLockParser(); final Map<String, String> lockResolvedVersions = yarnLockParser.getYarnLockResolvedVersionMap(yarnLockText); assertEquals("2.6.9", lockResolvedVersions.get("debug@2")); assertEquals("2.6.9", lockResolvedVersions.get("[email protected]")); assertEquals("2.6.9", lockResolvedVersions.get("debug@^2.2.0")); assertEquals("2.6.9", lockResolvedVersions.get("debug@^2.3.3")); assertEquals("2.6.9", lockResolvedVersions.get("debug@~2.6.4")); assertEquals("2.6.9", lockResolvedVersions.get("debug@~2.6.6")); } @Test public void testThatDependenciesWithQuotesAreResolvedCorrectly() { final List<String> yarnLockText = new ArrayList<>(); yarnLockText.add("\"cssstyle@>= 0.2.37 < 0.3.0\":"); yarnLockText.add(" version \"0.2.37\""); yarnLockText.add(" resolved \"http: yarnLockText.add(" dependencies:"); yarnLockText.add(" cssom \"0.3.x\""); final YarnLockParser yarnLockParser = new YarnLockParser(); final Map<String, String> lockResolvedVersions = yarnLockParser.getYarnLockResolvedVersionMap(yarnLockText); assertEquals("0.2.37", lockResolvedVersions.get("cssstyle@>= 0.2.37 < 0.3.0")); }
PipInspectorTreeParser { public Optional<PipParseResult> parse(final List<String> pipInspectorOutputAsList, final String sourcePath) { PipParseResult parseResult = null; final MutableDependencyGraph graph = new MutableMapDependencyGraph(); final DependencyHistory history = new DependencyHistory(); Dependency project = null; for (final String line : pipInspectorOutputAsList) { final String trimmedLine = StringUtils.trimToEmpty(line); if (StringUtils.isEmpty(trimmedLine) || !trimmedLine.contains(SEPARATOR) || trimmedLine.startsWith(UNKNOWN_REQUIREMENTS_PREFIX) || trimmedLine.startsWith(UNPARSEABLE_REQUIREMENTS_PREFIX) || trimmedLine.startsWith( UNKNOWN_PACKAGE_PREFIX)) { parseErrorsFromLine(trimmedLine); continue; } final Dependency currentDependency = parseDependencyFromLine(trimmedLine, sourcePath); final int lineLevel = getLineLevel(trimmedLine); try { history.clearDependenciesDeeperThan(lineLevel); } catch (final IllegalStateException e) { logger.warn(String.format("Problem parsing line '%s': %s", line, e.getMessage())); } if (project == null) { project = currentDependency; } else if (project.equals(history.getLastDependency())) { graph.addChildToRoot(currentDependency); } else if (history.isEmpty()) { graph.addChildToRoot(currentDependency); } else { graph.addChildWithParents(currentDependency, history.getLastDependency()); } history.add(currentDependency); } if (project != null) { final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.PIP, sourcePath, project.externalId, graph).build(); parseResult = new PipParseResult(project.name, project.version, codeLocation); } return Optional.ofNullable(parseResult); } PipInspectorTreeParser(final ExternalIdFactory externalIdFactory); Optional<PipParseResult> parse(final List<String> pipInspectorOutputAsList, final String sourcePath); static final String SEPARATOR; static final String UNKNOWN_PROJECT_NAME; static final String UNKNOWN_PROJECT_VERSION; static final String UNKNOWN_REQUIREMENTS_PREFIX; static final String UNPARSEABLE_REQUIREMENTS_PREFIX; static final String UNKNOWN_PACKAGE_PREFIX; static final String INDENTATION; }
@Test public void indendtationAndLineToNodeTest() { final List<String> pipInspectorOutput = new ArrayList<>(); pipInspectorOutput.add("projectName==projectVersionName"); pipInspectorOutput.add(" appnope==0.1.0"); pipInspectorOutput.add(" decorator==4.3.0"); pipInspectorOutput.add(" dj-database-url==0.5.0"); pipInspectorOutput.add(" Django==1.10.4"); pipInspectorOutput.add(" ipython==5.1.0"); pipInspectorOutput.add(" pexpect==4.6.0"); pipInspectorOutput.add(" ptyprocess==0.6.0"); pipInspectorOutput.add(" appnope==0.1.0"); pipInspectorOutput.add(" setuptools==40.0.0"); pipInspectorOutput.add(" simplegeneric==0.8.1"); pipInspectorOutput.add(" decorator==4.3.0"); pipInspectorOutput.add(" pickleshare==0.7.4"); pipInspectorOutput.add(" traitlets==4.3.2"); pipInspectorOutput.add(" six==1.11.0"); pipInspectorOutput.add(" ipython-genutils==0.2.0"); pipInspectorOutput.add(" decorator==4.3.0"); pipInspectorOutput.add(" Pygments==2.2.0"); pipInspectorOutput.add(" prompt-toolkit==1.0.15"); pipInspectorOutput.add(" six==1.11.0"); pipInspectorOutput.add(" wcwidth==0.1.7"); pipInspectorOutput.add(" ipython-genutils==0.2.0"); pipInspectorOutput.add(" mypackage==5.2.0"); pipInspectorOutput.add(" pexpect==4.6.0"); pipInspectorOutput.add(" ptyprocess==0.6.0"); pipInspectorOutput.add(" pickleshare==0.7.4"); pipInspectorOutput.add(" prompt-toolkit==1.0.15"); pipInspectorOutput.add(" six==1.11.0"); pipInspectorOutput.add(" wcwidth==0.1.7"); pipInspectorOutput.add(" psycopg2==2.7.5"); pipInspectorOutput.add(" ptyprocess==0.6.0"); pipInspectorOutput.add(" Pygments==2.2.0"); pipInspectorOutput.add(" simplegeneric==0.8.1"); pipInspectorOutput.add(" six==1.11.0"); pipInspectorOutput.add(" traitlets==4.3.2"); pipInspectorOutput.add(" six==1.11.0"); pipInspectorOutput.add(" ipython-genutils==0.2.0"); pipInspectorOutput.add(" decorator==4.3.0"); pipInspectorOutput.add(" wcwidth==0.1.7"); final Optional<PipParseResult> validParse = parser.parse(pipInspectorOutput, ""); Assert.assertTrue(validParse.isPresent()); Assert.assertTrue(validParse.get().getProjectName().equals("projectName")); Assert.assertTrue(validParse.get().getProjectVersion().equals("projectVersionName")); } @Test public void invalidParseTest() { final List<String> invalidText = new ArrayList<>(); invalidText.add("i am not a valid file"); invalidText.add("the status should be optional.empty()"); final Optional<PipParseResult> invalidParse = parser.parse(invalidText, ""); Assert.assertFalse(invalidParse.isPresent()); } @Test public void errorTest() { final List<String> invalidText = new ArrayList<>(); invalidText.add(PipInspectorTreeParser.UNKNOWN_PACKAGE_PREFIX + "probably_an_internal_dependency_PY"); invalidText.add(PipInspectorTreeParser.UNPARSEABLE_REQUIREMENTS_PREFIX + "/not/a/real/path/encrypted/requirements.txt"); invalidText.add(PipInspectorTreeParser.UNKNOWN_REQUIREMENTS_PREFIX + "/not/a/real/path/requirements.txt"); final Optional<PipParseResult> invalidParse = parser.parse(invalidText, ""); Assert.assertFalse(invalidParse.isPresent()); }
ClangCompileCommandParser { public String getCompilerCommand(final String origCompileCommand) { final String[] parts = origCompileCommand.trim().split("\\s+"); return parts[0]; } String getCompilerCommand(final String origCompileCommand); List<String> getCompilerArgsForGeneratingDepsMkFile(final String origCompileCommand, final String depsMkFilePath, final Map<String, String> optionOverrides); }
@Test public void testGetCompilerCmd() { ClangCompileCommandParser compileCommandParser = new ClangCompileCommandParser(); Map<String, String> optionOverrides = new HashMap<>(1); optionOverrides.put("-o", "/dev/null"); String compilerCommand = compileCommandParser.getCompilerCommand( "g++ -DDOUBLEQUOTED=\"A value for the compiler\" -DSINGLEQUOTED='Another value for the compiler' file.c -o file.o"); assertEquals("g++", compilerCommand); }
ClangCompileCommandParser { public List<String> getCompilerArgsForGeneratingDepsMkFile(final String origCompileCommand, final String depsMkFilePath, final Map<String, String> optionOverrides) { logger.trace(String.format("origCompileCommand : %s", origCompileCommand)); String quotesRemovedCompileCommand = escapeQuotedWhitespace(origCompileCommand.trim()); logger.trace(String.format("quotesRemovedCompileCommand: %s", quotesRemovedCompileCommand)); StringTokenizer tokenizer = new StringTokenizer(quotesRemovedCompileCommand); tokenizer.setQuoteMatcher(StringMatcherFactory.INSTANCE.quoteMatcher()); final List<String> argList = new ArrayList<>(); String lastPart = ""; int partIndex = 0; while (tokenizer.hasNext()) { String part = unEscapeDoubleQuotes(restoreWhitespace(tokenizer.nextToken())); if (partIndex > 0) { String optionValueOverride = null; for (String optionToOverride : optionOverrides.keySet()) { if (optionToOverride.equals(lastPart)) { optionValueOverride = optionOverrides.get(optionToOverride); } } if (optionValueOverride != null) { argList.add(optionValueOverride); } else { argList.add(part); } } lastPart = part; partIndex++; } argList.add("-M"); argList.add("-MF"); argList.add(depsMkFilePath); return argList; } String getCompilerCommand(final String origCompileCommand); List<String> getCompilerArgsForGeneratingDepsMkFile(final String origCompileCommand, final String depsMkFilePath, final Map<String, String> optionOverrides); }
@Test public void testGetCompilerArgs() { ClangCompileCommandParser compileCommandParser = new ClangCompileCommandParser(); Map<String, String> optionOverrides = new HashMap<>(1); optionOverrides.put("-o", "/dev/null"); List<String> result = compileCommandParser.getCompilerArgsForGeneratingDepsMkFile( "g++ -DDOUBLEQUOTED=\"A value for the compiler\" -DSINGLEQUOTED='Another value for the compiler' file.c -o file.o", "/testMkFilePath", optionOverrides); for (String part : result) { System.out.printf("compiler arg: %s\n", part); } assertEquals(8, result.size()); int i=0; assertEquals("-DDOUBLEQUOTED=A value for the compiler", result.get(i++)); assertEquals("-DSINGLEQUOTED=Another value for the compiler", result.get(i++)); assertEquals("file.c", result.get(i++)); assertEquals("-o", result.get(i++)); assertEquals("/dev/null", result.get(i++)); assertEquals("-M", result.get(i++)); assertEquals("-MF", result.get(i++)); assertEquals("/testMkFilePath", result.get(i++)); } @Test public void testGetCompilerArgsFromJsonFile() throws IOException { final List<CompileCommand> compileCommands = CompileCommandsJsonFile.parseJsonCompilationDatabaseFile(new Gson(), new File("src/test/resources/clang/compile_commands.json")); ClangCompileCommandParser compileCommandParser = new ClangCompileCommandParser(); Map<String, String> optionOverrides = new HashMap<>(1); optionOverrides.put("-o", "/dev/null"); List<String> result = compileCommandParser.getCompilerArgsForGeneratingDepsMkFile( compileCommands.get(0).getCommand(), "/testMkFilePath", optionOverrides); for (String part : result) { System.out.printf("compiler arg: %s\n", part); } verifyResults(result); } @Test public void testGetCompilerArgsFromJsonFileUsingArgs() throws IOException { final List<CompileCommand> compileCommands = CompileCommandsJsonFile.parseJsonCompilationDatabaseFile(new Gson(), new File("src/test/resources/clang/compile_commands_args.json")); ClangCompileCommandParser compileCommandParser = new ClangCompileCommandParser(); Map<String, String> optionOverrides = new HashMap<>(1); optionOverrides.put("-o", "/dev/null"); List<String> result = compileCommandParser.getCompilerArgsForGeneratingDepsMkFile( compileCommands.get(0).getCommand(), "/testMkFilePath", optionOverrides); for (String part : result) { System.out.printf("compiler arg: %s\n", part); } verifyResults(result); }
CodeLocationNameGenerator { public String createScanCodeLocationName(final String sourcePath, final String scanTargetPath, final String projectName, final String projectVersionName, final String prefix, final String suffix) { final String pathPiece = cleanScanTargetPath(scanTargetPath, sourcePath); final String codeLocationTypeString = CodeLocationNameType.SCAN.toString().toLowerCase(); final List<String> fileCodeLocationNamePieces = Arrays.asList(pathPiece, projectName, projectVersionName); final List<String> fileCodeLocationEndPieces = Arrays.asList(codeLocationTypeString); return createCodeLocationName(prefix, fileCodeLocationNamePieces, suffix, fileCodeLocationEndPieces); } CodeLocationNameGenerator(final DetectFileFinder detectFileFinder); String createBomCodeLocationName(final String detectSourcePath, final String sourcePath, final ExternalId externalId, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerCodeLocationName(final String sourcePath, final String projectName, final String projectVersionName, final String dockerImage, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerScanCodeLocationName(final String dockerTarFilename, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createScanCodeLocationName(final String sourcePath, final String scanTargetPath, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createBinaryScanCodeLocationName(final String filename, final String projectName, final String projectVersionName, final String prefix, final String suffix); static final int MAXIMUM_CODE_LOCATION_NAME_LENGTH; }
@Test public void testScanCodeLocationName() { final String expected = "hub-common-rest/target/hub-common-rest/2.5.1-SNAPSHOT scan"; final DetectFileFinder detectFileFinder = mock(DetectFileFinder.class); when(detectFileFinder.extractFinalPieceFromPath("/Users/ekerwin/Documents/source/integration/hub-common-rest")).thenReturn("hub-common-rest"); final CodeLocationNameGenerator codeLocationNameGenerator = new CodeLocationNameGenerator(detectFileFinder); final String sourcePath = "/Users/ekerwin/Documents/source/integration/hub-common-rest"; final String scanTargetPath = "/Users/ekerwin/Documents/source/integration/hub-common-rest/target"; final String projectName = "hub-common-rest"; final String projectVersionName = "2.5.1-SNAPSHOT"; final String prefix = ""; final String suffix = ""; final String actual = codeLocationNameGenerator.createScanCodeLocationName(sourcePath, scanTargetPath, projectName, projectVersionName, prefix, suffix); assertEquals(expected, actual); }
ClangExtractor { public Extraction extract(final ClangLinuxPackageManager pkgMgr, final File givenDir, final int depth, final ExtractionId extractionId, final File jsonCompilationDatabaseFile) { try { logger.info(String.format("Analyzing %s", jsonCompilationDatabaseFile.getAbsolutePath())); final File rootDir = fileFinder.findContainingDir(givenDir, depth); final File outputDirectory = directoryManager.getExtractionOutputDirectory(extractionId); logger.debug(String.format("extract() called; compileCommandsJsonFilePath: %s", jsonCompilationDatabaseFile.getAbsolutePath())); final Set<File> unManagedDependencyFiles = ConcurrentHashMap.newKeySet(64); final List<CompileCommand> compileCommands = CompileCommandsJsonFile.parseJsonCompilationDatabaseFile(gson, jsonCompilationDatabaseFile); final List<Dependency> bdioComponents = compileCommands.parallelStream() .flatMap(compileCommandToDependencyFilePathsConverter(outputDirectory)) .collect(Collectors.toSet()).parallelStream() .filter(StringUtils::isNotBlank) .map(File::new) .filter(fileIsNewPredicate()) .flatMap(dependencyFileToLinuxPackagesConverter(rootDir, unManagedDependencyFiles, pkgMgr)) .collect(Collectors.toSet()).parallelStream() .flatMap(linuxPackageToBdioComponentsConverter(pkgMgr)) .collect(Collectors.toList()); final DetectCodeLocation detectCodeLocation = codeLocationAssembler.generateCodeLocation(pkgMgr.getDefaultForge(), rootDir, bdioComponents); logSummary(bdioComponents, unManagedDependencyFiles); return new Extraction.Builder().success(detectCodeLocation).build(); } catch (final Exception e) { return new Extraction.Builder().exception(e).build(); } } ClangExtractor(final DetectConfiguration detectConfiguration, final ExecutableRunner executableRunner, final Gson gson, final DetectFileFinder fileFinder, final DirectoryManager directoryManager, final DependenciesListFileManager dependenciesListFileManager, final CodeLocationAssembler codeLocationAssembler); Extraction extract(final ClangLinuxPackageManager pkgMgr, final File givenDir, final int depth, final ExtractionId extractionId, final File jsonCompilationDatabaseFile); }
@Test public void testSimple() throws ExecutableRunnerException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final CompileCommand compileCommandWrapper = createCompileCommand("src/test/resources/clang/source/hello_world.cpp", "gcc hello_world.cpp", null); final Set<String> dependencyFilePaths = createDependencyFilePaths(new File("/usr/include/nonexistentfile1.h"), new File("src/test/resources/clang/source/myinclude.h")); final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class); final DirectoryManager directoryManager = Mockito.mock(DirectoryManager.class); final DependenciesListFileManager dependenciesListFileManager = Mockito.mock(DependenciesListFileManager.class); Mockito.when(dependenciesListFileManager.generateDependencyFilePaths(outputDir, compileCommandWrapper, true)).thenReturn(dependencyFilePaths); Mockito.when(executableRunner.executeFromDirQuietly(Mockito.any(File.class), Mockito.anyString(), Mockito.anyList())).thenReturn(new ExecutableOutput(0, "", "")); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final CodeLocationAssembler codeLocationAssembler = new CodeLocationAssembler(externalIdFactory); final ClangExtractor extractor = new ClangExtractor(null, executableRunner, gson, new DetectFileFinder(), directoryManager, dependenciesListFileManager, codeLocationAssembler); final ClangLinuxPackageManager pkgMgr = Mockito.mock(ClangLinuxPackageManager.class); final File givenDir = new File("src/test/resources/clang/source/build"); final int depth = 1; final ExtractionId extractionId = new ExtractionId(DetectorType.CLANG, EXTRACTION_ID); final File jsonCompilationDatabaseFile = new File("src/test/resources/clang/source/build/compile_commands.json"); Mockito.when(directoryManager.getExtractionOutputDirectory(Mockito.any(ExtractionId.class))).thenReturn(outputDir); final List<PackageDetails> packages = new ArrayList<>(); packages.add(new PackageDetails("testPackageName", "testPackageVersion", "testPackageArch")); Mockito.when(pkgMgr.getDefaultForge()).thenReturn(Forge.UBUNTU); Mockito.when(pkgMgr.getPackages(Mockito.any(File.class), Mockito.any(ExecutableRunner.class), Mockito.any(Set.class), Mockito.any(DependencyFileDetails.class))).thenReturn(packages); Mockito.when(pkgMgr.getForges()).thenReturn(Arrays.asList(Forge.UBUNTU, Forge.DEBIAN)); final Extraction extraction = extractor.extract(pkgMgr, givenDir, depth, extractionId, jsonCompilationDatabaseFile); checkGeneratedDependenciesSimple(extraction); } @Test public void testMultipleCommandsDependenciesPackages() throws ExecutableRunnerException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final CompileCommand compileCommandWrapperHelloWorld = createCompileCommand("src/test/resources/clang/source/hello_world.cpp", "gcc hello_world.cpp", null); final CompileCommand compileCommandWrapperGoodbyeWorld = createCompileCommand("src/test/resources/clang/source/goodbye_world.cpp", "gcc goodbye_world.cpp", null); final Set<String> dependencyFilePathsHelloWorld = createDependencyFilePaths(new File("src/test/resources/clang/source/myinclude.h"), new File("/usr/include/nonexistentfile1.h"), new File("/usr/include/nonexistentfile2.h")); final Set<String> dependencyFilePathsGoodbyeWorld = createDependencyFilePaths(new File("/usr/include/nonexistentfile4.h"), new File("/usr/include/nonexistentfile3.h")); final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class); final DirectoryManager directoryManager = Mockito.mock(DirectoryManager.class); final DependenciesListFileManager dependenciesListFileManager = Mockito.mock(DependenciesListFileManager.class); Mockito.when(dependenciesListFileManager.generateDependencyFilePaths(outputDir, compileCommandWrapperHelloWorld, true)).thenReturn(dependencyFilePathsHelloWorld); Mockito.when(dependenciesListFileManager.generateDependencyFilePaths(outputDir, compileCommandWrapperGoodbyeWorld, true)).thenReturn(dependencyFilePathsGoodbyeWorld); Mockito.when(executableRunner.executeFromDirQuietly(Mockito.any(File.class), Mockito.anyString(), Mockito.anyList())).thenReturn(new ExecutableOutput(0, "", "")); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final CodeLocationAssembler codeLocationAssembler = new CodeLocationAssembler(externalIdFactory); final ClangExtractor extractor = new ClangExtractor(null, executableRunner, gson, new DetectFileFinder(), directoryManager, dependenciesListFileManager, codeLocationAssembler); final ClangLinuxPackageManager pkgMgr = Mockito.mock(ClangLinuxPackageManager.class); final File givenDir = new File("src/test/resources/clang/source/build"); final int depth = 1; final ExtractionId extractionId = new ExtractionId(DetectorType.CLANG, EXTRACTION_ID); final File jsonCompilationDatabaseFile = new File("src/test/resources/clang/source/build/compile_commands.json"); Mockito.when(directoryManager.getExtractionOutputDirectory(Mockito.any(ExtractionId.class))).thenReturn(outputDir); final List<PackageDetails> packages = new ArrayList<>(); packages.add(new PackageDetails("testPackageName1", "testPackageVersion1", "testPackageArch1")); packages.add(new PackageDetails("testPackageName2", "testPackageVersion2", "testPackageArch2")); Mockito.when(pkgMgr.getDefaultForge()).thenReturn(Forge.CENTOS); Mockito.when(pkgMgr.getPackages(Mockito.any(File.class), Mockito.any(ExecutableRunner.class), Mockito.any(Set.class), Mockito.any(DependencyFileDetails.class))).thenReturn(packages); Mockito.when(pkgMgr.getForges()).thenReturn(Arrays.asList(Forge.CENTOS, Forge.FEDORA, Forge.REDHAT)); final Extraction extraction = extractor.extract(pkgMgr, givenDir, depth, extractionId, jsonCompilationDatabaseFile); checkGeneratedDependenciesComplex(extraction); } @Test public void testJsonWithArgumentsNotCommand() throws ExecutableRunnerException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final String[] argsHello = { "gcc", "hello_world.cpp" }; final CompileCommand compileCommandWrapperHelloWorld = createCompileCommand("src/test/resources/clang/source/hello_world.cpp", null, argsHello); final String[] argsGoodbye = { "gcc", "goodbye_world.cpp" }; final CompileCommand compileCommandWrapperGoodbyeWorld = createCompileCommand("src/test/resources/clang/source/goodbye_world.cpp", null, argsGoodbye); final Set<String> dependencyFilePathsHelloWorld = createDependencyFilePaths(new File("src/test/resources/clang/source/myinclude.h"), new File("/usr/include/nonexistentfile1.h"), new File("/usr/include/nonexistentfile2.h")); final Set<String> dependencyFilePathsGoodbyeWorld = createDependencyFilePaths(new File("/usr/include/nonexistentfile4.h"), new File("/usr/include/nonexistentfile3.h")); ; final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class); final DirectoryManager directoryManager = Mockito.mock(DirectoryManager.class); final DependenciesListFileManager dependenciesListFileManager = Mockito.mock(DependenciesListFileManager.class); Mockito.when(dependenciesListFileManager.generateDependencyFilePaths(outputDir, compileCommandWrapperHelloWorld, true)).thenReturn(dependencyFilePathsHelloWorld); Mockito.when(dependenciesListFileManager.generateDependencyFilePaths(outputDir, compileCommandWrapperGoodbyeWorld, true)).thenReturn(dependencyFilePathsGoodbyeWorld); Mockito.when(executableRunner.executeFromDirQuietly(Mockito.any(File.class), Mockito.anyString(), Mockito.anyList())).thenReturn(new ExecutableOutput(0, "", "")); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final CodeLocationAssembler codeLocationAssembler = new CodeLocationAssembler(externalIdFactory); final ClangExtractor extractor = new ClangExtractor(null, executableRunner, gson, new DetectFileFinder(), directoryManager, dependenciesListFileManager, codeLocationAssembler); final ClangLinuxPackageManager pkgMgr = Mockito.mock(ClangLinuxPackageManager.class); final File givenDir = new File("src/test/resources/clang/source/build"); final int depth = 1; final ExtractionId extractionId = new ExtractionId(DetectorType.CLANG, EXTRACTION_ID); final File jsonCompilationDatabaseFile = new File("src/test/resources/clang/source/build/compile_commands_usesArguments.json"); Mockito.when(directoryManager.getExtractionOutputDirectory(Mockito.any(ExtractionId.class))).thenReturn(outputDir); final List<PackageDetails> packages = new ArrayList<>(); packages.add(new PackageDetails("testPackageName1", "testPackageVersion1", "testPackageArch1")); packages.add(new PackageDetails("testPackageName2", "testPackageVersion2", "testPackageArch2")); Mockito.when(pkgMgr.getDefaultForge()).thenReturn(Forge.CENTOS); Mockito.when(pkgMgr.getPackages(Mockito.any(File.class), Mockito.any(ExecutableRunner.class), Mockito.any(Set.class), Mockito.any(DependencyFileDetails.class))).thenReturn(packages); Mockito.when(pkgMgr.getForges()).thenReturn(Arrays.asList(Forge.CENTOS, Forge.FEDORA, Forge.REDHAT)); final Extraction extraction = extractor.extract(pkgMgr, givenDir, depth, extractionId, jsonCompilationDatabaseFile); checkGeneratedDependenciesComplex(extraction); }
CpanListParser { public DependencyGraph parse(final List<String> cpanListText, final List<String> directDependenciesText) { final Map<String, String> nameVersionMap = createNameVersionMap(cpanListText); final List<String> directModuleNames = getDirectModuleNames(directDependenciesText); final MutableDependencyGraph graph = new MutableMapDependencyGraph(); for (final String moduleName : directModuleNames) { final String version = nameVersionMap.get(moduleName); if (null != version) { final String name = moduleName.replace("::", "-"); final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.CPAN, name, version); final Dependency dependency = new Dependency(name, version, externalId); graph.addChildToRoot(dependency); } else { logger.warn(String.format("Could node find resolved version for module: %s", moduleName)); } } return graph; } CpanListParser(final ExternalIdFactory externalIdFactory); DependencyGraph parse(final List<String> cpanListText, final List<String> directDependenciesText); }
@Test public void parseTest() { String cpanList = "Test::More\t1.2.3" + "\n"; cpanList += "Test::Less\t1.2.4" + "\n"; cpanList += "This is an invalid line" + "\n"; cpanList += "This\t1\t1also\t1invalid" + "\n"; cpanList += "Invalid" + "\n"; final List<String> tokens = Arrays.asList(StringUtils.tokenizeToStringArray(cpanList, "\n")); final Map<String, String> nodeMap = cpanListParser.createNameVersionMap(tokens); assertEquals(2, nodeMap.size()); assertNotNull(nodeMap.get("Test::More")); assertNotNull(nodeMap.get("Test::Less")); assertEquals("1.2.3", nodeMap.get("Test::More")); assertEquals("1.2.4", nodeMap.get("Test::Less")); } @Test public void makeDependencyNodesTest() { final DependencyGraph dependencyGraph = cpanListParser.parse(cpanListText, showDepsText); DependencyGraphResourceTestUtil.assertGraph("/cpan/expectedDependencyNodes_graph.json", dependencyGraph); }
CpanListParser { List<String> getDirectModuleNames(final List<String> directDependenciesText) { final List<String> modules = new ArrayList<>(); for (final String line : directDependenciesText) { if (StringUtils.isBlank(line)) { continue; } if (line.contains("-->") || ((line.contains(" ... ") && line.contains("Configuring")))) { continue; } modules.add(line.split("~")[0].trim()); } return modules; } CpanListParser(final ExternalIdFactory externalIdFactory); DependencyGraph parse(final List<String> cpanListText, final List<String> directDependenciesText); }
@Test public void getDirectModuleNamesTest() { final List<String> names = cpanListParser.getDirectModuleNames(showDepsText); assertEquals(4, names.size()); assertTrue(names.contains("ExtUtils::MakeMaker")); assertTrue(names.contains("Test::More")); assertTrue(names.contains("perl")); assertTrue(names.contains("ExtUtils::MakeMaker")); }
CondaListParser { public Dependency condaListElementToDependency(final String platform, final CondaListElement element) { final String name = element.name; final String version = String.format("%s-%s-%s", element.version, element.buildString, platform); final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.ANACONDA, name, version); return new Dependency(name, version, externalId); } CondaListParser(final Gson gson, final ExternalIdFactory externalIdFactory); DependencyGraph parse(final String listJsonText, final String infoJsonText); Dependency condaListElementToDependency(final String platform, final CondaListElement element); }
@Test public void condaListElementToDependencyNodeTransformerTest() { final String platform = "linux"; final CondaListElement element = new CondaListElement(); element.name = "sampleName"; element.version = "sampleVersion"; element.buildString = "py36_0"; final Dependency dependency = condaListParser.condaListElementToDependency(platform, element); assertEquals("sampleName", dependency.name); assertEquals("sampleVersion-py36_0-linux", dependency.version); assertEquals("sampleName=sampleVersion-py36_0-linux", dependency.externalId.createExternalId()); }
CondaListParser { public DependencyGraph parse(final String listJsonText, final String infoJsonText) { final Type listType = new TypeToken<ArrayList<CondaListElement>>() { }.getType(); final List<CondaListElement> condaList = gson.fromJson(listJsonText, listType); final CondaInfo condaInfo = gson.fromJson(infoJsonText, CondaInfo.class); final String platform = condaInfo.platform; final MutableDependencyGraph graph = new MutableMapDependencyGraph(); for (final CondaListElement condaListElement : condaList) { graph.addChildToRoot(condaListElementToDependency(platform, condaListElement)); } return graph; } CondaListParser(final Gson gson, final ExternalIdFactory externalIdFactory); DependencyGraph parse(final String listJsonText, final String infoJsonText); Dependency condaListElementToDependency(final String platform, final CondaListElement element); }
@Test public void smallParseTest() { final String condaInfoJson = testUtil.getResourceAsUTF8String("/conda/condaInfo.json"); final String condaListJson = testUtil.getResourceAsUTF8String("/conda/condaListSmall.json"); final DependencyGraph dependencyGraph = condaListParser.parse(condaListJson, condaInfoJson); DependencyGraphResourceTestUtil.assertGraph("/conda/condaListSmallExpected_graph.json", dependencyGraph); } @Test public void largeParseTest() { final String condaInfoJson = testUtil.getResourceAsUTF8String("/conda/condaInfo.json"); final String condaListJson = testUtil.getResourceAsUTF8String("/conda/condaListLarge.json"); final DependencyGraph dependencyGraph = condaListParser.parse(condaListJson, condaInfoJson); DependencyGraphResourceTestUtil.assertGraph("/conda/condaListLargeExpected_graph.json", dependencyGraph); }
CodeLocationNameGenerator { public String createDockerScanCodeLocationName(final String dockerTarFilename, final String projectName, final String projectVersionName, final String prefix, final String suffix) { final String codeLocationTypeString = CodeLocationNameType.SCAN.toString().toLowerCase(); final List<String> fileCodeLocationNamePieces = Arrays.asList(dockerTarFilename, projectName, projectVersionName); final List<String> fileCodeLocationEndPieces = Arrays.asList(codeLocationTypeString); return createCodeLocationName(prefix, fileCodeLocationNamePieces, suffix, fileCodeLocationEndPieces); } CodeLocationNameGenerator(final DetectFileFinder detectFileFinder); String createBomCodeLocationName(final String detectSourcePath, final String sourcePath, final ExternalId externalId, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerCodeLocationName(final String sourcePath, final String projectName, final String projectVersionName, final String dockerImage, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerScanCodeLocationName(final String dockerTarFilename, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createScanCodeLocationName(final String sourcePath, final String scanTargetPath, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createBinaryScanCodeLocationName(final String filename, final String projectName, final String projectVersionName, final String prefix, final String suffix); static final int MAXIMUM_CODE_LOCATION_NAME_LENGTH; }
@Test public void testDockerScanCodeLocationName() { final String expected = "dockerTar.tar.gz/hub-common-rest/2.5.1-SNAPSHOT scan"; final DetectFileFinder detectFileFinder = mock(DetectFileFinder.class); when(detectFileFinder.extractFinalPieceFromPath("")).thenReturn("hub-common-rest"); final CodeLocationNameGenerator codeLocationNameGenerator = new CodeLocationNameGenerator(detectFileFinder); final String dockerTarFileName = "dockerTar.tar.gz"; final String projectName = "hub-common-rest"; final String projectVersionName = "2.5.1-SNAPSHOT"; final String prefix = ""; final String suffix = ""; final String actual = codeLocationNameGenerator.createDockerScanCodeLocationName(dockerTarFileName, projectName, projectVersionName, prefix, suffix); assertEquals(expected, actual); }
GradleReportParser { public Optional<DetectCodeLocation> parseDependencies(final File codeLocationFile) { DetectCodeLocation codeLocation = null; String projectSourcePath = ""; String projectGroup = ""; String projectName = ""; String projectVersionName = ""; boolean processingMetaData = false; final MutableDependencyGraph graph = new MutableMapDependencyGraph(); final DependencyHistory history = new DependencyHistory(); try (FileInputStream dependenciesInputStream = new FileInputStream(codeLocationFile); BufferedReader reader = new BufferedReader(new InputStreamReader(dependenciesInputStream, StandardCharsets.UTF_8));) { while (reader.ready()) { final String line = reader.readLine(); if (line.startsWith(DETECT_META_DATA_HEADER)) { processingMetaData = true; continue; } if (line.startsWith(DETECT_META_DATA_FOOTER)) { processingMetaData = false; continue; } if (processingMetaData) { if (line.startsWith(PROJECT_PATH_PREFIX)) { projectSourcePath = line.substring(PROJECT_PATH_PREFIX.length()).trim(); } else if (line.startsWith(PROJECT_GROUP_PREFIX)) { projectGroup = line.substring(PROJECT_GROUP_PREFIX.length()).trim(); } else if (line.startsWith(PROJECT_NAME_PREFIX)) { projectName = line.substring(PROJECT_NAME_PREFIX.length()).trim(); } else if (line.startsWith(PROJECT_VERSION_PREFIX)) { projectVersionName = line.substring(PROJECT_VERSION_PREFIX.length()).trim(); } continue; } if (StringUtils.isBlank(line)) { history.clear(); gradleReportConfigurationParser = new GradleReportConfigurationParser(); continue; } final Dependency dependency = gradleReportConfigurationParser.parseDependency(externalIdFactory, line); if (dependency == null) { continue; } final int lineTreeLevel = gradleReportConfigurationParser.getTreeLevel(); try { history.clearDependenciesDeeperThan(lineTreeLevel); } catch (final IllegalStateException e) { logger.warn(String.format("Problem parsing line '%s': %s", line, e.getMessage())); } if (history.isEmpty()) { graph.addChildToRoot(dependency); } else { graph.addChildWithParents(dependency, history.getLastDependency()); } history.add(dependency); } final ExternalId id = externalIdFactory.createMavenExternalId(projectGroup, projectName, projectVersionName); codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.GRADLE, projectSourcePath, id, graph).build(); } catch (final IOException e) { codeLocation = null; } return Optional.ofNullable(codeLocation); } GradleReportParser(final ExternalIdFactory externalIdFactory); Optional<DetectCodeLocation> parseDependencies(final File codeLocationFile); Optional<NameVersion> parseRootProjectNameVersion(final File rootProjectMetadataFile); static final String PROJECT_PATH_PREFIX; static final String PROJECT_GROUP_PREFIX; static final String PROJECT_NAME_PREFIX; static final String PROJECT_VERSION_PREFIX; static final String ROOT_PROJECT_NAME_PREFIX; static final String ROOT_PROJECT_VERSION_PREFIX; static final String DETECT_META_DATA_HEADER; static final String DETECT_META_DATA_FOOTER; }
@Test public void testSpringFrameworkAop() throws IOException { final File file = new File("src/test/resources/gradle/spring-framework/spring_aop_dependencyGraph.txt"); final GradleReportParser gradleReportParser = new GradleReportParser(new ExternalIdFactory()); final Optional<DetectCodeLocation> result = gradleReportParser.parseDependencies(file); assertTrue(result.isPresent()); System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(result.get())); } @Test public void testImplementationsGraph() throws IOException { final File file = new File("src/test/resources/gradle/gradle_implementations_dependencyGraph.txt"); final GradleReportParser gradleReportParser = new GradleReportParser(new ExternalIdFactory()); final Optional<DetectCodeLocation> result = gradleReportParser.parseDependencies(file); assertTrue(result.isPresent()); System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(result.get())); }
NugetInspectorPackager { public NugetParseResult createDetectCodeLocation(final File dependencyNodeFile) throws IOException { final String text = FileUtils.readFileToString(dependencyNodeFile, StandardCharsets.UTF_8); final NugetInspection nugetInspection = gson.fromJson(text, NugetInspection.class); final List<DetectCodeLocation> codeLocations = new ArrayList<>(); String projectName = ""; String projectVersion = ""; for (final NugetContainer it : nugetInspection.containers) { final Optional<NugetParseResult> possibleParseResult = createDetectCodeLocationFromNugetContainer(it); if (possibleParseResult.isPresent()) { final NugetParseResult result = possibleParseResult.get(); if (StringUtils.isNotBlank(result.projectName)) { projectName = result.projectName; projectVersion = result.projectVersion; } codeLocations.addAll(result.codeLocations); } } return new NugetParseResult(projectName, projectVersion, codeLocations); } NugetInspectorPackager(final Gson gson, final ExternalIdFactory externalIdFactory); NugetParseResult createDetectCodeLocation(final File dependencyNodeFile); }
@Test(timeout = 5000L) public void createCodeLocationDWService() throws IOException { final File dependencyNodeFile = new File(getClass().getResource("/nuget/dwCheckApi_inspection_martin.json").getFile()); final ExternalIdFactory externalIdFactory = new ExternalIdFactory(); final NugetInspectorPackager packager = new NugetInspectorPackager(gson, externalIdFactory); final NugetParseResult result = packager.createDetectCodeLocation(dependencyNodeFile); for (final DetectCodeLocation codeLocation : result.codeLocations) { final BdioPropertyHelper bdioPropertyHelper = new BdioPropertyHelper(); final BdioNodeFactory bdioNodeFactory = new BdioNodeFactory(bdioPropertyHelper); final DependencyGraphTransformer dependencyNodeTransformer = new DependencyGraphTransformer(bdioPropertyHelper, bdioNodeFactory); final BdioExternalIdentifier projectId = bdioPropertyHelper.createExternalIdentifier(codeLocation.getExternalId()); final BdioProject project = bdioNodeFactory.createProject(result.projectName, result.projectVersion, Forge.NUGET.toString(), projectId); final Map<ExternalId, BdioNode> components = new HashMap<>(); components.put(codeLocation.getExternalId(), project); final List<BdioComponent> bdioComponents = dependencyNodeTransformer.transformDependencyGraph(codeLocation.getDependencyGraph(), project, codeLocation.getDependencyGraph().getRootDependencies(), components); assertEquals(bdioComponents.size(), bdioComponents.size()); } }
NpmLockfileParser { public NpmParseResult parse(final String sourcePath, final Optional<String> packageJsonText, final String lockFileText, final boolean includeDevDependencies) { final MutableDependencyGraph dependencyGraph = new MutableMapDependencyGraph(); logger.info("Parsing lock file text: "); logger.debug(lockFileText); Optional<PackageJson> packageJson = Optional.empty(); if (packageJsonText.isPresent()) { logger.debug(packageJsonText.get()); packageJson = Optional.of(gson.fromJson(packageJsonText.get(), PackageJson.class)); } final PackageLock packageLock = gson.fromJson(lockFileText, PackageLock.class); logger.debug(lockFileText); logger.info("Processing project."); if (packageLock.dependencies != null) { logger.info(String.format("Found %d dependencies.", packageLock.dependencies.size())); NpmDependencyConverter dependencyConverter = new NpmDependencyConverter(externalIdFactory); NpmDependency rootDependency = dependencyConverter.convertLockFile(packageLock, packageJson); traverse(rootDependency, dependencyGraph, true, includeDevDependencies); } else { logger.info("Lock file did not have a 'dependencies' section."); } logger.info("Finished processing."); final ExternalId projectId = externalIdFactory.createNameVersionExternalId(Forge.NPM, packageLock.name, packageLock.version); final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.NPM, sourcePath, projectId, dependencyGraph).build(); return new NpmParseResult(packageLock.name, packageLock.version, codeLocation); } NpmLockfileParser(final Gson gson, final ExternalIdFactory externalIdFactory); NpmParseResult parse(final String sourcePath, final Optional<String> packageJsonText, final String lockFileText, final boolean includeDevDependencies); }
@Test public void parseLockFileWithRecreatedJsonTest() { final String lockFileText = testUtil.getResourceAsUTF8String("/npm/package-lock.json"); final NpmParseResult result = npmLockfileParser.parse("source", recreatePackageJsonFromLock(lockFileText), lockFileText, true); Assert.assertEquals(result.projectName, "knockout-tournament"); Assert.assertEquals(result.projectVersion, "1.0.0"); DependencyGraphResourceTestUtil.assertGraph("/npm/packageLockExpected_graph.json", result.codeLocation.getDependencyGraph()); } @Test public void parseLockFileTest() { final String lockFileText = testUtil.getResourceAsUTF8String("/npm/package-lock.json"); final NpmParseResult result = npmLockfileParser.parse("source", Optional.empty(), lockFileText, true); Assert.assertEquals(result.projectName, "knockout-tournament"); Assert.assertEquals(result.projectVersion, "1.0.0"); DependencyGraphResourceTestUtil.assertGraph("/npm/packageLockExpected_graph.json", result.codeLocation.getDependencyGraph()); } @Test public void parseShrinkwrapWithRecreatedJsonTest() { final String shrinkwrapText = testUtil.getResourceAsUTF8String("/npm/npm-shrinkwrap.json"); final NpmParseResult result = npmLockfileParser.parse("source", recreatePackageJsonFromLock(shrinkwrapText), shrinkwrapText, true); Assert.assertEquals(result.projectName, "fec-builder"); Assert.assertEquals(result.projectVersion, "1.3.7"); DependencyGraphResourceTestUtil.assertGraph("/npm/shrinkwrapExpected_graph.json", result.codeLocation.getDependencyGraph()); } @Test public void parseShrinkwrapTest() { final String shrinkwrapText = testUtil.getResourceAsUTF8String("/npm/npm-shrinkwrap.json"); final NpmParseResult result = npmLockfileParser.parse("source", Optional.empty(), shrinkwrapText, true); Assert.assertEquals(result.projectName, "fec-builder"); Assert.assertEquals(result.projectVersion, "1.3.7"); DependencyGraphResourceTestUtil.assertGraph("/npm/shrinkwrapExpected_graph.json", result.codeLocation.getDependencyGraph()); }
CodeLocationNameGenerator { public String createBomCodeLocationName(final String detectSourcePath, final String sourcePath, final ExternalId externalId, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix) { final String pathPiece = FileNameUtils.relativize(detectSourcePath, sourcePath); final List<String> pieces = Arrays.asList(externalId.getExternalIdPieces()); final String externalIdPiece = StringUtils.join(pieces, "/"); final String codeLocationTypeString = CodeLocationNameType.BOM.toString().toLowerCase(); final String bomToolTypeString = detectCodeLocationType.toString().toLowerCase(); final List<String> bomCodeLocationNamePieces = Arrays.asList(pathPiece, externalIdPiece); final List<String> bomCodeLocationEndPieces = Arrays.asList(bomToolTypeString, codeLocationTypeString); return createCodeLocationName(prefix, bomCodeLocationNamePieces, suffix, bomCodeLocationEndPieces); } CodeLocationNameGenerator(final DetectFileFinder detectFileFinder); String createBomCodeLocationName(final String detectSourcePath, final String sourcePath, final ExternalId externalId, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerCodeLocationName(final String sourcePath, final String projectName, final String projectVersionName, final String dockerImage, final DetectCodeLocationType detectCodeLocationType, final String prefix, final String suffix); String createDockerScanCodeLocationName(final String dockerTarFilename, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createScanCodeLocationName(final String sourcePath, final String scanTargetPath, final String projectName, final String projectVersionName, final String prefix, final String suffix); String createBinaryScanCodeLocationName(final String filename, final String projectName, final String projectVersionName, final String prefix, final String suffix); static final int MAXIMUM_CODE_LOCATION_NAME_LENGTH; }
@Test public void testBomCodeLocationName() { final String expected = "hub-common-rest/child/group/name/version npm/bom"; final ExternalIdFactory factory = new ExternalIdFactory(); final ExternalId externalId = factory.createMavenExternalId("group", "name", "version"); final DetectFileFinder detectFileFinder = new DetectFileFinder(); final CodeLocationNameGenerator codeLocationNameGenerator = new CodeLocationNameGenerator(detectFileFinder); final String sourcePath = "/Users/ekerwin/Documents/source/integration/hub-common-rest"; final String codeLocationPath = "/Users/ekerwin/Documents/source/integration/hub-common-rest/child"; final String prefix = ""; final String suffix = ""; final String actual = codeLocationNameGenerator.createBomCodeLocationName(sourcePath, codeLocationPath, externalId, DetectCodeLocationType.NPM, prefix, suffix); assertEquals(expected, actual); } @Test public void testLongCodeLocationNames() { final String expected = "hub-common-rest/hub...esthub-common-rest/group/name/version npm/bom"; final ExternalIdFactory factory = new ExternalIdFactory(); final ExternalId externalId = factory.createMavenExternalId("group", "name", "version"); final DetectFileFinder detectFileFinder = new DetectFileFinder(); final CodeLocationNameGenerator codeLocationNameGenerator = new CodeLocationNameGenerator(detectFileFinder); final String sourcePath = "/Users/ekerwin/Documents/source/integration/hub-common-rest"; final String codeLocationPath = "/Users/ekerwin/Documents/source/integration/hub-common-rest/hub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-resthub-common-rest"; final String prefix = ""; final String suffix = ""; final String actual = codeLocationNameGenerator.createBomCodeLocationName(sourcePath, codeLocationPath, externalId, DetectCodeLocationType.NPM, prefix, suffix); assertEquals(expected, actual); }
MavenCodeLocationPackager { public List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules) { final ExcludedIncludedFilter filter = new ExcludedIncludedFilter(excludedModules, includedModules); codeLocations = new ArrayList<>(); currentMavenProject = null; dependencyParentStack = new Stack<>(); parsingProjectSection = false; currentGraph = new MutableMapDependencyGraph(); level = 0; for (final String currentLine : mavenOutputText.split(System.lineSeparator())) { String line = currentLine.trim(); if (!isLineRelevant(line)) { continue; } line = trimLogLevel(line); if (StringUtils.isBlank(line)) { continue; } if (isProjectSection(line)) { parsingProjectSection = true; continue; } if (!parsingProjectSection) { continue; } if (isDependencyTreeUpdates(line)) { continue; } if (parsingProjectSection && currentMavenProject == null) { currentGraph = new MutableMapDependencyGraph(); final MavenParseResult mavenProject = createMavenParseResult(sourcePath, line, currentGraph); if (null != mavenProject && filter.shouldInclude(mavenProject.projectName)) { logger.trace(String.format("Project: %s", mavenProject.projectName)); this.currentMavenProject = mavenProject; codeLocations.add(mavenProject); } else { logger.trace("Project: unknown"); currentMavenProject = null; dependencyParentStack.clear(); parsingProjectSection = false; level = 0; } continue; } final boolean finished = line.contains("--------"); if (finished) { currentMavenProject = null; dependencyParentStack.clear(); parsingProjectSection = false; level = 0; continue; } final int previousLevel = level; final String cleanedLine = calculateCurrentLevelAndCleanLine(line); final ScopedDependency dependency = textToDependency(cleanedLine); if (null == dependency) { continue; } if (currentMavenProject != null) { if (level == 1) { if (dependency.isInScope(targetScope)) { logger.trace(String.format("Level 1 component %s:%s:%s:%s is in scope; adding it to hierarchy root", dependency.externalId.group, dependency.externalId.name, dependency.externalId.version, dependency.scope)); currentGraph.addChildToRoot(dependency); inOutOfScopeTree = false; } else { logger.trace(String.format("Level 1 component %s:%s:%s:%s is a top-level out-of-scope component; entering non-scoped tree", dependency.externalId.group, dependency.externalId.name, dependency.externalId.version, dependency.scope)); inOutOfScopeTree = true; } dependencyParentStack.clear(); dependencyParentStack.push(dependency); } else { if (level == previousLevel) { dependencyParentStack.pop(); addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree, dependencyParentStack.peek(), dependency); dependencyParentStack.push(dependency); } else if (level > previousLevel) { addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree, dependencyParentStack.peek(), dependency); dependencyParentStack.push(dependency); } else { for (int i = previousLevel; i >= level; i--) { dependencyParentStack.pop(); } addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree, dependencyParentStack.peek(), dependency); dependencyParentStack.push(dependency); } } } } addOrphansToGraph(currentGraph, orphans); return codeLocations; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void extractCodeLocationsTest() { final String mavenOutputText = testUtil.getResourceAsUTF8String("/maven/sonarStashOutput.txt"); createNewCodeLocationTest(mavenOutputText, "/maven/sonarStashCodeLocation.json"); }
MavenCodeLocationPackager { Dependency textToProject(final String componentText) { if (!isGav(componentText)) { return null; } final String[] gavParts = componentText.split(":"); final String group = gavParts[0]; final String artifact = gavParts[1]; String version; if (gavParts.length == 4) { version = gavParts[gavParts.length - 1]; } else if (gavParts.length == 5) { version = gavParts[gavParts.length - 1]; } else { logger.debug(String.format("%s does not look like a dependency we can parse", componentText)); return null; } final ExternalId externalId = externalIdFactory.createMavenExternalId(group, artifact, version); return new Dependency(artifact, version, externalId); } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testParseProject() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(new ExternalIdFactory()); Dependency dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:0.0.1"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:classifier:0.0.1"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar"); assertNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:classifier:0.0.1:monkey"); assertNull(dependency); }
MavenCodeLocationPackager { ScopedDependency textToDependency(final String componentText) { if (!isGav(componentText)) { return null; } final String[] gavParts = componentText.split(":"); final String group = gavParts[0]; final String artifact = gavParts[1]; final String scope = gavParts[gavParts.length - 1]; final boolean recognizedScope = KNOWN_SCOPES.stream().anyMatch(knownScope -> scope.startsWith(knownScope)); if (!recognizedScope) { logger.warn("This line can not be parsed correctly due to an unknown dependency format - it is unlikely a match will be found for this dependency: " + componentText); } final String version = gavParts[gavParts.length - 2]; final ExternalId externalId = externalIdFactory.createMavenExternalId(group, artifact, version); return new ScopedDependency(artifact, version, externalId, scope); } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }
@Test public void testParseDependency() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(new ExternalIdFactory()); ScopedDependency dependency = mavenCodeLocationPackager.textToDependency("stuff:things:jar:0.0.1:compile"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToDependency("stuff:things:jar:classifier:0.0.1:test"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToDependency("stuff:things:jar"); assertNull(dependency); dependency = mavenCodeLocationPackager.textToDependency("stuff:things:jar:classifier:0.0.1"); assertNotNull(dependency); }
ProductMapper { public Product toProduct(ProductDto product) { return this.mapper.map(product, Product.class); } ProductMapper(); ProductDto toProductDto(Product product); List<ProductDto> toProductDtoList(List<Product> products); Product toProduct(ProductDto product); }
@Test public void testProductDto2JpaMapping() { ProductDto productDto = ProductDto.builder() .id("product-1") .name("product-1") .brand("brand-1") .description("description-1") .category(ImmutableList.of("one", "two")) .price(BigDecimal.TEN) .build(); Product productJpa = mapper.toProduct(productDto); softly.then(productJpa.getId()).isEqualTo(productDto.getId()); softly.then(productJpa.getName()).isEqualTo(productDto.getName()); softly.then(productJpa.getBrand()).isEqualTo(productDto.getBrand()); softly.then(productJpa.getDescription()).isEqualTo(productDto.getDescription()); softly.then(productJpa.getPrice()).isEqualTo(productDto.getPrice()); assertThat(productJpa.getCategories()).isNotNull(); softly.then(productJpa.getCategories()).usingElementComparatorOnFields("category"); }
ProductMapper { public ProductDto toProductDto(Product product) { return this.mapper.map(product, ProductDto.class); } ProductMapper(); ProductDto toProductDto(Product product); List<ProductDto> toProductDtoList(List<Product> products); Product toProduct(ProductDto product); }
@Test public void testProductJpa2DtoMapping() { Product productJpa = Product.builder() .id("product-1") .name("product-1") .brand("brand-1") .description("description-1") .categories(ImmutableList.of( Category.builder().name("one").build(), Category.builder().name("two").build())) .price(BigDecimal.TEN) .build(); ProductDto productDto = mapper.toProductDto(productJpa); softly.then(productDto.getId()).isEqualTo(productJpa.getId()); softly.then(productDto.getName()).isEqualTo(productJpa.getName()); softly.then(productDto.getBrand()).isEqualTo(productJpa.getBrand()); softly.then(productDto.getDescription()).isEqualTo(productJpa.getDescription()); softly.then(productDto.getPrice()).isEqualTo(productJpa.getPrice()); softly.then(productDto.getCategory()).isEqualTo(ImmutableList.of("one","two")); }
OrderMapper { public OrderForm toOrderForm(OrderDto order) { return this.mapper.map(order, OrderForm.class); } OrderMapper(); OrderDto toOrderDto(OrderForm order); OrderForm toOrderForm(OrderDto order); List<OrderDto> toOrderDtoList(List<OrderForm> orders); }
@Test public void testEmptyOrderDto() { OrderDto orderDto = OrderDto.builder() .id("order-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .build(); OrderForm orderJpa = mapper.toOrderForm(orderDto); softly.then(orderJpa.getId()).isEqualTo(orderDto.getId()); softly.then(orderJpa.getUserId()).isEqualTo(orderDto.getUserId()); softly.then(orderJpa.getStatus()).isEqualTo(orderDto.getStatus()); } @Test public void testOrderDtoWithOrderItemDto() { OrderDto orderDto = OrderDto.builder() .id("order-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .items(ImmutableList.of( OrderItemDto.builder() .productId("product-1") .quantity(10) .build() )) .build(); OrderForm orderJpa = mapper.toOrderForm(orderDto); softly.then(orderJpa.getId()).isEqualTo(orderDto.getId()); softly.then(orderJpa.getUserId()).isEqualTo(orderDto.getUserId()); softly.then(orderJpa.getStatus()).isEqualTo(orderDto.getStatus()); softly.then(orderJpa.getItems()) .isNotNull() .hasSize(1); softly.then(orderJpa.getItems().get(0).getId()).isNull(); softly.then(orderJpa.getItems().get(0).getOrder()) .isNotNull() .hasFieldOrPropertyWithValue("id", "order-1"); softly.then(orderJpa.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(orderJpa.getItems().get(0).getQuantity()).isEqualTo(10); }
OrderMapper { public OrderDto toOrderDto(OrderForm order) { return this.mapper.map(order, OrderDto.class); } OrderMapper(); OrderDto toOrderDto(OrderForm order); OrderForm toOrderForm(OrderDto order); List<OrderDto> toOrderDtoList(List<OrderForm> orders); }
@Test public void testOrderJpaToOrderDto() throws IOException { OrderForm orderJpa = OrderForm.builder() .id("orderJpa-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .items(ImmutableList.of( OrderItem.builder() .productId("product-1") .quantity(10) .build() )) .build(); OrderDto orderDto = mapper.toOrderDto(orderJpa); softly.then(orderDto.getId()).isEqualTo(orderJpa.getId()); softly.then(orderDto.getUserId()).isEqualTo(orderJpa.getUserId()); softly.then(orderDto.getStatus()).isEqualTo(orderJpa.getStatus()); softly.then(orderDto.getItems()) .isNotNull() .hasSize(1); softly.then(orderDto.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(orderDto.getItems().get(0).getQuantity()).isEqualTo(10); ObjectMapper jsonMapper = new ObjectMapper(); String jsonOrderDto = jsonMapper.writeValueAsString(orderDto); OrderDto pojoOrderDto = jsonMapper.readValue(jsonOrderDto, OrderDto.class); softly.then(pojoOrderDto.getId()).isEqualTo(orderJpa.getId()); softly.then(pojoOrderDto.getUserId()).isEqualTo(orderJpa.getUserId()); softly.then(pojoOrderDto.getStatus()).isEqualTo(orderJpa.getStatus()); softly.then(pojoOrderDto.getItems()) .isNotNull() .hasSize(1); softly.then(pojoOrderDto.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(pojoOrderDto.getItems().get(0).getQuantity()).isEqualTo(10); }
UserMapper { public User toUser(UserDto user) { return this.mapper.map(user, User.class); } UserMapper(); UserDto toUserDto(User user); List<UserDto> toUserDtoList(List<User> users); User toUser(UserDto user); }
@Test public void testUserDtoMapping() { UserDto userDto = UserDto.builder() .id("user-1") .title("Mr") .givenName("Mickey") .familyName("Mouse") .email("[email protected]") .bday(LocalDate.of(1928,1,1).atStartOfDay()) .build(); User userJpa = mapper.toUser(userDto); softly.then(userJpa.getId()).isEqualTo(userDto.getId()); softly.then(userJpa.getTitle()).isEqualTo(userDto.getTitle()); softly.then(userJpa.getFirstname()).isEqualTo(userDto.getGivenName()); softly.then(userJpa.getLastname()).isEqualTo(userDto.getFamilyName()); softly.then(userJpa.getEmail()).isEqualTo(userDto.getEmail()); softly.then(userJpa.getDob()).isEqualTo(userDto.getBday().toLocalDate()); }
UserMapper { public UserDto toUserDto(User user) { return this.mapper.map(user, UserDto.class); } UserMapper(); UserDto toUserDto(User user); List<UserDto> toUserDtoList(List<User> users); User toUser(UserDto user); }
@Test public void testUserJpaMapping() { User userJpa = User.builder() .id("user-1") .title("Mr") .firstname("Mickey") .lastname("Mouse") .email("[email protected]") .dob(LocalDate.of(1928,1,1)) .build(); UserDto userDto = mapper.toUserDto(userJpa); softly.then(userDto.getId()).isEqualTo(userJpa.getId()); softly.then(userDto.getTitle()).isEqualTo(userJpa.getTitle()); softly.then(userDto.getGivenName()).isEqualTo(userJpa.getFirstname()); softly.then(userDto.getFamilyName()).isEqualTo(userJpa.getLastname()); softly.then(userDto.getEmail()).isEqualTo(userJpa.getEmail()); softly.then(userDto.getBday()).isEqualTo(userJpa.getDob().atStartOfDay()); }
UserRepository { public List<User> findAll() { return Collections.unmodifiableList(new ArrayList<>(mapUsers.values())); } UserRepository(); List<User> findAll(); Optional<User> findOne(String id); User save(User newUser); Optional<User> remove(String id); }
@Test public void testLoadedProducts(){ List<User> allUsers = userRepository.findAll(); log.info(name+" loaded User data = " + allUsers); assertThat(allUsers).isNotNull().hasSize(3); }
SudokuArguments { @Param(value = 1, mappedBy = Mapper.class) abstract List<List<List<List<List<List<List<Set<Set<Set<Set<Set<Set<Collection<Integer>>>>>>>>>>>>>> number(); }
@Test void testSudoku() { SudokuArguments_Parser.ParseResult parsed = new SudokuArguments_Parser().parse(new String[]{""}); assertTrue(parsed instanceof SudokuArguments_Parser.ParsingSuccess); SudokuArguments args = ((SudokuArguments_Parser.ParsingSuccess) parsed).getResult(); assertTrue(args.number().isEmpty()); }
OptionalIntegerArguments { @Option(value = "a", mnemonic = 'a', mappedBy = Mapper.class) abstract Optional<Integer> a(); }
@Test void testPresent() { OptionalIntegerArguments args = new OptionalIntegerArguments_Parser().parseOrExit(new String[]{"-a", "1"}); assertEquals(Optional.of(1), args.a()); }
AllDoublesArguments { @Param(1) abstract List<Double> positional(); }
@Test void positional() { f.assertThat("--obj=1.5", "--prim=1.5", "5.5", "3.5").succeeds( "positional", asList(5.5d, 3.5d), "listOfDoubles", emptyList(), "optionalDouble", Optional.empty(), "doubleObject", 1.5d, "primitiveDouble", 1.5d); }
CpArguments { @Option("backup") abstract Optional<Control> backup(); }
@Test void testEnum() { assertEquals(Optional.of(Control.NUMBERED), f.parse("a", "b", "--backup=NUMBERED").backup()); f.assertThat("-r", "a", "b", "--backup", "SIMPLE") .succeeds( "source", "a", "dest", "b", "recursive", true, "backup", Optional.of(Control.SIMPLE), "suffix", Optional.empty()); }
AllFloatsArguments { @Param(1) abstract List<Float> positional(); }
@Test void positional() { f.assertThat("--obj=1.5", "--prim=1.5", "5.5", "3.5").succeeds( "positional", asList(5.5f, 3.5f), "listOfFloats", emptyList(), "optionalFloat", Optional.empty(), "floatObject", 1.5f, "primitiveFloat", 1.5f); }
TarArguments { @Option(value = "x", mnemonic = 'x') abstract boolean extract(); }
@Test void testExtract() { f.assertThat("-x", "-f", "foo.tar").succeeds( "extract", true, "create", false, "verbose", false, "compress", false, "file", "foo.tar"); f.assertThat("-v", "-x", "-f", "foo.tar").succeeds( "extract", true, "create", false, "verbose", true, "compress", false, "file", "foo.tar"); }
ListIntegerArguments { @Option(value = "a", mnemonic = 'a', mappedBy = Mapper.class) abstract List<Integer> a(); }
@Test void testPresent() { ListIntegerArguments args = new ListIntegerArguments_Parser().parseOrExit(new String[]{"-a", "1"}); assertEquals(Collections.singletonList(1), args.a()); }
OptionalIntArguments { @Option(value = "a", mnemonic = 'a', mappedBy = Mapper.class) abstract OptionalInt a(); }
@Test void testPresent() { OptionalIntArguments args = new OptionalIntArguments_Parser().parseOrExit(new String[]{"-a", "1"}); assertEquals(OptionalInt.of(1), args.a()); }
Main { public static void main(String[] arguments) { Arguments args = new Main_Arguments_Parser().parseOrExit(arguments); System.out.println("The file '" + args.file() + "' was provided and verbosity is set to '" + args.verbose() + "'."); } static void main(String[] arguments); }
@Test void testMain() { String[] argv = new String[]{"-v", "-f", "file.txt"}; Main.Arguments args = new Main_Arguments_Parser().parseOrExit(argv); assertEquals("file.txt", args.file()); assertTrue(args.verbose()); }
OptionalIntArgumentsOptional { @Option(value = "a", mnemonic = 'a', mappedBy = Mapper.class) abstract OptionalInt a(); }
@Test void testPresent() { OptionalIntArgumentsOptional args = new OptionalIntArgumentsOptional_Parser().parseOrExit(new String[]{"-a", "1"}); assertEquals(OptionalInt.of(1), args.a()); } @Test void testAbsent() { OptionalIntArgumentsOptional args = new OptionalIntArgumentsOptional_Parser().parseOrExit(new String[]{}); assertEquals(OptionalInt.empty(), args.a()); }
AllLongsArguments { @Param(1) abstract List<Long> positional(); }
@Test void positional() { f.assertThat("--obj=1", "--prim=1", "5", "3").succeeds( "positional", asList(5L, 3L), "listOfLongs", emptyList(), "optionalLong", Optional.empty(), "longObject", 1L, "primitiveLong", 1L); }
VariousArguments { @Option("bigDecimal") abstract BigDecimal bigDecimal(); }
@Test void bigDecimal() { VariousArguments_Parser.ParseResult parsed = new VariousArguments_Parser().parse(new String[]{ "--bigDecimal", "3.14159265358979323846264338327950288419716939937510", "--bigInteger", "60221407600000000000000", "--path", "/home", "--localDate", "2001-02-01", "--uri", "http: "--pattern", "^[abc]*$", "6.02214076e23", "60221407600000000000000", "/etc/hosts", "/home", "2001-02-01", "http: "^[abc]*$" }); assertTrue(parsed instanceof VariousArguments_Parser.ParsingSuccess); VariousArguments args = ((VariousArguments_Parser.ParsingSuccess) parsed).getResult(); assertEquals(new BigDecimal("3.14159265358979323846264338327950288419716939937510"), args.bigDecimal()); assertEquals(Optional.of(Paths.get("/home")), args.pathPos()); assertEquals(URI.create("http: assertEquals(Optional.of(URI.create("http: }
AllIntegersArguments { @Option("opt") abstract Optional<Integer> optionalInteger(); }
@Test void optionalInteger() { f.assertThat("--opt", "1", "--obj=1", "--prim=1").succeeds( "positional", emptyList(), "listOfIntegers", emptyList(), "optionalInteger", Optional.of(1), "integer", 1, "primitiveInt", 1); }
AllIntegersArguments { @Param(1) abstract List<Integer> positional(); }
@Test void positional() { f.assertThat("--obj=1", "--prim=1", "5", "3").succeeds( "positional", asList(5, 3), "listOfIntegers", emptyList(), "optionalInteger", Optional.empty(), "integer", 1, "primitiveInt", 1); }
Optionalish { static Optional<Optionalish> unwrap(TypeMirror type, TypeTool tool) { Optional<Optionalish> optionalPrimtive = getOptionalPrimitive(type, tool); if (optionalPrimtive.isPresent()) { return optionalPrimtive; } return tool.unwrap(Optional.class, type) .map(wrapped -> new Optionalish(p -> CodeBlock.of("$N", p), type, wrapped)); } private Optionalish( Function<ParameterSpec, CodeBlock> extract, TypeMirror liftedType, TypeMirror wrappedType); }
@Test void testLiftPrimitiveInt() { EvaluatingProcessor.source().run((elements, types) -> { TypeMirror primitiveInt = types.getPrimitiveType(TypeKind.INT); Optional<Optionalish> opt = Optionalish.unwrap(primitiveInt, new TypeTool(elements, types)); assertFalse(opt.isPresent()); }); } @Test void testLiftString() { EvaluatingProcessor.source().run((elements, types) -> { TypeMirror string = elements.getTypeElement(String.class.getCanonicalName()).asType(); Optional<Optionalish> opt = Optionalish.unwrap(string, new TypeTool(elements, types)); assertFalse(opt.isPresent()); }); }
ReferenceTool { public ReferencedType<E> getReferencedType() { return resolver.typecheck(referencedClass, Supplier.class) .fold(this::handleNotSupplier, this::handleSupplier); } ReferenceTool(ExpectedType<E> expectedType, Function<String, ValidationException> errorHandler, TypeTool tool, TypeElement referencedClass); ReferencedType<E> getReferencedType(); }
@Test void simpleTest() { EvaluatingProcessor.source( "import java.util.List;", "import java.util.function.Supplier;", "import java.util.function.Function;", "", "class Mapper<AA1, AA2> implements A<AA1, AA2> { public Function<AA1, List<AA2>> get() { return null; } }", "interface A<BB1, BB2> extends B<BB1, List<BB2>> { }", "interface B<CC1, CC2> extends C<CC1, CC2> { }", "interface C<DD1, DD2> extends Supplier<Function<DD1, DD2>> { }" ).run("Mapper", (elements, types) -> { TypeElement mapperClass = elements.getTypeElement("Mapper"); TypeMirror AA1 = mapperClass.getTypeParameters().get(0).asType(); TypeMirror AA2 = mapperClass.getTypeParameters().get(1).asType(); TypeTool tool = new TypeTool(elements, types); ReferenceTool<Function> referenceTool = new ReferenceTool<>(ExpectedType.FUNCTION, s -> null, tool, mapperClass); ReferencedType<Function> referencedType = referenceTool.getReferencedType(); assertTrue(referencedType.isSupplier()); assertEquals(2, referencedType.typeArguments().size()); assertTrue(types.isSameType(AA1, referencedType.typeArguments().get(0))); assertTrue(types.isSameType(tool.getDeclaredType(List.class, Collections.singletonList(AA2)), referencedType.typeArguments().get(1))); }); }
Resolver { <E> Either<TypecheckFailure, List<? extends TypeMirror>> typecheck(TypeElement dog, Class<E> animal) { List<ImplementsRelation> hierarchy = new HierarchyUtil(tool).getHierarchy(dog); List<ImplementsRelation> path = findPath(hierarchy, animal); if (path.isEmpty()) { return left(nonFatal("not a " + animal.getCanonicalName())); } assert path.get(0).dog() == dog; if (tool.isRaw(path.get(path.size() - 1).animal())) { return left(fatal("raw type: " + path.get(path.size() - 1).animal())); } return dogToAnimal(path).map(Function.identity(), DeclaredType::getTypeArguments); } Resolver(ExpectedType<?> expectedType, TypeTool tool); Either<TypecheckFailure, List<? extends TypeMirror>> typecheck(DeclaredType declared, Class<E> someInterface); }
@Test void testTypecheckSuccess() { EvaluatingProcessor.source( "package test;", "", "import java.util.function.Supplier;", "", "interface StringSupplier extends Supplier<String> { }", "", "abstract class Foo implements StringSupplier { }" ).run("Mapper", (elements, types) -> { TypeTool tool = new TypeTool(elements, types); TypeElement mapper = elements.getTypeElement("test.Foo"); Resolver resolver = new Resolver(FUNCTION, tool); Either<TypecheckFailure, List<? extends TypeMirror>> result = resolver.typecheck(mapper, Supplier.class); assertTrue(result instanceof Right); List<? extends TypeMirror> typeArguments = ((Right<TypecheckFailure, List<? extends TypeMirror>>) result).value(); assertEquals(1, typeArguments.size()); TypeMirror typeParameter = typeArguments.get(0); TypeElement string = elements.getTypeElement("java.lang.String"); assertTrue(types.isSameType(string.asType(), typeParameter)); }); } @Test void testTypecheckFail() { EvaluatingProcessor.source( "package test;", "", "import java.util.function.Supplier;", "", "interface StringSupplier extends Supplier<String> { }", "", "abstract class Foo implements StringSupplier { }" ).run("Mapper", (elements, types) -> { TypeTool tool = new TypeTool(elements, types); TypeElement mapper = elements.getTypeElement("test.Foo"); Either<TypecheckFailure, List<? extends TypeMirror>> result = new Resolver(FUNCTION, tool).typecheck(mapper, String.class); assertTrue(result instanceof Left); }); } @Test void testTypecheckFunction() { EvaluatingProcessor.source( "package test;", "", "import java.util.function.Supplier;", "import java.util.function.Function;", "", "interface FunctionSupplier extends Supplier<Function<String, String>> { }" ).run("Mapper", (elements, types) -> { TypeTool tool = new TypeTool(elements, types); TypeElement mapper = elements.getTypeElement("test.FunctionSupplier"); DeclaredType declaredType = TypeTool.asDeclared(mapper.getInterfaces().get(0)); DeclaredType functionType = TypeTool.asDeclared(declaredType.getTypeArguments().get(0)); Either<TypecheckFailure, List<? extends TypeMirror>> result = new Resolver(FUNCTION, tool).typecheck(functionType, Function.class); assertTrue(result instanceof Right); }); }
CollectorClassValidator { CollectorInfo getCollectorInfo() { commonChecks(collectorClass); checkNotAbstract(collectorClass); ReferencedType<Collector> collectorType = new ReferenceTool<>(COLLECTOR, errorHandler, tool, collectorClass) .getReferencedType(); TypeMirror inputType = collectorType.typeArguments().get(0); TypeMirror outputType = collectorType.typeArguments().get(2); TypevarMapping rightSolution = tool.unify(returnType, outputType) .orElseThrow(this::boom); TypevarMapping leftSolution = new TypevarMapping(Collections.emptyMap(), tool); FlattenerResult result = new Flattener(tool, collectorClass) .mergeSolutions(leftSolution, rightSolution) .orElseThrow(this::boom); return CollectorInfo.create(tool, result.substitute(inputType).orElseThrow(f -> boom(f.getMessage())), collectorClass, collectorType.isSupplier(), result.getTypeParameters()); } CollectorClassValidator(Function<String, ValidationException> errorHandler, TypeTool tool, TypeElement collectorClass, TypeMirror returnType); }
@Test void simpleTest() { EvaluatingProcessor.source( "import java.util.Set;", "import java.util.function.Supplier;", "import java.util.stream.Collector;", "import java.util.stream.Collectors;", "", "class ToSetCollector<E> implements Supplier<Collector<E, ?, Set<E>>> {", " public Collector<E, ?, Set<E>> get() {", " return Collectors.toSet();", " }", "}" ).run("ToSetCollector", (elements, types) -> { TypeTool tool = new TypeTool(elements, types); DeclaredType returnType = tool.getDeclaredType(Set.class, Collections.singletonList(tool.asType(String.class))); TypeElement collectorClass = elements.getTypeElement("ToSetCollector"); CollectorInfo collectorInfo = new CollectorClassValidator(s -> null, tool, collectorClass, returnType) .getCollectorInfo(); CodeBlock expected = CodeBlock.of(".collect(new $T<$T>().get())", types.erasure(collectorClass.asType()), String.class); assertEquals(expected, collectorInfo.collectExpr()); }); }
ExtremelySimpleArguments { @Param(value = 1) abstract int hello(); }
@Test void simpleTest() { assertEquals(1, f.parse("1").hello()); }
MapperClassValidator { public Either<String, CodeBlock> getMapExpr() { commonChecks(mapperClass); checkNotAbstract(mapperClass); ReferencedType<Function> functionType = new ReferenceTool<>(FUNCTION, errorHandler, tool, mapperClass).getReferencedType(); TypeMirror inputType = functionType.typeArguments().get(0); TypeMirror outputType = functionType.typeArguments().get(1); return tool.unify(tool.asType(String.class), inputType).flatMap(FUNCTION::boom, inputSolution -> handle(functionType, outputType, inputSolution)); } MapperClassValidator(Function<String, ValidationException> errorHandler, TypeTool tool, TypeMirror expectedReturnType, TypeElement mapperClass); Either<String, CodeBlock> getMapExpr(); }
@Test void simpleTest() { EvaluatingProcessor.source( "import java.util.List;", "import java.util.function.Supplier;", "import java.util.function.Function;", "", "class Mapper<AA1, AA2> implements A<AA1, AA2> { public Function<AA1, List<AA2>> get() { return null; } }", "interface A<BB1, BB2> extends B<BB1, List<BB2>> { }", "interface B<CC1, CC2> extends C<CC1, CC2> { }", "interface C<DD1, DD2> extends Supplier<Function<DD1, DD2>> { }" ).run("Mapper", (elements, types) -> { TypeElement mapperClass = elements.getTypeElement("Mapper"); TypeTool tool = new TypeTool(elements, types); DeclaredType expectedReturnType = TypeExpr.prepare(elements, types).parse("java.util.List<java.lang.Integer>"); Either<String, CodeBlock> either = new MapperClassValidator(s -> null, tool, expectedReturnType, mapperClass) .getMapExpr(); assertTrue(either instanceof Right); CodeBlock mapExpr = ((Right<String, CodeBlock>) either).value(); CodeBlock expected = CodeBlock.of("new $T<$T, $T>().get()", types.erasure(mapperClass.asType()), String.class, Integer.class); assertEquals(expected, mapExpr); }); }
TypevarMapping { public TypeMirror get(String key) { return map.get(key); } TypevarMapping(Map<String, TypeMirror> map, TypeTool tool); Set<Map.Entry<String, TypeMirror>> entries(); TypeMirror get(String key); Either<TypecheckFailure, TypeMirror> substitute(TypeMirror input); Either<TypecheckFailure, DeclaredType> substitute(DeclaredType declaredType); Either<String, TypevarMapping> merge(TypevarMapping solution); Map<String, TypeMirror> getMapping(); }
@Test void unifyTest() { EvaluatingProcessor.source( "import java.util.Set;", "", "abstract class Foo { abstract <E> Set<E> getSet(); }" ).run((elements, types) -> { TypeTool tool = new TypeTool(elements, types); TypeElement set = elements.getTypeElement("java.util.Set"); TypeElement string = elements.getTypeElement("java.lang.String"); List<ExecutableElement> methods = ElementFilter.methodsIn(elements.getTypeElement("Foo").getEnclosedElements()); ExecutableElement getSetMethod = methods.get(0); TypeMirror returnType = getSetMethod.getReturnType(); Either<String, TypevarMapping> result = tool.unify(types.getDeclaredType(set, string.asType()), returnType); assertTrue(result instanceof Right); TypevarMapping solution = ((Right<String, TypevarMapping>) result).value(); assertNotNull(solution.get("E")); TypeMirror value = solution.get("E"); assertTrue(types.isSameType(value, string.asType())); }); }
TypevarMapping { public Either<TypecheckFailure, TypeMirror> substitute(TypeMirror input) { if (input.getKind() == TypeKind.TYPEVAR) { return right(map.getOrDefault(input.toString(), input)); } if (input.getKind() == TypeKind.ARRAY) { return right(input); } return substitute(input.accept(AS_DECLARED, null)) .map(Function.identity(), type -> type); } TypevarMapping(Map<String, TypeMirror> map, TypeTool tool); Set<Map.Entry<String, TypeMirror>> entries(); TypeMirror get(String key); Either<TypecheckFailure, TypeMirror> substitute(TypeMirror input); Either<TypecheckFailure, DeclaredType> substitute(DeclaredType declaredType); Either<String, TypevarMapping> merge(TypevarMapping solution); Map<String, TypeMirror> getMapping(); }
@Test void substituteTest() { EvaluatingProcessor.source().run((elements, types) -> { TypeTool tool = new TypeTool(elements, types); TypeElement string = elements.getTypeElement("java.lang.String"); TypevarMapping mapping = new TypevarMapping(Collections.emptyMap(), tool); Either<TypecheckFailure, TypeMirror> substitute = mapping.substitute(string.asType()); assertNotNull(substitute); assertTrue(substitute instanceof Right); }); }
CustomCollectorArguments { @Option(value = "H", mnemonic = 'H', collectedBy = MyStringCollector.class) abstract Set<String> strings(); }
@Test void testNoMapper() { CustomCollectorArguments parsed = f.parse( "-H", "A", "-H", "A", "-H", "HA"); assertEquals(new HashSet<>(asList("A", "HA")), parsed.strings()); }
CustomCollectorArguments { @Option(value = "B", mnemonic = 'B', collectedBy = MyIntegerCollector.class) abstract Set<Integer> integers(); }
@Test void testBuiltinMapper() { CustomCollectorArguments parsed = f.parse( "-B", "1", "-B", "1", "-B", "2"); assertEquals(new HashSet<>(asList(1, 2)), parsed.integers()); }
CustomCollectorArguments { @Option( value = "M", mnemonic = 'M', mappedBy = CustomBigIntegerMapper.class, collectedBy = ToSetCollector.class) abstract Set<BigInteger> bigIntegers(); }
@Test void testCustomMapper() { CustomCollectorArguments parsed = f.parse( "-M", "0x5", "-M", "0xA", "-M", "10"); assertEquals(Stream.of(5L, 10L).map(BigInteger::valueOf).collect(toSet()), parsed.bigIntegers()); }
CustomCollectorArguments { @Option(value = "K", mnemonic = 'K', collectedBy = ToSetCollector.class) abstract Set<Giddy> moneySet(); }
@Test void testCustomEnum() { CustomCollectorArguments parsed = f.parse( "-K", "SOME", "-K", "NONE"); assertEquals(Stream.of( CustomCollectorArguments.Giddy.SOME, CustomCollectorArguments.Giddy.NONE).collect(toSet()), parsed.moneySet()); }
CustomCollectorArguments { @Option( value = "T", mnemonic = 'T', mappedBy = MapEntryTokenizer.class, collectedBy = ToMapCollector.class) abstract Map<String, LocalDate> dateMap(); }
@Test void testMap() { CustomCollectorArguments parsed = f.parse( "-T", "A:2004-11-11", "-T", "B:2018-11-12"); assertEquals(LocalDate.parse("2004-11-11"), parsed.dateMap().get("A")); assertEquals(LocalDate.parse("2018-11-12"), parsed.dateMap().get("B")); }
ComplicatedMapperArguments { @Option( value = "number", mappedBy = Mapper.class) abstract Integer number(); }
@Test void number() { ComplicatedMapperArguments parsed = f.parse( "--number", "12", "--numbers", "3", "--numbers", "oops"); assertEquals(1, parsed.number().intValue()); assertEquals(2, parsed.numbers().size()); assertEquals(Integer.valueOf(3), parsed.numbers().get(0).get()); assertThrows(NumberFormatException.class, () -> parsed.numbers().get(1).get()); }
AdditionArguments { final int sum() { return a() + b() + c().orElse(0); } }
@Test void dashesIgnored() { f.assertThat("--", "1", "-2", "3").satisfies(e -> e.sum() == 2); f.assertThat("--", "-1", "-2", "-3").satisfies(e -> e.sum() == -6); f.assertThat("--", "-1", "-2", "3").satisfies(e -> e.sum() == 0); f.assertThat("--", "-1", "-2").satisfies(e -> e.sum() == -3); }
CustomStringSpanName implements QuerySpanNameProvider { CustomStringSpanName(String customString) { if (customString == null) { this.customString = "execute"; } else { this.customString = customString; } } CustomStringSpanName(String customString); @Override String querySpanName(String query); static Builder newBuilder(); }
@Test public void customStringSpanNameTest() { QuerySpanNameProvider customStringSpanName = CustomStringSpanName.newBuilder().build(); assertEquals("execute", customStringSpanName.querySpanName("SELECT * FROM test.table_name;")); customStringSpanName = CustomStringSpanName.newBuilder().build(null); assertEquals("execute", customStringSpanName.querySpanName("SELECT * FROM test.table_name;")); customStringSpanName = CustomStringSpanName.newBuilder().build("CUSTOM"); assertEquals("CUSTOM", customStringSpanName.querySpanName("SELECT * FROM test.table_name;")); }
PrefixedFullQuerySpanName implements QuerySpanNameProvider { PrefixedFullQuerySpanName(String prefix) { if (prefix == null || prefix.equals("")) { this.prefix = ""; } else { this.prefix = prefix + ": "; } } PrefixedFullQuerySpanName(String prefix); @Override String querySpanName(String query); static Builder newBuilder(); }
@Test public void prefixedFullQuerySpanNameTest() { QuerySpanNameProvider fullQuerySpanName = PrefixedFullQuerySpanName.newBuilder().build(); assertEquals("Cassandra: SELECT * FROM test.table_name;", fullQuerySpanName.querySpanName("SELECT * FROM test.table_name;")); assertEquals("Cassandra: N/A", fullQuerySpanName.querySpanName("")); assertEquals("Cassandra: N/A", fullQuerySpanName.querySpanName(null)); fullQuerySpanName = PrefixedFullQuerySpanName.newBuilder().build(""); assertEquals("SELECT * FROM test.table_name;", fullQuerySpanName.querySpanName("SELECT * FROM test.table_name;")); assertEquals("N/A", fullQuerySpanName.querySpanName("")); assertEquals("N/A", fullQuerySpanName.querySpanName(null)); fullQuerySpanName = PrefixedFullQuerySpanName.newBuilder().build(null); assertEquals("SELECT * FROM test.table_name;", fullQuerySpanName.querySpanName("SELECT * FROM test.table_name;")); assertEquals("N/A", fullQuerySpanName.querySpanName("")); assertEquals("N/A", fullQuerySpanName.querySpanName(null)); fullQuerySpanName = PrefixedFullQuerySpanName.newBuilder().build("CUSTOM"); assertEquals("CUSTOM: SELECT * FROM test.table_name;", fullQuerySpanName.querySpanName("SELECT * FROM test.table_name;")); assertEquals("CUSTOM: N/A", fullQuerySpanName.querySpanName("")); assertEquals("CUSTOM: N/A", fullQuerySpanName.querySpanName(null)); }
FullQuerySpanName implements QuerySpanNameProvider { FullQuerySpanName() { } FullQuerySpanName(); @Override String querySpanName(String query); static Builder newBuilder(); }
@Test public void fullQuerySpanNameTest() { QuerySpanNameProvider fullQuerySpanName = FullQuerySpanName.newBuilder().build(); assertEquals("SELECT * FROM test.table_name;", fullQuerySpanName.querySpanName("SELECT * FROM test.table_name;")); assertEquals("N/A", fullQuerySpanName.querySpanName("")); assertEquals("N/A", fullQuerySpanName.querySpanName(null)); }
GuavaCompatibilityUtil { static boolean isGuavaCompatibilityFound() { return INSTANCE.isGuavaCompatibilityFound; } private GuavaCompatibilityUtil(); }
@Test public void isGuavaCompatibilityFound() { assertTrue(GuavaCompatibilityUtil.isGuavaCompatibilityFound()); }
LiveFrameRateMonitor implements IFeedRtcp { @Override public void feed(JFGMsgVideoRtcp rtcp) { Log.d("rtcp", "此消息在smartcall已有打印,无需再打印.rtcp:" + rtcp.frameRate); badFrameCount = rtcp.frameRate == 0 ? ++badFrameCount : 0; if (monitorListener == null) return; boolean isFrameFailed = badFrameCount >= FAILED_TARGET; boolean isFrameLoading = badFrameCount >= LOADING_TARGET; Log.d("LiveFrameRateMonitor", "视频帧率分析结果, 是否加载失败:" + isFrameFailed + ",是否 Loading:" + isFrameLoading + ",badCount:" + badFrameCount); long dutation = System.currentTimeMillis() - lastNotifyTime; if (isFrameLoading && isFrameFailed && dutation > NOTIFY_WINDOW) { lastNotifyTime = System.currentTimeMillis(); monitorListener.onFrameFailed(); AppLogger.d("onFrameFailed"); } else if (dutation > NOTIFY_WINDOW && preStatus != isFrameLoading) { preStatus = isFrameLoading; lastNotifyTime = System.currentTimeMillis(); monitorListener.onFrameRate(isFrameLoading); AppLogger.d("onFrameRate" + isFrameLoading); } } @Override void feed(JFGMsgVideoRtcp rtcp); @Override void stop(); void setMonitorListener(MonitorListener monitorListener); }
@Test public void feed() throws Exception { feedRtcp = new LiveFrameRateMonitor(); feedRtcp.setMonitorListener(this); System.out.println(feedRtcp); new Thread(() -> { for (int i = 0; i < 100; i++) { JFGMsgVideoRtcp rtcp = new JFGMsgVideoRtcp(); rtcp.frameRate = new Random().nextInt(4); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } feedRtcp.feed(rtcp); System.out.println("i: " + i + "-->" + rtcp.frameRate); } }).start(); Thread.sleep(5000); }
HomeMinePresenterImpl extends AbstractFragmentPresenter<HomeMineContract.View> implements HomeMineContract.Presenter { @Override public void start() { super.start(); addSubscription(getAccountBack()); addSubscription(loginInMe()); } HomeMinePresenterImpl(HomeMineContract.View view); @Override void start(); @Override void stop(); @Override void portraitBlur(Bitmap bitmap); @Override String createRandomName(); @Override JFGAccount getUserInfoBean(); @Override boolean checkOpenLogIn(); @Override void fetchNewInfo(); @Override Subscription getAccountBack(); @Override void loginType(); Subscription loginInMe(); }
@Test public void testStart() throws Exception { HomeMinePresenterImpl homeMinePresenter = Mockito.mock(HomeMinePresenterImpl.class); assertTrue(homeMinePresenter.createRandomName().contains("d")); }
HomeMinePresenterImpl extends AbstractFragmentPresenter<HomeMineContract.View> implements HomeMineContract.Presenter { @Override public void stop() { super.stop(); } HomeMinePresenterImpl(HomeMineContract.View view); @Override void start(); @Override void stop(); @Override void portraitBlur(Bitmap bitmap); @Override String createRandomName(); @Override JFGAccount getUserInfoBean(); @Override boolean checkOpenLogIn(); @Override void fetchNewInfo(); @Override Subscription getAccountBack(); @Override void loginType(); Subscription loginInMe(); }
@Test public void testStop() throws Exception { }
HomeMinePresenterImpl extends AbstractFragmentPresenter<HomeMineContract.View> implements HomeMineContract.Presenter { @Override public void portraitBlur(Bitmap bitmap) { AppLogger.e("需要在io线程操作."); Observable.just(bitmap) .subscribeOn(Schedulers.io()) .map(b -> { if (b == null) { b = BitmapFactory.decodeResource(mView.getContext().getResources(), R.drawable.me_bg_top_image); } Bitmap result = BitmapUtils.zoomBitmap(b, 160, 160); Bitmap blur = FastBlurUtil.blur(result, 20, 2); return new BitmapDrawable(ContextUtils.getContext().getResources(), blur); }) .filter(result -> check()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> getView().onBlur(result), AppLogger::e); } HomeMinePresenterImpl(HomeMineContract.View view); @Override void start(); @Override void stop(); @Override void portraitBlur(Bitmap bitmap); @Override String createRandomName(); @Override JFGAccount getUserInfoBean(); @Override boolean checkOpenLogIn(); @Override void fetchNewInfo(); @Override Subscription getAccountBack(); @Override void loginType(); Subscription loginInMe(); }
@Test public void testPortraitBlur() throws Exception { }
HomeMinePresenterImpl extends AbstractFragmentPresenter<HomeMineContract.View> implements HomeMineContract.Presenter { @Override public String createRandomName() { String[] firtPart = {"a", "isFriend", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" , "m", "n", "o", "p", "q", "r", "account", "t", "u", "v", "w", "x", "y", "z"}; Random random = new Random(); int randNum1 = random.nextInt(10); int randNum2 = random.nextInt(10); if (randNum1 == randNum2) { randNum2 /= 2; } int randNum3 = random.nextInt(10); if ((randNum1 == randNum3) || (randNum2 == randNum3)) { randNum3 /= 2; } int a = random.nextInt(26); int b = random.nextInt(26); if (b == a) { b /= 2; } int c = random.nextInt(26); if ((a == c) || (b == c)) { c /= 2; } String result = firtPart[a] + firtPart[b] + firtPart[c] + randNum1 + randNum2 + randNum3; return result; } HomeMinePresenterImpl(HomeMineContract.View view); @Override void start(); @Override void stop(); @Override void portraitBlur(Bitmap bitmap); @Override String createRandomName(); @Override JFGAccount getUserInfoBean(); @Override boolean checkOpenLogIn(); @Override void fetchNewInfo(); @Override Subscription getAccountBack(); @Override void loginType(); Subscription loginInMe(); }
@Test public void testCreateRandomName() throws Exception { }
TimeUtils { public static long getTodayStartTime() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTimeInMillis(); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getTodayStartTime() throws Exception { }
TimeUtils { public static long getTodayEndTime() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); return calendar.getTimeInMillis(); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getTodayEndTime() throws Exception { }
TimeUtils { public static long getSpecificDayEndTime(long time) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); return calendar.getTimeInMillis(); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getSpecificDayEndTime() throws Exception { }
TimeUtils { public static long getSpecificDayStartTime(long time) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTimeInMillis(); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getSpecificDayStartTime() throws Exception { System.out.println("" + TimeUtils.getSpecificDayStartTime(1490410868253L)); long result = 1490371200253L + 24 * 3600 * 1000L; System.out.println(result); }
TimeUtils { public static String getMediaPicTimeInString(final long time) { boolean isSameYear = sameYear(System.currentTimeMillis(), time); if (isSameYear) { return getSimpleDateFormat_2.get().format(new Date(time)); } else { return getSimpleDateFormat_3.get().format(new Date(time)); } } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getMediaPicTimeInString() throws Exception { }
TimeUtils { public static String getMediaVideoTimeInString(final long time) { return getSimpleDateFormatVideo.get().format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getMediaVideoTimeInString() throws Exception { }
LiveFrameRateMonitor implements IFeedRtcp { @Override public void stop() { preStatus = false; badFrameCount = 0; } @Override void feed(JFGMsgVideoRtcp rtcp); @Override void stop(); void setMonitorListener(MonitorListener monitorListener); }
@Test public void stop() throws Exception { }
TimeUtils { public static String getTodayString() { return new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault()) .format(new Date(System.currentTimeMillis())); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getTodayString() throws Exception { }
TimeUtils { public static String getDayString(long time) { return new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault()) .format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getDayString() throws Exception { }
TimeUtils { public static String getUptime(long time) { if (time == 0) return ContextUtils.getContext().getString(R.string.STANBY_TIME, 0, 0, 0); time = System.currentTimeMillis() / 1000 - time; int temp = (int) time / 60; int minute = temp % 60; temp = temp / 60; int hour = temp % 24; temp = temp / 24; int day = temp; return ContextUtils.getContext().getString(R.string.STANBY_TIME, day, hour, minute); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void testGetUptime() throws Exception { long time = System.currentTimeMillis() / 1000 - RandomUtils.getRandom(50) * 1000; time = 0; int temp = (int) time / 60; int minute = temp % 60; temp = temp / 60; int hour = temp % 24; temp = temp / 24; int day = temp; if (day > 0 && hour > 0) { System.out.println(String.format(Locale.CANADA, "%1$d天%2$d小时%3$d分", day, hour, minute)); } else if (hour > 0) { System.out.println(String.format(Locale.CANADA, "%1$d小时%2$d分", hour, minute)); } else { System.out.println(String.format(Locale.CANADA, "%1$d分", minute)); } }
TimeUtils { public static String getDayInMonth(long time) { Calendar instance = Calendar.getInstance(); instance.setTimeInMillis(time); int i = instance.get(Calendar.DAY_OF_MONTH); return i + ""; } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getDayInMonth() throws Exception { }
TimeUtils { public static String getMM_DD(long time) { return new SimpleDateFormat("MM月dd日", Locale.getDefault()) .format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getMM_DD() throws Exception { }
TimeUtils { public static String getHH_MM(long time) { return getSimpleDateFormatHHMM.get().format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getHH_MM() throws Exception { }
TimeUtils { public static String getHH_MM_Remain(long timeMs) { int totalMinutes = (int) (timeMs / 1000 / 60); int minutes = totalMinutes % 60; int hours = totalMinutes / 60; String str_hour = hours > 9 ? "" + hours : "0" + hours; String str_minute = minutes > 9 ? "" + minutes : "0" + minutes; return str_hour + ":" + str_minute; } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; }
@Test public void getHH_MM_Remain() throws Exception { }