Skip to content

Commit

Permalink
Fix StringIndexOutOfBoundsException for license (#122)
Browse files Browse the repository at this point in the history
  • Loading branch information
rpanman-sonatype authored Feb 26, 2024
1 parent 576a55f commit 133320e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

import org.sonatype.cs.getmetrics.service.PolicyIdsService;
import org.sonatype.cs.getmetrics.service.UtilService;

import java.util.ArrayList;
import java.util.List;

import javax.json.JsonArray;
import javax.json.JsonObject;

Expand Down Expand Up @@ -52,13 +50,15 @@ private static String getCVE(JsonArray reasons) {
return cveList;
}

private static String getLicense(JsonArray reasons) {
public static String getLicense(JsonArray reasons) {
String licenseList = "";
List<String> licenses = new ArrayList<>();

for (JsonObject reason : reasons.getValuesAs(JsonObject.class)) {
String licenseFound = reason.getString("reason");

if (licenseFound.isEmpty()){
continue;
}
String license =
licenseFound.substring(
licenseFound.indexOf("(") + 1, licenseFound.indexOf(")"));
Expand All @@ -69,11 +69,18 @@ private static String getLicense(JsonArray reasons) {
}
}

for (String l : licenses) {
licenseList = l + ":" + licenseList;
if (licenses.size()==0){
return "";
}

licenseList = UtilService.removeLastChar(licenseList);
for (String l : licenses) {
if (licenseList.isEmpty()){
licenseList = l;
}
else{
licenseList = licenseList + ":" +l;
}
}

return licenseList;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.sonatype.cs.getmetrics.util;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.json.Json;
import javax.json.JsonArray;

public class ParseReasonsTest {
@Test
void testEmptyLicenseString() {
JsonArray reasons = Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("reason", ""))
.build();

String actualReason = ParseReasons.getLicense(reasons);
Assertions.assertEquals("", actualReason);
}

@Test
void testSingleLicenseString() {
JsonArray reasons = Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("reason", "(license)"))
.build();

String actualReason = ParseReasons.getLicense(reasons);
Assertions.assertEquals("license", actualReason);
}

@Test
void testMultipltLicenseString() {
JsonArray reasons = Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("reason", "(license)")
)
.add(Json.createObjectBuilder()
.add("reason", "(license2)")
)
.build();

String actualReason = ParseReasons.getLicense(reasons);
Assertions.assertEquals("license:license2", actualReason);
}
}

0 comments on commit 133320e

Please sign in to comment.