Skip to content

Commit

Permalink
Remove oneMillion API-Call completly
Browse files Browse the repository at this point in the history
  • Loading branch information
Reamer committed Nov 11, 2024
1 parent 49ef2b2 commit 7f1ce5d
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 161 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public final class ResourceConstants {

public static final String V1_BOM = "/api/v1/bom";
public static final String V1_BOM_TOKEN_UUID = "/api/v1/bom/token/{uuid}";
public static final String V1_PROJECT = "/api/v1/project?limit=1000000&offset=0";
public static final String V1_PROJECT_LOOKUP = "/api/v1/project/lookup";
public static final String V1_PROJECT_UUID = "/api/v1/project/{uuid}";
public static final String V1_FINDING_PROJECT_UUID = "/api/v1/finding/project/{uuid}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Optional;

import static io.github.pmckeown.dependencytrack.ResourceConstants.V1_PROJECT;
import static io.github.pmckeown.dependencytrack.ResourceConstants.V1_PROJECT_UUID;
import static io.github.pmckeown.dependencytrack.ResourceConstants.V1_PROJECT_LOOKUP;
import static kong.unirest.Unirest.*;
Expand All @@ -33,21 +31,6 @@ public ProjectClient(CommonConfig commonConfig) {
this.commonConfig = commonConfig;
}

public Response<List<Project>> getProjects() {
HttpResponse<List<Project>> httpResponse = get(commonConfig.getDependencyTrackBaseUrl() + V1_PROJECT)
.header(X_API_KEY, commonConfig.getApiKey())
.asObject(new GenericType<List<Project>>(){});

Optional<List<Project>> body;
if (httpResponse.isSuccess()) {
body = Optional.of(httpResponse.getBody());
} else {
body = Optional.empty();
}

return new Response<>(httpResponse.getStatus(), httpResponse.getStatusText(), httpResponse.isSuccess(), body);
}

public Response<Project> getProject(String projectName, String projectVersion) {
HttpResponse<Project> httpResponse = get(commonConfig.getDependencyTrackBaseUrl() + V1_PROJECT_LOOKUP)
.queryString("name", projectName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Optional;

import static io.github.pmckeown.dependencytrack.Constants.DELIMITER;
Expand Down Expand Up @@ -41,9 +40,9 @@ public ScoreAction(ProjectClient projectClient, MetricsAction metricsAction, Com

Integer determineScore(Integer inheritedRiskScoreThreshold) throws DependencyTrackException {
try {
Response<List<Project>> response = projectClient.getProjects();
Response<Project> response = projectClient.getProject(commonConfig.getProjectName(), commonConfig.getProjectVersion());

Optional<List<Project>> body = response.getBody();
Optional<Project> body = response.getBody();
if (response.isSuccess() && body.isPresent()) {
return generateResult(body.get(), inheritedRiskScoreThreshold);
} else {
Expand All @@ -55,25 +54,13 @@ Integer determineScore(Integer inheritedRiskScoreThreshold) throws DependencyTra
}
}

private Integer generateResult(List<Project> projects, Integer inheritedRiskScoreThreshold)
private Integer generateResult(Project project, Integer inheritedRiskScoreThreshold)
throws DependencyTrackException {
logger.debug(projects.toString());
logger.debug("Found %s projects", projects.size());
Metrics metrics = getMetricsFromProject(project);

Optional<Project> projectOptional = findCurrentProject(projects);
if (projectOptional.isPresent()) {
Project project = projectOptional.get();
printInheritedRiskScore(project, metrics.getInheritedRiskScore(), inheritedRiskScoreThreshold);

Metrics metrics = getMetricsFromProject(project);

printInheritedRiskScore(project, metrics.getInheritedRiskScore(), inheritedRiskScoreThreshold);

return metrics.getInheritedRiskScore();

} else {
throw new DependencyTrackException(format("Failed to find project on server: Project: %s, Version: %s",
commonConfig.getProjectName(), commonConfig.getProjectVersion()));
}
return metrics.getInheritedRiskScore();
}

private Metrics getMetricsFromProject(Project project) throws DependencyTrackException {
Expand Down Expand Up @@ -102,18 +89,4 @@ private void printInheritedRiskScore(Project project, int inheritedRiskScore, In
}
logger.info(DELIMITER);
}

private Optional<Project> findCurrentProject(List<Project> projects) {
logger.debug("Searching for project using Name: [%s] and Version [%s]",
commonConfig.getProjectName(), commonConfig.getProjectVersion());

// Output each project when debug is enabled
projects.forEach(project -> logger.debug(project.toString()));

return projects.stream()
.parallel()
.filter(project -> project.getName().equals(commonConfig.getProjectName()))
.filter(project -> project.getVersion().equals(commonConfig.getProjectVersion()))
.findFirst();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ public class TestResourceConstants {
public static final String V1_METRICS_PROJECT_CURRENT = "/api/v1/metrics/project/(.*)/current";
public static final String V1_METRICS_PROJECT_REFRESH = "/api/v1/metrics/project/(.*)/refresh";
public static final String V1_PROJECT_UUID = "/api/v1/project/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})";
public static final String V1_PROJECT_WITH_ONE_MILLION_LIMIT = "/api/v1/project?limit=1000000&offset=0";
public static final String V1_BOM_TOKEN_UUID = "/api/v1/bom/token/(.*)";
public static final String V1_FINDING_PROJECT_UUID = "/api/v1/finding/project/(.*)";
public static final String V1_POLICY_VIOLATION_PROJECT_UUID = "/api/v1/violation/project/(.*)";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,21 @@
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;
import java.util.List;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.exactly;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.patch;
import static com.github.tomakehurst.wiremock.client.WireMock.patchRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static io.github.pmckeown.dependencytrack.TestResourceConstants.V1_PROJECT_UUID;
import static io.github.pmckeown.dependencytrack.TestResourceConstants.V1_PROJECT_WITH_ONE_MILLION_LIMIT;
import static io.github.pmckeown.dependencytrack.project.ProjectInfoBuilder.aProjectInfo;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class ProjectClientIntegrationTest extends AbstractDependencyTrackMojoTest {

private static final int COUNT_ALL_PROJECTS = 9;

private ProjectClient projectClient;

@Before
Expand All @@ -40,18 +31,6 @@ public void setUp() {
projectClient = new ProjectClient(commonConfig);
}

@Test
public void thatCallingDependencyTrackWithAHighResponseLimitReturnsAllProjects() {

stubFor(get(urlEqualTo(V1_PROJECT_WITH_ONE_MILLION_LIMIT)).willReturn(
aResponse().withBodyFile("api/v1/project/get-all-projects.json")));

List<Project> projects = projectClient.getProjects().getBody().orElse(Collections.emptyList());

verify(exactly(1), getRequestedFor(urlEqualTo(V1_PROJECT_WITH_ONE_MILLION_LIMIT)));
assertThat(projects.size(), is(COUNT_ALL_PROJECTS));
}

@Test
public void thatProjectInfoUpdateReturnsSuccessWhenServerReturnsSuccess() {
stubFor(patch(urlPathMatching(V1_PROJECT_UUID)).willReturn(
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.github.pmckeown.dependencytrack.project.ProjectClient;
import io.github.pmckeown.util.Logger;
import kong.unirest.UnirestException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
Expand All @@ -17,13 +18,12 @@
import static io.github.pmckeown.dependencytrack.metrics.MetricsBuilder.aMetrics;
import static io.github.pmckeown.dependencytrack.project.ProjectBuilder.aProject;
import static io.github.pmckeown.dependencytrack.ResponseBuilder.aSuccessResponse;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
Expand All @@ -34,8 +34,6 @@
public class ScoreActionTest {

private static final Integer INHERITED_RISK_SCORE_THRESHOLD = 3;
private static final String PROJECT_VERSION = "projectVersion";
private static final String PROJECT_NAME = "projectName";

@InjectMocks
private ScoreAction scoreAction;
Expand All @@ -52,52 +50,30 @@ public class ScoreActionTest {
@Mock
private Logger logger;

@Test
public void thatWhenAnExceptionOccursGettingProjectsThenAnExceptionIsThrown() {
doThrow(UnirestException.class).when(projectClient).getProjects();

try {
scoreAction.determineScore(INHERITED_RISK_SCORE_THRESHOLD);
fail("Exception expected");
} catch (DependencyTrackException ex) {
assertThat(ex, is(instanceOf(DependencyTrackException.class)));
}
}
@Test(expected = DependencyTrackException.class)
public void thatWhenAnExceptionOccursGettingProjectsThenAnExceptionIsThrown() throws DependencyTrackException {
doReturn("ProjectName").when(commonConfig).getProjectName();
doReturn("ProjectVersion").when(commonConfig).getProjectVersion();
doThrow(UnirestException.class).when(projectClient).getProject(anyString(), anyString());

@Test
public void thatWhenNoProjectsAreFoundThenAnExceptionIsThrown() {
doReturn(new Response(404, "Not Found", false)).when(projectClient).getProjects();

try {
scoreAction.determineScore(INHERITED_RISK_SCORE_THRESHOLD);
fail("Exception expected");
} catch (DependencyTrackException ex) {
assertThat(ex, is(instanceOf(DependencyTrackException.class)));
}
scoreAction.determineScore(INHERITED_RISK_SCORE_THRESHOLD);
fail("Exception expected");
}

@Test
public void thatWhenCurrentProjectsIsNotFoundInListThenAnExceptionIsThrown() {
doReturn(aSuccessResponse().withBody(
singletonList(
aProject().withMetrics(aMetrics().withInheritedRiskScore(100)).build()
)).build()).when(projectClient).getProjects();
doReturn("unknown-project").when(commonConfig).getProjectName();
doReturn("1.2.3").when(commonConfig).getProjectVersion();

try {
scoreAction.determineScore(INHERITED_RISK_SCORE_THRESHOLD);
fail("Exception expected");
} catch (DependencyTrackException ex) {
assertThat(ex, is(instanceOf(DependencyTrackException.class)));
}
@Test(expected = DependencyTrackException.class)
public void thatWhenNoProjectsAreFoundThenAnExceptionIsThrown() throws DependencyTrackException {
doReturn("ProjectName").when(commonConfig).getProjectName();
doReturn("ProjectVersion").when(commonConfig).getProjectVersion();
doReturn(new Response(404, "Not Found", false)).when(projectClient).getProject(anyString(), anyString());

scoreAction.determineScore(INHERITED_RISK_SCORE_THRESHOLD);
fail("Exception expected");
}

@Test
public void thatWhenTheCurrentProjectHasMetricsInItThenTheScoreIsReturned() throws Exception {
Project project = aProject().withMetrics(aMetrics().withInheritedRiskScore(100)).build();
doReturn(aSuccessResponse().withBody(
singletonList(project)).build()).when(projectClient).getProjects();
doReturn(aSuccessResponse().withBody(project).build()).when(projectClient).getProject(anyString(), anyString());
doReturn(project.getName()).when(commonConfig).getProjectName();
doReturn(project.getVersion()).when(commonConfig).getProjectVersion();

Expand All @@ -110,8 +86,7 @@ public void thatWhenTheCurrentProjectHasMetricsInItThenTheScoreIsReturned() thro
@Test
public void thatWhenTheCurrentProjectHasNoMetricsInItTheyAreRequestedAndThenTheScoreIsReturned() throws Exception {
Project project = aProject().build();
doReturn(aSuccessResponse().withBody(
singletonList(project)).build()).when(projectClient).getProjects();
doReturn(aSuccessResponse().withBody(project).build()).when(projectClient).getProject(anyString(), anyString());
doReturn(aMetrics().withInheritedRiskScore(100).build()).when(metricsAction).getMetrics(
any(Project.class));
doReturn(project.getName()).when(commonConfig).getProjectName();
Expand All @@ -126,8 +101,7 @@ public void thatWhenTheCurrentProjectHasNoMetricsInItTheyAreRequestedAndThenTheS
@Test
public void thatWhenTheCurrentProjectScoreIsZeroThenTheScoreIsReturned() throws Exception {
Project project = aProject().build();
doReturn(aSuccessResponse().withBody(
singletonList(project)).build()).when(projectClient).getProjects();
doReturn(aSuccessResponse().withBody(project).build()).when(projectClient).getProject(anyString(), anyString());
doReturn(aMetrics().withInheritedRiskScore(0).build()).when(metricsAction).getMetrics(
any(Project.class));
doReturn(project.getName()).when(commonConfig).getProjectName();
Expand Down
Loading

0 comments on commit 7f1ce5d

Please sign in to comment.