Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add java 21 update fixes #409

Merged
merged 2 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ tasks.register('karateTest', Test) {
}

pmd {
toolVersion = '6.55.0'
toolVersion = '7.5.0'
ruleSetConfig = rootProject.resources.text.fromFile('config/pmd/ruleset.xml')
ruleSets = []
ignoreFailures = false
Expand Down
12 changes: 5 additions & 7 deletions config/pmd/ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
<exclude-pattern>.*/test/.*</exclude-pattern>

<rule ref="category/java/errorprone.xml">
<exclude name="DataflowAnomalyAnalysis"/>
<exclude name="MissingSerialVersionUID"/>
</rule>

<rule ref="category/java/multithreading.xml">
<!-- Because it complains for the Map interface in the Resource class.-->
<exclude name="UseConcurrentHashMap"/>
<!-- J2EE prohibits threads, while we don't use J2EE -->
<exclude name="DoNotUseThreads" />

</rule>

<rule ref="category/java/bestpractices.xml">
Expand All @@ -40,12 +42,6 @@
<exclude name="TooManyStaticImports"/>
<exclude name="ClassNamingConventions"/>
<exclude name="UnnecessaryConstructor"/>
<!-- Conflicts with the rule category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending -->
<exclude name="CommentDefaultAccessModifier"/>
<!-- Conflicts with the rule category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending -->
<exclude name="DefaultPackage"/>


<exclude name="ConfusingTernary"/>

<!-- printStackTrace is used in the Default Amazon handler in a static clause
Expand All @@ -63,6 +59,8 @@
<!-- Sometimes it is useful in debugging to assign the return value to a local variable -->
<exclude name="UnnecessaryLocalBeforeReturn"/>

<!-- We don't want to exclude use of "var" -->
<exclude name="UseExplicitTypes"/>

</rule>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public enum ParameterKeyBiobank implements IParameterKey {
public static final int IGNORE_PATH_PARAMETER_INDEX = 2;

public static final Set<ParameterKeyBiobank> VALID_QUERY_PARAMETERS =
Arrays.stream(ParameterKeyBiobank.values())
Arrays.stream(values())
.filter(ParameterKeyBiobank::ignorePathKeys)
.collect(Collectors.toSet());

Expand Down Expand Up @@ -103,16 +103,12 @@ public String toString() {
}

public static ParameterKeyBiobank keyFromString(String paramName, String value) {
var result = Arrays.stream(ParameterKeyBiobank.values())
.filter(ParameterKeyBiobank::ignorePathKeys)
.filter(IParameterKey.equalTo(paramName))
.collect(Collectors.toSet());
return result.size() == 1
? result.stream().findFirst().get()
: result.stream()
.filter(IParameterKey.hasValidValue(value))
.findFirst()
.orElse(INVALID);
return Arrays.stream(values())
.filter(ParameterKeyBiobank::ignorePathKeys)
.filter(IParameterKey.equalTo(paramName))
.distinct()
.reduce((first, second) -> IParameterKey.hasValidValue(value).test(second) ? second : first)
.orElse(INVALID);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Utils {
public final class Utils {

private static final Logger logger = LoggerFactory.getLogger(Utils.class);

Expand All @@ -40,6 +40,9 @@ public class Utils {
public static final String USER_IS_INTERNAL_BACKEND = "User is internal backend";
public static final String USER_TOP_LEVEL_CRISTIN_ORGANIZATION = "User has top level cristin organization {}";

private Utils() {
// NO-OP
}

/**
* Check if a string supplied is a positive integer.
Expand Down Expand Up @@ -130,7 +133,7 @@ public static String getValidOrgId(RequestInfo requestInfo) throws BadRequestExc


private static boolean isValidIdentifier(String identifier) {
return Utils.isPositiveInteger(identifier);
return isPositiveInteger(identifier);
}

/**
Expand Down Expand Up @@ -169,7 +172,7 @@ public static String extractCristinInstitutionIdentifier(RequestInfo requestInfo

private static String extractInstitution(URI organization) {
var organizationIdentifier = UriUtils.extractLastPathElement(organization);
return Utils.removeUnitPartFromIdentifierIfPresent(organizationIdentifier);
return removeUnitPartFromIdentifierIfPresent(organizationIdentifier);
}

private static BadRequestException failedToRetrieveTopLevelOrgCristinId() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,11 @@ private List<HttpResponse<String>> collectSuccessfulResponses(
.filter(Try::isSuccess)
.map(Try::get)
.filter(this::isSuccessfulRequest)
.collect(Collectors.toList());
.toList();
}

// This is reported as unused, but it is…
@SuppressWarnings("PMD.UnusedPrivateMethod")
private boolean isSuccessfulRequest(HttpResponse<String> response) {
try {
checkHttpStatusCode(response.uri(), response.statusCode(), response.body());
Expand Down
30 changes: 17 additions & 13 deletions cristin-commons/src/main/java/no/unit/nva/utils/AccessUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;

import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static java.net.http.HttpRequest.newBuilder;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static nva.commons.apigateway.AccessRight.MANAGE_CUSTOMERS;
import static nva.commons.apigateway.AccessRight.MANAGE_OWN_AFFILIATION;
import static nva.commons.core.attempt.Try.attempt;
Expand Down Expand Up @@ -80,23 +80,27 @@ public static boolean clientIsCustomerAdministrator(RequestInfo requestInfo) {
* Fetches an internal backend token from Cognito.
*/
public static String getBackendAccessToken() throws IOException, InterruptedException {
var cognitoTokenUrl = getCognitoTokenUrl();
var payload = GRANT_TYPE_PAYLOAD;

var request = newBuilder(cognitoTokenUrl)
.POST(HttpRequest.BodyPublishers.ofString(payload))
.header(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
.header(AUTHORIZATION, basicAuthHeader())
.build();
HttpClient client = HttpClient.newBuilder()
try (var client = createHttpClient()) {
var response = client.send(createTokenRequest(), ofString(StandardCharsets.UTF_8));
var jsonTree = JsonUtils.dtoObjectMapper.readTree(response.body());
return jsonTree.get(ACCESS_TOKEN).textValue();
}
}

private static HttpClient createHttpClient() {
return HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.connectTimeout(Duration.ofSeconds(30))
.build();
}

HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
var jsonTree = JsonUtils.dtoObjectMapper.readTree(response.body());
return jsonTree.get(ACCESS_TOKEN).textValue();
private static HttpRequest createTokenRequest() {
return newBuilder(getCognitoTokenUrl())
.POST(HttpRequest.BodyPublishers.ofString(GRANT_TYPE_PAYLOAD))
.header(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
.header(AUTHORIZATION, basicAuthHeader())
.build();
}

private static URI getCognitoTokenUrl() {
Expand Down
8 changes: 6 additions & 2 deletions cristin-commons/src/main/java/no/unit/nva/utils/UriUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@
import java.util.regex.Pattern;
import nva.commons.core.paths.UriWrapper;

public class UriUtils {
public final class UriUtils {

public static final String POSITION = "position";
public static final String PROJECT = "project";
public static final String PERSON = "person";
private static final String NATIONAL_IDENTITY_PATTERN = "national_id=(\\d+)(\\d{2})";

private UriUtils() {
// NO-OP
}

/**
* Create URI identifying NVA resource from path and identifier.
*
Expand Down Expand Up @@ -85,7 +89,7 @@ public static URI getNvaApiUri(String path) {

public static URI createNvaProjectId(String identifier) {
return new UriWrapper(HTTPS, DOMAIN_NAME)
.addChild(BASE_PATH).addChild(UriUtils.PROJECT).addChild(identifier).getUri();
.addChild(BASE_PATH).addChild(PROJECT).addChild(identifier).getUri();
}

public static String extractLastPathElement(URI uri) {
Expand Down
34 changes: 23 additions & 11 deletions cristin-commons/src/main/java/no/unit/nva/utils/UserUtils.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package no.unit.nva.utils;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.http.HttpResponse;
import no.unit.nva.cognito.CognitoUtil;
import no.unit.nva.commons.json.JsonUtils;
import nva.commons.core.paths.UriWrapper;
Expand All @@ -19,16 +18,20 @@

import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static java.net.http.HttpRequest.newBuilder;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static no.unit.nva.cristin.model.Constants.DOMAIN_NAME;
import static no.unit.nva.cristin.model.Constants.HTTPS;
import static no.unit.nva.utils.AccessUtils.BASIC;

public class UserUtils {
public final class UserUtils {

private static final Logger logger = LoggerFactory.getLogger(UserUtils.class);
public static final String RESPONSE_FROM_USER_CREATE = "Response from user create={}";
public static final String USER_CREATED_WITH_ROLES = "User {} created with role(s) '{}'";

private UserUtils() {
// NO-OP
}

/**
* Creates user in Cognito used for Karate tests.
Expand All @@ -50,20 +53,29 @@ public static void createUserWithRoles(String username, String password, String

private static void createNvaUserWithRoles(String nationalIdentityNumber, URI customerId, Set<String> roles)
throws IOException, InterruptedException {
try (var client = createHttpClient()) {
final var response = client.send(createHttpRequest(nationalIdentityNumber, customerId, roles),
ofString(StandardCharsets.UTF_8));
logger.info(RESPONSE_FROM_USER_CREATE, response);
}
}

private static HttpClient createHttpClient() {
return HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.connectTimeout(Duration.ofSeconds(30))
.build();
}

private static HttpRequest createHttpRequest(String nationalIdentityNumber,
URI customerId,
Set<String> roles) throws IOException, InterruptedException {
final var userRoles = new UserRoles(nationalIdentityNumber, customerId, roles);
final var body = JsonUtils.dtoObjectMapper.writeValueAsString(userRoles);
final var request = newBuilder(createUserServiceUri())
return newBuilder(createUserServiceUri())
.header(AUTHORIZATION, BASIC + AccessUtils.getBackendAccessToken())
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
final var client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.connectTimeout(Duration.ofSeconds(30))
.build();

final var response =
client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
logger.info(RESPONSE_FROM_USER_CREATE, response);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;

// The private fields in the record are viewed as unused, this is a bug
@SuppressWarnings("PMD.UnusedPrivateField")
public record CristinFundingSource(@JsonProperty(CODE_FIELD) String code,
@JsonProperty(NAME_FIELD) Map<String, String> name) {

Expand All @@ -14,5 +16,4 @@ public record CristinFundingSource(@JsonProperty(CODE_FIELD) String code,
public Map<String, String> name() {
return nonEmptyOrDefault(name);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ protected Integer getSuccessStatusCode(Void input, SearchResponse<Keyword> outpu
return HTTP_OK;
}

private ConcurrentHashMap<String, String> parseQueryParams(RequestInfo requestInfo) throws BadRequestException {
private Map<String, String> parseQueryParams(RequestInfo requestInfo) throws BadRequestException {
validateQueryParameterKeys(requestInfo);

var queryParams = new ConcurrentHashMap<String, String>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ public class CristinOrganizationApiClient
public static final String NULL_HTTP_RESPONSE_ERROR_MESSAGE = "No HttpResponse found";
public static final int SINGLE_HIT = 1;
public static final String UNIQUELY_IDENTIFY_ORGANIZATION = "Identifier does not uniquely identify organization";
public static final int FIRST_AND_ONLY_UNIT = 0;
private static final int NO_HITS = 0;

/**
Expand Down Expand Up @@ -120,12 +119,11 @@ public Organization executeFetch(Map<String, String> params) throws ApiGatewayEx

private Organization extractOrganization(String identifier, HttpResponse<String> response)
throws ApiGatewayException {
List<SubUnitDto> units = attempt(() ->
OBJECT_MAPPER.readValue(response.body(), new TypeReference<List<SubUnitDto>>() {
}))
var type = new TypeReference<List<SubUnitDto>>() {};
List<SubUnitDto> units = attempt(() -> OBJECT_MAPPER.readValue(response.body(), type))
.orElseThrow(fail -> new FailedHttpRequestException(fail.getException()));
if (SINGLE_HIT == units.size()) {
return toOrganization(identifier, units.get(FIRST_AND_ONLY_UNIT));
return toOrganization(identifier, units.getFirst());
} else {
throw new BadRequestException(UNIQUELY_IDENTIFY_ORGANIZATION);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ protected Integer getSuccessStatusCode(Void input, SearchResponse<Organization>
return HttpURLConnection.HTTP_OK;
}

private ConcurrentHashMap<String, String> extractQueryParameters(RequestInfo requestInfo)
private Map<String, String> extractQueryParameters(RequestInfo requestInfo)
throws BadRequestException {

var requestQueryParams = new ConcurrentHashMap<String, String>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import static no.unit.nva.utils.UriUtils.getNvaApiId;
import static nva.commons.core.attempt.Try.attempt;

@SuppressWarnings("PMD.CouplingBetweenObjects")
public class CristinPersonApiClient extends ApiClient
implements ClientVersion,
CristinAuthorizedQueryClient<Map<String, String>, Person> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
import static no.unit.nva.cristin.model.Constants.PERSON_PATH_NVA;
import static no.unit.nva.cristin.person.model.nva.JsonPropertyNames.NATIONAL_IDENTITY_NUMBER;

@SuppressWarnings({"unused", "PMD.GodClass", "PMD.TooManyFields", "PMD.ExcessivePublicCount"})
@SuppressWarnings({"unused", "PMD.GodClass", "PMD.TooManyFields", "PMD.ExcessivePublicCount",
"PMD.CouplingBetweenObjects"})
@JacocoGenerated
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class CristinPerson implements JsonSerializable {
Expand Down Expand Up @@ -394,11 +395,8 @@ private Set<Employment> extractEmployments() {
private Boolean extractVerified() {
if (nonNull(getIdentifiedCristinPerson()) && getIdentifiedCristinPerson()) {
return true;
} else if (isNviVerified()) {
return true;
} else {
return getIdentifiedCristinPerson();
}
return isNviVerified() || Boolean.TRUE.equals(getIdentifiedCristinPerson());
}

private boolean isNviVerified() {
Expand Down
Loading
Loading