apply plugin: 'org.springframework.boot'
apply plugin: 'com.gorylenko.gradle-git-properties'
apply plugin: 'jacoco'
+apply plugin: 'com.diffplug.spotless'
dependencyManagement {
imports {
test.finalizedBy jacocoTestReport
configurations.implementation.setCanBeResolved(true)
+
+spotless {
+ java {
+ removeUnusedImports()
+ trimTrailingWhitespace()
+ googleJavaFormat('1.15.0')
+ }
+}
+
+tasks.withType(JavaCompile) {
+ dependsOn 'spotlessApply'
+}
\ No newline at end of file
package org.onap.portal.bff;
-import static io.vavr.API.None;
-import static io.vavr.API.Some;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.specification.RequestSpecification;
-import io.vavr.collection.List;
-import io.vavr.control.Option;
+import java.net.URISyntaxException;
import java.time.Clock;
import java.time.OffsetDateTime;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
import java.util.UUID;
+import org.apache.http.client.utils.URIBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.onap.portal.bff.config.IdTokenExchangeFilterFunction;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
-import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
return TokenGenerator.TokenGeneratorConfig.builder()
.port(port)
.realm(realm)
- .roles(List.of(role))
+ .roles(Collections.singletonList(role))
.build();
}
return UUID.randomUUID().toString();
}
- public static String adjustPath(String basePath, Option<Integer> page, Option<Integer> pageSize) {
- return adjustPath(basePath, page, pageSize, None());
+ public static String adjustPath(
+ String basePath, Optional<Integer> page, Optional<Integer> pageSize) {
+ return adjustPath(basePath, page, pageSize, Optional.empty());
}
public static String adjustPath(
- String basePath, Option<Integer> page, Option<Integer> pageSize, Option<String> filter) {
- return page.map(pg -> basePath + "?page=" + pg)
- .fold(
- () -> pageSize.map(pgs -> basePath + "?pageSize=" + pgs),
- pth -> pageSize.map(pgs -> pth + "&pageSize=" + pgs).orElse(Some(pth)))
- .fold(
- () -> filter.map(f -> basePath + "?filter=" + f),
- pth -> filter.map(f -> pth + "&filter=" + f).orElse(Some(pth)))
- .getOrElse(basePath);
+ String basePath,
+ Optional<Integer> page,
+ Optional<Integer> pageSize,
+ Optional<String> filter) {
+ URIBuilder builder;
+ try {
+ builder = new URIBuilder(basePath);
+ if (page.isPresent()) {
+ builder.addParameter("page", String.valueOf(page.get()));
+ }
+ if (pageSize.isPresent()) {
+ builder.addParameter("pageSize", String.valueOf(pageSize.get()));
+ }
+ if (filter.isPresent()) {
+ builder.addParameter("filter", filter.get());
+ }
+ return builder.build().toString();
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ }
+ return basePath;
}
}
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
-import io.vavr.collection.List;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
+import java.util.Collections;
import java.util.Date;
+import java.util.List;
import java.util.UUID;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
private final JWKSet jwkSet;
private final JWSSigner signer;
- @Autowired
public TokenGenerator(Clock clock) {
try {
this.clock = clock;
@NonNull @Builder.Default private final Duration expireIn = Duration.ofMinutes(5);
- @Builder.Default private final List<String> roles = List.empty();
+ @Builder.Default private final List<String> roles = Collections.emptyList();
public String issuer() {
return String.format("http://localhost:%d/auth/realms/%s", port, realm);
@Test
void xRequestIdHeaderIsCorrectlySetInResponse() throws Exception {
// use preferences endpoint for testing the header
- final PreferencesPortalPrefsDto preferencesPortalPrefsDto =
- new PreferencesPortalPrefsDto();
+ final PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
- //mockGetTile(tileDetailResponsePortalServiceDto, X_REQUEST_ID);
+ // mockGetTile(tileDetailResponsePortalServiceDto, X_REQUEST_ID);
mockGetPreferences(preferencesPortalPrefsDto, X_REQUEST_ID);
final String response = getPreferencesExtractHeader(X_REQUEST_ID);
assertThat(response).isEqualTo(X_REQUEST_ID);
}
- protected void mockGetPreferences(PreferencesPortalPrefsDto preferencesPortalPrefsDto, String xRequestId)
- throws Exception {
+ protected void mockGetPreferences(
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto, String xRequestId) throws Exception {
WireMock.stubFor(
WireMock.get(WireMock.urlEqualTo("/v1/preferences"))
.withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
package org.onap.portal.bff.users;
-import static io.vavr.API.List;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.API;
-import io.vavr.collection.List;
+import java.util.Collections;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
.username("user1")
.email("user1@localhost.com")
.enabled(true)
- .requiredActions(List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList());
+ .requiredActions(List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD));
final String userId = randomUUID();
mockCreateUser(keycloakRequest, userId);
mockGetUser(userId, keycloakResponse);
final RoleKeycloakDto onapAdmin = new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
- mockAddRoles(userId, List(onapAdmin));
- mockAssignedRoles(userId, List(onapAdmin));
- mockListRealmRoles(List(onapAdmin));
+ mockAddRoles(userId, List.of(onapAdmin));
+ mockAssignedRoles(userId, List.of(onapAdmin));
+ mockListRealmRoles(List.of(onapAdmin));
requestSpecification()
.given()
.extract()
.body()
.as(RoleListResponseApiDto.class);
- mockSendUpdateEmail(userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD));
+ mockSendUpdateEmail(userId, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD));
final CreateUserRequestApiDto request =
new CreateUserRequestApiDto()
.username("user1")
.email("user1@localhost.com")
.enabled(true)
- .requiredActions(List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList());
+ .requiredActions(List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD));
final String userId = randomUUID();
mockCreateUser(keycloakRequest, userId);
mockGetUser(userId, keycloakResponse);
final RoleKeycloakDto onapAdmin = new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
- mockAddRoles(userId, List(onapAdmin));
- mockListRealmRoles(List(onapAdmin));
+ mockAddRoles(userId, List.of(onapAdmin));
+ mockListRealmRoles(List.of(onapAdmin));
final ErrorResponseKeycloakDto keycloakErrorResponse =
new ErrorResponseKeycloakDto().errorMessage("Some error message");
mockSendUpdateEmailWithProblem(
- userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD), keycloakErrorResponse);
+ userId, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD), keycloakErrorResponse);
final CreateUserRequestApiDto request =
new CreateUserRequestApiDto()
void userCanNotBeCreatedWithNonexistentRoles() throws Exception {
String xRequestID = "addf6005-3075-4c80-b7bc-2c70b7d42b57";
- mockListRealmRoles(List());
+ mockListRealmRoles(Collections.emptyList());
final CreateUserRequestApiDto request =
new CreateUserRequestApiDto()
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
package org.onap.portal.bff.users;
-import static io.vavr.API.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
-import io.vavr.control.Option;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
mockGetUserCount(2);
mockListUsers(List.of(tAdmin, tDesigner), 0, 10);
- mockListRealmRoles(List(ONAP_ADMIN, OFFLINE_ACCESS));
- mockListRoleUsers(OFFLINE_ACCESS.getName(), List(tAdmin, tDesigner));
- mockListRoleUsers(ONAP_ADMIN.getName(), List(tAdmin));
+ mockListRealmRoles(List.of(ONAP_ADMIN, OFFLINE_ACCESS));
+ mockListRoleUsers(OFFLINE_ACCESS.getName(), List.of(tAdmin, tDesigner));
+ mockListRoleUsers(ONAP_ADMIN.getName(), List.of(tAdmin));
final UserResponseApiDto expectedTAdmin =
new UserResponseApiDto()
mockGetUserCount(1);
mockListUsers(List.of(keycloakUser), 60, 30);
- mockListRealmRoles(List());
+ mockListRealmRoles(Collections.emptyList());
- final UserListResponseApiDto response = listUsers(Some(3), Some(30));
+ final UserListResponseApiDto response = listUsers(Optional.of(3), Optional.of(30));
assertThat(response).isNotNull();
assertThat(response.getTotalCount()).isEqualTo(1);
assertThat(response.getItems())
mockGetUserCount(55);
mockListUsersWithProblems(keycloakErrorResponse, 60, 30);
- mockListRealmRoles(List());
+ mockListRealmRoles(Collections.emptyList());
ProblemApiDto response =
requestSpecification()
.accept(MediaType.APPLICATION_JSON_VALUE)
.header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
.when()
- .get(adjustPath("/users", Some(3), Some(30)))
+ .get(adjustPath("/users", Optional.of(3), Optional.of(30)))
.then()
.statusCode(HttpStatus.BAD_GATEWAY.value())
.extract()
}
protected UserListResponseApiDto listUsers() {
- return listUsers(None(), None());
+ return listUsers(Optional.empty(), Optional.empty());
}
- protected UserListResponseApiDto listUsers(Option<Integer> page, Option<Integer> pageSize) {
+ protected UserListResponseApiDto listUsers(Optional<Integer> page, Optional<Integer> pageSize) {
return requestSpecification()
.given()
.accept(MediaType.APPLICATION_JSON_VALUE)
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.Collections;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
final List<RoleKeycloakDto> keycloakAvailableRoles = List.of(keycloakRole1, keycloakRole2);
- final List<RoleKeycloakDto> keycloakAssignedRoles = List.empty();
+ final List<RoleKeycloakDto> keycloakAssignedRoles = Collections.emptyList();
final List<RoleKeycloakDto> keycloakRolesToRemove = List.of(keycloakRole1, keycloakRole2);
WireMock.stubFor(
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withBody(objectMapper.writeValueAsString(keycloakAssignedRoles))));
- final List<RoleApiDto> rolesToAssign = List.empty();
+ final List<RoleApiDto> rolesToAssign = Collections.emptyList();
final RoleListResponseApiDto response =
requestSpecification()
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.http.Header;
-import io.vavr.collection.List;
+import java.util.List;
import org.junit.jupiter.api.Test;
import org.onap.portal.bff.BaseIntegrationTest;
import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import io.vavr.collection.HashMap;
-import io.vavr.collection.List;
-import io.vavr.control.Option;
-import java.util.Comparator;
-import lombok.Data;
-import lombok.NonNull;
-import org.junit.jupiter.api.Test;
-
-class SortingChainResolverTest {
-
- @Test
- void emptySortIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse(""));
- assertThat(comparatorOption.isEmpty()).isTrue();
- }
-
- @Test
- void sortWithUnknownPropertyIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse("unknown"));
- assertThat(comparatorOption.isEmpty()).isTrue();
- }
-
- @Test
- void sortWithSingleAscendingPropertyIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse("age"));
- assertThat(comparatorOption.isDefined()).isTrue();
-
- final List<DummyPerson> list =
- List.of(new DummyPerson("Albert", 10), new DummyPerson("Bernard", 7));
- final List<DummyPerson> expectedList =
- List.of(new DummyPerson("Bernard", 7), new DummyPerson("Albert", 10));
- assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
- }
-
- @Test
- void sortWithSingleDescendingPropertyIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse("-age"));
- assertThat(comparatorOption.isDefined()).isTrue();
-
- final List<DummyPerson> list =
- List.of(new DummyPerson("Charles", 23), new DummyPerson("Dominick", 31));
- final List<DummyPerson> expectedList =
- List.of(new DummyPerson("Dominick", 31), new DummyPerson("Charles", 23));
- assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
- }
-
- @Test
- void sortWithMultiplePropertiesIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(
- HashMap.of("age", Comparator.comparing(DummyPerson::getAge))
- .put("name", Comparator.comparing(DummyPerson::getName)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse("age,name"));
- assertThat(comparatorOption.isDefined()).isTrue();
-
- final List<DummyPerson> list =
- List.of(
- new DummyPerson("Harold", 27),
- new DummyPerson("Diego", 70),
- new DummyPerson("David", 27));
- final List<DummyPerson> expectedList =
- List.of(
- new DummyPerson("David", 27),
- new DummyPerson("Harold", 27),
- new DummyPerson("Diego", 70));
- assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
- }
-
- @Test
- void sortWithMultiplePropertiesInDifferentOrderIsCorrectlyResolved() {
- final SortingChainResolver<DummyPerson> resolver =
- new SortingChainResolver<>(
- HashMap.of("age", Comparator.comparing(DummyPerson::getAge))
- .put("name", Comparator.comparing(DummyPerson::getName)));
-
- final Option<Comparator<DummyPerson>> comparatorOption =
- resolver.resolve(SortingParser.parse("name,age"));
- assertThat(comparatorOption.isDefined()).isTrue();
-
- final List<DummyPerson> list =
- List.of(
- new DummyPerson("Harold", 27),
- new DummyPerson("Diego", 70),
- new DummyPerson("David", 27));
- final List<DummyPerson> expectedList =
- List.of(
- new DummyPerson("David", 27),
- new DummyPerson("Diego", 70),
- new DummyPerson("Harold", 27));
- assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
- }
-
- @Data
- private static class DummyPerson {
- @NonNull private final String name;
- private final int age;
- }
-}
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.junit.jupiter.api.Test;
-
-class SortingParserTest {
-
- @Test
- void emptySortIsCorrectlyParsed() {
- assertThat(SortingParser.parse("")).isEmpty();
- }
-
- @Test
- void sortIsCorrectlyParsed() {
- assertThat(SortingParser.parse("age,-name"))
- .containsExactly(
- new SortingParser.SortingParam("age", false),
- new SortingParser.SortingParam("name", true));
- }
-
- @Test
- void sortWithInvalidPartsIsCorrectlyParsed() {
- assertThat(SortingParser.parse("age,,name,-"))
- .containsExactly(
- new SortingParser.SortingParam("age", false),
- new SortingParser.SortingParam("name", false));
- }
-}
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import io.vavr.collection.List;
-import org.junit.jupiter.api.Test;
-
-class VersionComparatorTest {
-
- @Test
- void versionsAreCorrectlySorted() {
- final VersionComparator comparator = new VersionComparator();
-
- final List<String> expectedVersions =
- List.of("1.0", "1.0.1", "1.1", "1.1.1", "1.2", "1.2.1", "1.10", "2.0");
- final List<String> versions = expectedVersions.shuffle().shuffle();
-
- assertThat(versions.sorted(comparator)).containsExactlyElementsOf(expectedVersions);
- }
-}
}
}
+tasks.withType(JavaCompile) {
+ dependsOn 'spotlessApply'
+}
+
spotbugs {
ignoreFailures = false
effort = "max"
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
-import io.vavr.jackson.datatype.VavrModule;
import java.time.Clock;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder
- .modules(new VavrModule(), new ProblemModule(), new JavaTimeModule())
+ .modules(new ProblemModule(), new JavaTimeModule())
.build()
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
package org.onap.portal.bff.config;
-import io.vavr.collection.List;
+import java.util.List;
import org.onap.portal.bff.mappers.ActionsMapper;
import org.onap.portal.bff.mappers.PreferencesMapper;
import org.onap.portal.bff.mappers.RolesMapper;
package org.onap.portal.bff.config;
-import io.vavr.control.Option;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
@NotNull private final Map<String, List<String>> accessControl;
public Mono<List<String>> getRoles(String method) {
- return Option.of(accessControl.get(method))
- .map(Mono::just)
- .getOrElse(
- Mono.error(
- Problem.valueOf(
- Status.FORBIDDEN, "The user does not have the necessary access rights")));
+ return Mono.just(accessControl)
+ .map(control -> control.get(method))
+ .onErrorResume(
+ e ->
+ Mono.error(
+ Problem.valueOf(
+ Status.FORBIDDEN, "The user does not have the necessary access rights")));
}
}
package org.onap.portal.bff.controller;
-import io.vavr.collection.List;
import org.onap.portal.bff.config.PortalBffConfig;
import org.onap.portal.bff.openapi.server.api.UsersApi;
import org.onap.portal.bff.openapi.server.model.CreateUserRequestApiDto;
String userId, String xRequestId, Flux<RoleApiDto> rolesFlux, ServerWebExchange exchange) {
return checkRoleAccess(UPDATE_ROLES, exchange)
.then(rolesFlux.collectList())
- .map(List::ofAll)
.flatMap(roles -> keycloakService.updateAssignedRoles(userId, roles, xRequestId))
.map(ResponseEntity::ok);
}
import io.vavr.API;
import io.vavr.Tuple;
import io.vavr.Tuple2;
-import io.vavr.collection.List;
-import io.vavr.control.Option;
import java.net.URI;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
log.debug("Create user in keycloak. request=`{}`", request);
final List<RoleApiDto> rolesToBeAssigned =
- Option.of(request.getRoles()).fold(List::empty, List::ofAll);
+ request.getRoles().isEmpty() ? Collections.emptyList() : request.getRoles();
return listRoles(xRequestId)
.collectList()
.flatMap(
realmRoles -> {
final List<RoleApiDto> absentRoles =
- rolesToBeAssigned.filter(role -> !realmRoles.contains(role));
+ rolesToBeAssigned.stream().filter(role -> !realmRoles.contains(role)).toList();
if (!absentRoles.isEmpty()) {
return Mono.error(
DownstreamApiProblemException.builder()
.detail(
String.format(
"Roles not found in the realm: %s",
- absentRoles.map(RoleApiDto::getName).asJava()))
+ absentRoles.stream().map(RoleApiDto::getName).toList()))
.downstreamSystem(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString())
.title(HttpStatus.NOT_FOUND.toString())
.build());
}
return Mono.just(rolesToBeAssigned);
})
- .flatMap(roles -> createUserWithRoles(request, xRequestId, List.ofAll(roles)));
+ .flatMap(roles -> createUserWithRoles(request, xRequestId, roles));
}
private Mono<UserResponseApiDto> createUserWithRoles(
CreateUserRequestApiDto request, String xRequestId, List<RoleApiDto> roles) {
return keycloakApi
.createUserWithHttpInfo(
- usersMapper.convert(
- request, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD).asJava()))
+ usersMapper.convert(request, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD)))
+ .map(responseEntit -> responseEntit.getHeaders().getLocation())
+ .map(URI::toString)
+ .map(location -> location.substring(location.lastIndexOf("/") + 1))
+ .flatMap(userId -> !roles.isEmpty() ? assignRoles(userId, roles) : Mono.just(userId))
.flatMap(
- responseEntity ->
- Option.of(responseEntity.getHeaders().getLocation())
- .map(URI::toString)
- .map(location -> location.substring(location.lastIndexOf("/") + 1))
- .fold(
- () -> Mono.error(DownstreamApiProblemException.builder().build()),
- Mono::just))
- .flatMap(
- userId -> {
- if (!roles.isEmpty()) {
- return assignRoles(userId, roles);
- }
- return Mono.just(userId);
- })
- .flatMap(
- userId ->
- sendActionEmail(
- userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList()))
+ userId -> sendActionEmail(userId, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD)))
.onErrorResume(
DownstreamApiProblemException.class,
ex -> {
listUsersByRole(role.getName(), xRequestId)
.map(user -> Tuple.of(user.getId(), role.getName())))
.collectList()
- .map(List::ofAll)
+ .map(io.vavr.collection.List::ofAll)
.map(list -> list.groupBy(t -> t._1).map((k, v) -> Tuple.of(k, v.map(Tuple2::_2)))))
.map(
tuple -> {
final UserListResponseApiDto result = new UserListResponseApiDto();
result.setTotalCount(tuple.getT1());
result.setItems(
- List.ofAll(tuple.getT2())
+ io.vavr.collection.List.ofAll(tuple.getT2())
.map(
user ->
usersMapper.convert(
user,
tuple.getT3().getOrElse(user.getId(), API.List()).toJavaList()))
.toJavaList());
+ // result.setItems(
+ // tuple.getT2().stream()
+ // .map(user -> usersMapper.convert(user,tuple.getT3()))
+ // .toList());
return result;
})
log.debug(
"Assign roles to user in keycloak. userId=`{}`, roleIds=`{}`",
userId,
- roles.map(RoleApiDto::getId).mkString(", "));
+ roles.stream().map(RoleApiDto::getId).collect(Collectors.joining(", ")));
return keycloakApi
- .addRealmRoleMappingsToUser(userId, roles.map(rolesMapper::convert).toJavaList())
+ .addRealmRoleMappingsToUser(userId, roles.stream().map(rolesMapper::convert).toList())
.thenReturn(userId);
}
log.debug(
"Update assigned roles for user in keycloak. userId=`{}`, roleIds=`{}`",
userId,
- roles.map(RoleApiDto::getId).mkString(", "));
+ roles.stream().map(RoleApiDto::getId).collect(Collectors.joining(", ")));
return getAssignedRoles(userId, xRequestId)
- .map(response -> List.ofAll(response.getItems()))
+ .map(response -> response.getItems())
.flatMap(
assignedRoles -> {
if (assignedRoles.isEmpty()) {
log.debug(
"Unassign roles from user in keycloak. userId=`{}`, roleIds=`{}`",
userId,
- roles.map(RoleApiDto::getId).mkString(", "));
+ roles.stream().map(RoleApiDto::getId).collect(Collectors.joining(", ")));
return keycloakApi.deleteRealmRoleMappingsByUserId(
- userId, roles.map(rolesMapper::convert).toJavaList());
+ userId, roles.stream().map(rolesMapper::convert).toList());
}
public Mono<String> sendActionEmail(
public Flux<RoleApiDto> listRoles(String xRequestId) {
return keycloakApi
.getRoles(null, null, null, null)
- .log()
.map(role -> conversionService.convert(role, RoleApiDto.class))
.onErrorResume(
DownstreamApiProblemException.class,
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import io.vavr.collection.Map;
-import io.vavr.collection.Seq;
-import io.vavr.control.Option;
-import java.util.Comparator;
-
-public class SortingChainResolver<T> {
- final Map<String, Comparator<T>> comparators;
-
- public SortingChainResolver(Map<String, Comparator<T>> comparators) {
- this.comparators = comparators;
- }
-
- public Option<Comparator<T>> resolve(Seq<SortingParser.SortingParam> sortingParams) {
- final Seq<Comparator<T>> resolvedComparators =
- sortingParams.flatMap(
- sortingParam ->
- comparators
- .get(sortingParam.getName())
- .map(
- comparator -> {
- if (sortingParam.isDescending()) {
- return comparator.reversed();
- }
- return comparator;
- }));
-
- if (resolvedComparators.isEmpty()) {
- return Option.none();
- }
- return Option.some(resolvedComparators.reduceLeft(Comparator::thenComparing));
- }
-}
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import io.vavr.collection.List;
-import io.vavr.collection.Seq;
-import lombok.Builder;
-import lombok.NonNull;
-import lombok.Value;
-
-public class SortingParser {
- private static final String DESC_PREFIX = "-";
- private static final String SEPARATOR = ",";
-
- private SortingParser() {}
-
- public static Seq<SortingParam> parse(String sort) {
- return List.of(sort.split(SEPARATOR))
- .filter(name -> !name.isEmpty() && !name.equals(DESC_PREFIX))
- .map(
- name -> {
- if (name.startsWith(DESC_PREFIX)) {
- return SortingParam.builder()
- .name(name.substring(DESC_PREFIX.length()))
- .isDescending(true)
- .build();
- }
- return SortingParam.builder().name(name).isDescending(false).build();
- });
- }
-
- @Builder
- @Value
- public static class SortingParam {
- @NonNull String name;
- boolean isDescending;
- }
-}
+++ /dev/null
-/*
- *
- * Copyright (c) 2022. Deutsche Telekom AG
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- *
- */
-
-package org.onap.portal.bff.utils;
-
-import java.util.Comparator;
-import java.util.regex.Pattern;
-
-public class VersionComparator implements Comparator<String> {
- private static final Pattern SEPARATOR_PATTERN = Pattern.compile("\\.");
-
- @Override
- public int compare(String version1, String version2) {
- final String[] parsedVersion1 = SEPARATOR_PATTERN.split(version1);
- final String[] parsedVersion2 = SEPARATOR_PATTERN.split(version2);
- final int maxLength = Math.max(parsedVersion1.length, parsedVersion2.length);
-
- for (int i = 0; i < maxLength; i++) {
- final Integer v1 = i < parsedVersion1.length ? Integer.parseInt(parsedVersion1[i]) : 0;
- final Integer v2 = i < parsedVersion2.length ? Integer.parseInt(parsedVersion2[i]) : 0;
- final int compare = v1.compareTo(v2);
-
- if (compare != 0) {
- return compare;
- }
- }
-
- return 0;
- }
-}