From 42d06558739fb0a6f3a6ad5fb38e6ec799e40bc1 Mon Sep 17 00:00:00 2001 From: Nikesh kumar Date: Thu, 16 Jan 2025 14:52:28 +0530 Subject: [PATCH] fix(rest): Add license information linking for project releases. Signed-off-by: Nikesh kumar --- .../project/ProjectController.java | 73 ++++++++++++++ .../project/Sw360ProjectService.java | 97 +++++++++++++++++++ .../restdocs/ProjectSpecTest.java | 15 +++ 3 files changed, 185 insertions(+) diff --git a/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/ProjectController.java b/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/ProjectController.java index 5ff76cb89d..30fc29500a 100644 --- a/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/ProjectController.java +++ b/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/ProjectController.java @@ -101,6 +101,7 @@ import org.eclipse.sw360.rest.resourceserver.vulnerability.Sw360VulnerabilityService; import org.eclipse.sw360.rest.resourceserver.vulnerability.VulnerabilityController; import org.jetbrains.annotations.NotNull; +import org.jose4j.json.internal.json_simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.GsonJsonParser; import org.springframework.data.domain.Pageable; @@ -119,6 +120,7 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -192,6 +194,8 @@ public class ProjectController implements RepresentationModelProcessor enumMainlineStateValues = Stream.of(MainlineState.values()) .map(MainlineState::name) .collect(Collectors.toList()); + private static final ImmutableMap RESPONSE_BODY_FOR_MODERATION_REQUEST_WITH_COMMIT = ImmutableMap.builder() + .put("message", "Unauthorized user or empty commit message passed.").build(); @NonNull private final Sw360ProjectService projectService; @@ -3480,4 +3484,73 @@ public ResponseEntity createDuplicateProjectWithDependencyNetwork( return true; }; } + + @Operation( + summary = "Add licenses to linked releases of a project.", + description = "This API adds license information to linked releases of a project by processing the approved CLI attachments for each release. It categorizes releases based on the number of CLI attachments (single, multiple, or none) and updates their main and other licenses accordingly.", + tags = {"Project"}, + parameters = { + @Parameter( + name = "projectId", + description = "The ID of the project whose linked releases need license updates.", + required = true, + example = "12345", + schema = @Schema(type = "string") + ) + }, + responses = { + @ApiResponse( + responseCode = "200", + description = "License information successfully added to linked releases.", + content = @Content( + mediaType = "application/hal+json", + schema = @Schema(type = "object", implementation = JSONObject.class), + examples = @ExampleObject( + value = "{\n \"one\": [\"Release1\", \"Release2\"],\n \"mul\": [\"Release3\"]\n}" + ) + ) + ), + @ApiResponse( + responseCode = "500", + description = "Error occurred while processing license information for linked releases.", + content = @Content( + mediaType = "application/json", + examples = @ExampleObject( + value = "{\n \"error\": \"Error adding license info to linked releases.\"\n}" + ) + ) + ) + } + ) + @PostMapping(value = PROJECTS_URL + "/{id}/addLinkedRelesesLicenses") + public ResponseEntity addLicenseToLinkedReleases( + @Parameter(description = "Project ID", example = "376576") + @PathVariable("id") String projectId, + @Parameter(description = "Comment message.") + @RequestParam(value = "comment", required = false) String comment + ) throws TTransportException, TException { + try { + User sw360User = restControllerHelper.getSw360UserFromAuthentication(); + sw360User.setCommentMadeDuringModerationRequest(comment); + Project project = projectService.getProjectForUserById(projectId, sw360User); + + if (!restControllerHelper.isWriteActionAllowed(project, sw360User) && comment == null) { + return new ResponseEntity<>(RESPONSE_BODY_FOR_MODERATION_REQUEST_WITH_COMMIT, HttpStatus.BAD_REQUEST); + } + RequestStatus requestStatus = projectService.addLicenseToLinkedReleases(projectId, sw360User); + + switch (requestStatus) { + case SENT_TO_MODERATOR: + return new ResponseEntity<>(RESPONSE_BODY_FOR_MODERATION_REQUEST, HttpStatus.ACCEPTED); + case SUCCESS: + return ResponseEntity.ok().body(Map.of("message", "License information successfully added to linked releases.")); + default: + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error adding license info to linked releases."); + } + + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Error adding license info to linked releases: " + e.getMessage()); + } + } } diff --git a/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/Sw360ProjectService.java b/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/Sw360ProjectService.java index d240064e75..56414393dd 100644 --- a/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/Sw360ProjectService.java +++ b/rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/project/Sw360ProjectService.java @@ -1543,4 +1543,101 @@ public List serveLinkedReleasesInDependencyNetworkByIndexPath(Strin ProjectService.Iface sw360ProjectClient = getThriftProjectClient(); return sw360ProjectClient.getReleaseLinksOfProjectNetWorkByIndexPath(projectId, indexPath, sw360User); } + + public RequestStatus addLicenseToLinkedReleases(String projectId, User sw360User) + throws TTransportException, TException { + ThriftClients thriftClients = new ThriftClients(); + ProjectService.Iface projectClient = getThriftProjectClient(); + LicenseInfoService.Iface licenseInfoClient = thriftClients.makeLicenseInfoClient(); + ComponentService.Iface componentClient = thriftClients.makeComponentClient(); + JSONObject jsonResult = new JSONObject(); + + try { + Project project = projectClient.getProjectById(projectId, sw360User); + if (project == null) { + throw new IllegalArgumentException("Project with ID " + projectId + " not found."); + } + + Set releaseIds = CommonUtils.getNullToEmptyKeyset(project.getReleaseIdToUsage()); + List releasesWithSingleCLI = new ArrayList<>(); + List releasesWithMultipleCLI = new ArrayList<>(); + boolean isModerationRequired = false; + + for (String releaseId : releaseIds) { + Release release = componentClient.getReleaseById(releaseId, sw360User); + if (release == null) { + throw new IllegalArgumentException("Release with ID " + releaseId + " not found."); + } + + List approvedCliAttachments = SW360Utils.getApprovedClxAttachmentForRelease(release); + if (approvedCliAttachments.isEmpty()) { + approvedCliAttachments = SW360Utils.getClxAttachmentForRelease(release); + } + + if (approvedCliAttachments.size() == 1) { + processSingleAttachment(approvedCliAttachments.get(0), release, licenseInfoClient, sw360User); + releasesWithSingleCLI.add(release); + } else { + if (approvedCliAttachments.size() > 1) { + releasesWithMultipleCLI.add(release); + } + jsonResult.put(SW360Constants.STATUS, SW360Constants.FAILURE); + isModerationRequired = true; + } + + componentClient.updateRelease(release, sw360User); + } + + jsonResult.put("releasesWithSingleCLI", releasesWithSingleCLI); + jsonResult.put("releasesWithMultipleCLI", releasesWithMultipleCLI); + + if (isModerationRequired) { + return RequestStatus.SENT_TO_MODERATOR; + } + + return RequestStatus.SUCCESS; + + } catch (Exception e) { + throw new RuntimeException("Error processing linked releases for project: " + projectId, e); + } + } + + + private void processSingleAttachment(Attachment attachment, Release release, + LicenseInfoService.Iface licenseInfoClient, User sw360User) throws TTransportException, TException { + String attachmentName = attachment.getFilename(); + + Set mainLicenses = new HashSet<>(); + Set otherLicenses = new HashSet<>(); + + List licenseInfoResults = licenseInfoClient.getLicenseInfoForAttachment(release, + attachment.getAttachmentContentId(), true, sw360User); + + if (attachmentName.endsWith(SW360Constants.RDF_FILE_EXTENSION)) { + licenseInfoResults.forEach(result -> { + if (result.getLicenseInfo() != null) { + mainLicenses.addAll(result.getLicenseInfo().getConcludedLicenseIds()); + otherLicenses.addAll(result.getLicenseInfo().getLicenseNamesWithTexts().stream() + .map(LicenseNameWithText::getLicenseName).collect(Collectors.toSet())); + } + }); + otherLicenses.removeAll(mainLicenses); + } else if (attachmentName.endsWith(SW360Constants.XML_FILE_EXTENSION)) { + licenseInfoResults.forEach(result -> { + if (result.getLicenseInfo() != null) { + result.getLicenseInfo().getLicenseNamesWithTexts().forEach(license -> { + if (SW360Constants.LICENSE_TYPE_GLOBAL.equals(license.getType())) { + mainLicenses.add(license.getLicenseName()); + } else { + otherLicenses.add(license.getLicenseName()); + } + }); + } + }); + } + + release.setMainLicenseIds(mainLicenses); + release.setOtherLicenseIds(otherLicenses); + } + } diff --git a/rest/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/ProjectSpecTest.java b/rest/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/ProjectSpecTest.java index 00187ea0cb..50ed2edc41 100644 --- a/rest/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/ProjectSpecTest.java +++ b/rest/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/ProjectSpecTest.java @@ -73,6 +73,8 @@ import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.eclipse.sw360.rest.resourceserver.vulnerability.Sw360VulnerabilityService; import org.hamcrest.Matchers; +import org.jose4j.json.internal.json_simple.JSONArray; +import org.jose4j.json.internal.json_simple.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -3250,4 +3252,17 @@ public void should_document_get_projects_by_advance_search() throws Exception { fieldWithPath("page.number").description("Number of the current page") ))); } + + @Test + public void should_add_license_to_linked_releases() throws Exception { + String projectId = "1234567"; + String comment = "This is a test comment"; + when(projectServiceMock.addLicenseToLinkedReleases(eq(projectId), any(User.class))).thenReturn(RequestStatus.SUCCESS); + + MockHttpServletRequestBuilder requestBuilder = post("/api/projects/" + projectId + "/addLinkedRelesesLicenses") + .contentType(MediaType.APPLICATION_JSON) + .param("comment", comment) + .header("Authorization", TestHelper.generateAuthHeader(testUserId, testUserPassword)); + this.mockMvc.perform(requestBuilder).andExpect(status().isOk()).andDo(this.documentationHandler.document()); + } }