bugfix: fixes HTTP POST on credentials, including person+subject (#184)
Co-authored-by: Michael Hoennig <michael@hoennig.de> Reviewed-on: https://dev.hostsharing.net/hostsharing/hs.hsadmin.ng/pulls/184 Reviewed-by: Marc Sandlus <marc.sandlus@hostsharing.net>
This commit is contained in:
@@ -50,6 +50,7 @@ public class ArchitectureTest {
|
||||
"..test.dom",
|
||||
"..context",
|
||||
"..credentials",
|
||||
"..credentials.scenarios",
|
||||
"..hash",
|
||||
"..lambda",
|
||||
"..journal",
|
||||
|
||||
@@ -4,9 +4,13 @@ import net.hostsharing.hsadminng.config.DisableSecurityConfig;
|
||||
import net.hostsharing.hsadminng.config.JsonObjectMapperConfiguration;
|
||||
import net.hostsharing.hsadminng.config.MessageTranslator;
|
||||
import net.hostsharing.hsadminng.context.Context;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacEntity;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacRepository;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRealRepository;
|
||||
import net.hostsharing.hsadminng.mapper.StrictMapper;
|
||||
import net.hostsharing.hsadminng.persistence.EntityManagerWrapper;
|
||||
import net.hostsharing.hsadminng.rbac.subject.RbacSubjectEntity;
|
||||
import net.hostsharing.hsadminng.rbac.subject.RbacSubjectRepository;
|
||||
import org.hamcrest.CustomMatcher;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -37,6 +41,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
@ActiveProfiles("test")
|
||||
class HsCredentialsControllerRestTest {
|
||||
|
||||
private static final UUID PERSON_UUID = UUID.randomUUID();
|
||||
|
||||
@Autowired
|
||||
MockMvc mockMvc;
|
||||
|
||||
@@ -54,7 +60,13 @@ class HsCredentialsControllerRestTest {
|
||||
EntityManagerFactory emf;
|
||||
|
||||
@MockitoBean
|
||||
HsOfficePersonRbacRepository personRbacRepo;
|
||||
RbacSubjectRepository subjectRepo;
|
||||
|
||||
@MockitoBean
|
||||
HsOfficePersonRealRepository realPersonRepo;
|
||||
|
||||
@MockitoBean
|
||||
HsOfficePersonRbacRepository rbacPersonRepo;
|
||||
|
||||
@MockitoBean
|
||||
HsCredentialsContextRbacRepository loginContextRbacRepo;
|
||||
@@ -62,6 +74,9 @@ class HsCredentialsControllerRestTest {
|
||||
@MockitoBean
|
||||
HsCredentialsRepository credentialsRepo;
|
||||
|
||||
@MockitoBean
|
||||
CredentialContextResourceToEntityMapper contextMapper;
|
||||
|
||||
@Test
|
||||
void patchCredentialsUsed() throws Exception {
|
||||
|
||||
@@ -70,6 +85,8 @@ class HsCredentialsControllerRestTest {
|
||||
when(credentialsRepo.findByUuid(givenCredentialsUuid)).thenReturn(Optional.of(
|
||||
HsCredentialsEntity.builder()
|
||||
.uuid(givenCredentialsUuid)
|
||||
.person(HsOfficePersonRbacEntity.builder().uuid(PERSON_UUID).build())
|
||||
.subject(RbacSubjectEntity.builder().name("some-nickname").build())
|
||||
.lastUsed(null)
|
||||
.onboardingToken("fake-onboarding-token")
|
||||
.build()
|
||||
|
||||
@@ -117,7 +117,8 @@ class HsCredentialsEntityPatcherUnitTest extends PatchUnitTestBase<
|
||||
|
||||
@Override
|
||||
protected HsCredentialsEntityPatcher createPatcher(final HsCredentialsEntity entity) {
|
||||
return new HsCredentialsEntityPatcher(em, mock(MessageTranslator.class), entity);
|
||||
final var contextMapper = new CredentialContextResourceToEntityMapper(em, mock(MessageTranslator.class));
|
||||
return new HsCredentialsEntityPatcher(contextMapper, entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package net.hostsharing.hsadminng.credentials;
|
||||
|
||||
import net.hostsharing.hsadminng.context.Context;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRealEntity;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacEntity;
|
||||
import net.hostsharing.hsadminng.rbac.context.ContextBasedTest;
|
||||
import net.hostsharing.hsadminng.rbac.subject.RbacSubjectEntity;
|
||||
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
|
||||
@@ -51,8 +51,8 @@ class HsCredentialsRepositoryIntegrationTest extends ContextBasedTest {
|
||||
private RbacSubjectEntity alexSubject;
|
||||
private RbacSubjectEntity drewSubject;
|
||||
private RbacSubjectEntity testUserSubject;
|
||||
private HsOfficePersonRealEntity drewPerson;
|
||||
private HsOfficePersonRealEntity testUserPerson;
|
||||
private HsOfficePersonRbacEntity drewPerson;
|
||||
private HsOfficePersonRbacEntity testUserPerson;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -218,13 +218,13 @@ class HsCredentialsRepositoryIntegrationTest extends ContextBasedTest {
|
||||
}
|
||||
}
|
||||
|
||||
private HsOfficePersonRealEntity fetchPersonByGivenName(final String givenName) {
|
||||
final String jpql = "SELECT p FROM HsOfficePersonRealEntity p WHERE p.givenName = :givenName";
|
||||
final Query query = em.createQuery(jpql, HsOfficePersonRealEntity.class);
|
||||
private HsOfficePersonRbacEntity fetchPersonByGivenName(final String givenName) {
|
||||
final String jpql = "SELECT p FROM HsOfficePersonRbacEntity p WHERE p.givenName = :givenName";
|
||||
final Query query = em.createQuery(jpql, HsOfficePersonRbacEntity.class);
|
||||
query.setParameter("givenName", givenName);
|
||||
try {
|
||||
context(SUPERUSER_ALEX_SUBJECT_NAME);
|
||||
return notNull((HsOfficePersonRealEntity) query.getSingleResult());
|
||||
return notNull((HsOfficePersonRbacEntity) query.getSingleResult());
|
||||
} catch (final NoResultException e) {
|
||||
throw new AssertionError(
|
||||
"Failed to find person with name '" + givenName + "'. Ensure test data is present.", e);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package net.hostsharing.hsadminng.credentials.scenarios;
|
||||
|
||||
import io.restassured.http.ContentType;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.ScenarioTest;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.UseCase;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import static io.restassured.http.ContentType.JSON;
|
||||
import static org.springframework.http.HttpStatus.OK;
|
||||
|
||||
public class CreateCredentials extends UseCase<CreateCredentials> {
|
||||
|
||||
public CreateCredentials(final ScenarioTest testSuite) {
|
||||
super(testSuite);
|
||||
|
||||
introduction("A set of credentials contains the login data for an RBAC subject.");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected HttpResponse run() {
|
||||
|
||||
obtain("Person: %{personGivenName} %{personFamilyName}", () ->
|
||||
httpGet("/api/hs/office/persons?name=%{personFamilyName}")
|
||||
.expecting(OK).expecting(JSON),
|
||||
response -> response.expectArrayElements(1).getFromBody("[0].uuid"),
|
||||
"In real situations we have more precise measures to find the related person."
|
||||
);
|
||||
|
||||
|
||||
obtain("CredentialsContexts", () ->
|
||||
httpGet("/api/hs/credentials/contexts").expecting(OK).expecting(JSON)
|
||||
);
|
||||
|
||||
return obtain("newCredentials", () ->
|
||||
httpPost("/api/hs/credentials/credentials", usingJsonBody("""
|
||||
{
|
||||
"person.uuid": ${Person: %{personGivenName} %{personFamilyName}},
|
||||
"nickname": ${nickname},
|
||||
"active": %{active},
|
||||
"emailAddress": ${emailAddress},
|
||||
"telephonePassword": ${telephonePassword},
|
||||
"smsNumber": ${smsNumber},
|
||||
"globalUid": %{globalUid},
|
||||
"globalGid": %{globalGid},
|
||||
"contexts": @{contexts}
|
||||
}
|
||||
"""))
|
||||
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void verify(final UseCase<CreateCredentials>.HttpResponse response) {
|
||||
verify(
|
||||
"Verify the New Credentials",
|
||||
() -> httpGet("/api/hs/credentials/credentials/%{newCredentials}")
|
||||
.expecting(OK).expecting(JSON),
|
||||
path("uuid").contains("%{newCredentials}"),
|
||||
path("nickname").contains("%{nickname}"),
|
||||
path("person.uuid").contains("%{Person: %{personGivenName} %{personFamilyName}}")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package net.hostsharing.hsadminng.credentials.scenarios;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import net.hostsharing.hsadminng.HsadminNgApplication;
|
||||
import net.hostsharing.hsadminng.config.DisableSecurityConfig;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.Produces;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.ScenarioTest;
|
||||
import net.hostsharing.hsadminng.mapper.Array;
|
||||
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
|
||||
import net.hostsharing.hsadminng.test.IgnoreOnFailureExtension;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.ClassOrderer;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestClassOrder;
|
||||
import org.junit.jupiter.api.TestInfo;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Tag("scenarioTest")
|
||||
@SpringBootTest(
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
classes = { HsadminNgApplication.class, DisableSecurityConfig.class, JpaAttempt.class },
|
||||
properties = {
|
||||
"spring.datasource.url=${HSADMINNG_POSTGRES_JDBC_URL:jdbc:tc:postgresql:15.5-bookworm:///scenariosTC}",
|
||||
"spring.datasource.username=${HSADMINNG_POSTGRES_ADMIN_USERNAME:ADMIN}",
|
||||
"spring.datasource.password=${HSADMINNG_POSTGRES_ADMIN_PASSWORD:password}",
|
||||
"hsadminng.superuser=${HSADMINNG_SUPERUSER:superuser-alex@hostsharing.net}"
|
||||
}
|
||||
)
|
||||
@ActiveProfiles("test")
|
||||
@TestClassOrder(ClassOrderer.OrderAnnotation.class)
|
||||
@ExtendWith(IgnoreOnFailureExtension.class)
|
||||
class CredentialsScenarioTests extends ScenarioTest {
|
||||
|
||||
@SneakyThrows
|
||||
@BeforeEach
|
||||
protected void beforeScenario(final TestInfo testInfo) {
|
||||
super.beforeScenario(testInfo);
|
||||
}
|
||||
@Nested
|
||||
@Order(10)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CredentialScenarios {
|
||||
|
||||
@Test
|
||||
@Order(1010)
|
||||
@Produces(explicitly = "Credentials@hsadmin: firby-susan", implicitly = { "Person: Susan Firby" })
|
||||
void shouldCreateInitialCredentialsForExistingNaturalPerson() {
|
||||
new CreateCredentials(scenarioTest)
|
||||
// to find a specific existing person
|
||||
.given("personFamilyName", "Firby")
|
||||
.given("personGivenName", "Susan")
|
||||
// a login name, to be stored in the new RBAC subject
|
||||
.given("nickname", "firby-susan")
|
||||
// initial credentials
|
||||
.given("active", true)
|
||||
.given("emailAddress", "susan.firby@example.com")
|
||||
.given("telephonePassword", "securePass123")
|
||||
.given("smsNumber", "+49123456789")
|
||||
.given("globalUid", 21011)
|
||||
.given("globalGid", 21011)
|
||||
.given("contexts", Array.of(
|
||||
Map.ofEntries(
|
||||
// a hardcoded context from test-data
|
||||
// TODO.impl: the uuid should be determined within CreateCredentials just by (HSDAMIN,prod)
|
||||
Map.entry("uuid", "11111111-1111-1111-1111-111111111111"),
|
||||
Map.entry("type", "HSADMIN"),
|
||||
Map.entry("qualifier", "prod")
|
||||
)
|
||||
))
|
||||
.doRun()
|
||||
.keep();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package net.hostsharing.hsadminng.hs.office.scenarios;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import net.hostsharing.hsadminng.HsadminNgApplication;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacEntity;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacRepository;
|
||||
import net.hostsharing.hsadminng.hs.office.scenarios.contact.AddPhoneNumberToContactData;
|
||||
import net.hostsharing.hsadminng.hs.office.scenarios.contact.AmendContactData;
|
||||
import net.hostsharing.hsadminng.hs.office.scenarios.contact.RemovePhoneNumberFromContactData;
|
||||
@@ -39,9 +42,11 @@ import net.hostsharing.hsadminng.hs.office.scenarios.subscription.UnsubscribeFro
|
||||
import net.hostsharing.hsadminng.hs.scenarios.Produces;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.Requires;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.ScenarioTest;
|
||||
import net.hostsharing.hsadminng.lambda.Reducer;
|
||||
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
|
||||
import net.hostsharing.hsadminng.config.DisableSecurityConfig;
|
||||
import net.hostsharing.hsadminng.test.IgnoreOnFailureExtension;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.ClassOrderer;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
@@ -50,8 +55,10 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestClassOrder;
|
||||
import org.junit.jupiter.api.TestInfo;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
@@ -71,6 +78,30 @@ import org.springframework.test.context.ActiveProfiles;
|
||||
@ExtendWith(IgnoreOnFailureExtension.class)
|
||||
class HsOfficeScenarioTests extends ScenarioTest {
|
||||
|
||||
@Autowired
|
||||
HsOfficePersonRbacRepository personRepo;
|
||||
|
||||
@SneakyThrows
|
||||
@BeforeEach
|
||||
protected void beforeScenario(final TestInfo testInfo) {
|
||||
createHostsharingPerson();
|
||||
super.beforeScenario(testInfo);
|
||||
}
|
||||
|
||||
private void createHostsharingPerson() {
|
||||
jpaAttempt.transacted(() ->
|
||||
{
|
||||
context.define("superuser-alex@hostsharing.net");
|
||||
putAlias(
|
||||
"Person: Hostsharing eG",
|
||||
personRepo.findPersonByOptionalNameLike("Hostsharing eG").stream()
|
||||
.map(HsOfficePersonRbacEntity::getUuid)
|
||||
.reduce(Reducer::toSingleElement).orElseThrow()
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@Order(10)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package net.hostsharing.hsadminng.hs.scenarios;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacEntity;
|
||||
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRbacRepository;
|
||||
import net.hostsharing.hsadminng.lambda.Reducer;
|
||||
import net.hostsharing.hsadminng.rbac.context.ContextBasedTest;
|
||||
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
|
||||
import net.hostsharing.hsadminng.hs.scenarios.TemplateResolver.Resolver;
|
||||
@@ -58,15 +55,11 @@ public abstract class ScenarioTest extends ContextBasedTest {
|
||||
Integer port;
|
||||
|
||||
@Autowired
|
||||
HsOfficePersonRbacRepository personRepo;
|
||||
|
||||
@Autowired
|
||||
JpaAttempt jpaAttempt;
|
||||
protected JpaAttempt jpaAttempt;
|
||||
|
||||
@SneakyThrows
|
||||
@BeforeEach
|
||||
void beforeScenario(final TestInfo testInfo) {
|
||||
createHostsharingPerson();
|
||||
protected void beforeScenario(final TestInfo testInfo) {
|
||||
try {
|
||||
testInfo.getTestMethod().ifPresent(currentTestMethod -> {
|
||||
callRequiredProducers(currentTestMethod);
|
||||
@@ -86,20 +79,6 @@ public abstract class ScenarioTest extends ContextBasedTest {
|
||||
testReport.close();
|
||||
}
|
||||
|
||||
private void createHostsharingPerson() {
|
||||
jpaAttempt.transacted(() ->
|
||||
{
|
||||
context.define("superuser-alex@hostsharing.net");
|
||||
putAlias(
|
||||
"Person: Hostsharing eG",
|
||||
personRepo.findPersonByOptionalNameLike("Hostsharing eG").stream()
|
||||
.map(HsOfficePersonRbacEntity::getUuid)
|
||||
.reduce(Reducer::toSingleElement).orElseThrow()
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private void callRequiredProducers(final Method currentTestMethod) {
|
||||
final var testMethodRequires = Optional.of(currentTestMethod)
|
||||
@@ -200,15 +179,15 @@ public abstract class ScenarioTest extends ContextBasedTest {
|
||||
return alias;
|
||||
}
|
||||
|
||||
static void putAlias(final String name, final UUID value) {
|
||||
protected static void putAlias(final String name, final UUID value) {
|
||||
aliases.put(name, value);
|
||||
}
|
||||
|
||||
static void putProperty(final String name, final Object value) {
|
||||
protected static void putProperty(final String name, final Object value) {
|
||||
properties.put(name, (value instanceof String string) ? resolveTyped(string) : value);
|
||||
}
|
||||
|
||||
static void removeProperty(final String propName) {
|
||||
protected static void removeProperty(final String propName) {
|
||||
properties.remove(propName);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,10 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -14,6 +16,8 @@ import static net.hostsharing.hsadminng.hs.scenarios.TemplateResolver.Resolver.D
|
||||
|
||||
public class TemplateResolver {
|
||||
|
||||
public static final String JSON_NULL_VALUE_TO_KEEP = "NULL";
|
||||
|
||||
public enum Resolver {
|
||||
DROP_COMMENTS, // deletes comments ('#{whatever}' -> '')
|
||||
KEEP_COMMENTS // keep comments ('#{whatever}' -> 'whatever')
|
||||
@@ -44,6 +48,12 @@ public class TemplateResolver {
|
||||
return value != null ? URLEncoder.encode(value.toString(), StandardCharsets.UTF_8) : "";
|
||||
}
|
||||
},
|
||||
JSON_ARRAY('@'){
|
||||
@Override
|
||||
String convert(final Object value, final Resolver resolver) {
|
||||
return jsonArray(value);
|
||||
}
|
||||
},
|
||||
COMMENT('#'){
|
||||
@Override
|
||||
String convert(final Object value, final Resolver resolver) {
|
||||
@@ -102,13 +112,14 @@ public class TemplateResolver {
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
|
||||
private static boolean keepLine(final String line) {
|
||||
final var trimmed = line.trim();
|
||||
return !trimmed.endsWith("null,") && !trimmed.endsWith("null");
|
||||
}
|
||||
|
||||
private static String keptNullValues(final String line) {
|
||||
return line.replace(": NULL", ": null");
|
||||
return line.replace(": "+ JSON_NULL_VALUE_TO_KEEP, ": null");
|
||||
}
|
||||
|
||||
private String copy() {
|
||||
@@ -163,12 +174,10 @@ public class TemplateResolver {
|
||||
// => last alternative element in expression was null and not optional
|
||||
throw new IllegalStateException("Missing required value in property-chain: " + nameExpression);
|
||||
});
|
||||
} else if (properties.containsKey(nameExpression)) {
|
||||
return properties.get(nameExpression);
|
||||
} else {
|
||||
final var val = properties.get(nameExpression);
|
||||
if (val == null) {
|
||||
throw new IllegalStateException("Missing required property: " + nameExpression);
|
||||
}
|
||||
return val;
|
||||
throw new IllegalStateException("Missing required property: " + nameExpression);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,19 +221,40 @@ public class TemplateResolver {
|
||||
|
||||
private static String jsonQuoted(final Object value) {
|
||||
return switch (value) {
|
||||
case null -> null;
|
||||
case null -> "null";
|
||||
case Boolean bool -> bool.toString();
|
||||
case Number number -> number.toString();
|
||||
case String string -> "\"" + string.replace("\n", "\\n") + "\"";
|
||||
default -> "\"" + value + "\"";
|
||||
case UUID uuid -> "\"" + uuid + "\"";
|
||||
default -> jsonObject(value);
|
||||
};
|
||||
}
|
||||
|
||||
private static String jsonObject(final Object value) {
|
||||
return switch (value) {
|
||||
case null -> null;
|
||||
case null -> "null";
|
||||
case Map<?, ?> map -> "{" + map.entrySet().stream()
|
||||
.map(entry -> "\"" + entry.getKey() + "\": " + jsonQuoted(entry.getValue()))
|
||||
.collect(Collectors.joining(", ")) + "}";
|
||||
case String string -> "{" + string.replace("\n", " ") + "}";
|
||||
default -> throw new IllegalArgumentException("can not format " + value.getClass() + " (" + value + ") as JSON object");
|
||||
};
|
||||
}
|
||||
|
||||
private static String jsonArray(final Object value) {
|
||||
return switch (value) {
|
||||
case null -> "null";
|
||||
case Object[] array -> "[" + Arrays.stream(array)
|
||||
.filter(Objects::nonNull)
|
||||
.map(TemplateResolver::jsonQuoted)
|
||||
.collect(Collectors.joining(", ")) + "]";
|
||||
case Collection<?> collection -> "[" + collection.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(TemplateResolver::jsonQuoted)
|
||||
.collect(Collectors.joining(", ")) + "]";
|
||||
case String string -> "[" + string.replace("\n", " ") + "]";
|
||||
default -> throw new IllegalArgumentException("Cannot format " + value.getClass() + " (" + value + ") as JSON array");
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package net.hostsharing.hsadminng.hs.scenarios;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static net.hostsharing.hsadminng.hs.scenarios.TemplateResolver.Resolver.DROP_COMMENTS;
|
||||
@@ -12,6 +15,12 @@ class TemplateResolverUnitTest {
|
||||
@Test
|
||||
void resolveTemplate() {
|
||||
final var resolved = new TemplateResolver("""
|
||||
JSON arrays:
|
||||
- arrayWithMixedValues: @{arrayWithMixedValues}
|
||||
- arrayWithObjects: @{arrayWithObjects}
|
||||
- emptyArray: @{emptyArray}
|
||||
- nullArray: @{nullArray}
|
||||
|
||||
with optional JSON quotes:
|
||||
|
||||
${boolean},
|
||||
@@ -19,7 +28,7 @@ class TemplateResolverUnitTest {
|
||||
${simple placeholder},
|
||||
${nested %{name}},
|
||||
${with-special-chars}
|
||||
|
||||
|
||||
and without quotes:
|
||||
|
||||
%{boolean},
|
||||
@@ -36,16 +45,34 @@ class TemplateResolverUnitTest {
|
||||
&{nested %{name}},
|
||||
&{with-special-chars}
|
||||
""",
|
||||
Map.ofEntries(
|
||||
Map.entry("name", "placeholder"),
|
||||
Map.entry("boolean", true),
|
||||
Map.entry("numeric", 42),
|
||||
Map.entry("simple placeholder", "einfach"),
|
||||
Map.entry("nested placeholder", "verschachtelt"),
|
||||
Map.entry("with-special-chars", "3&3 AG")
|
||||
orderedMapOfElementsWithNullValues(
|
||||
entry("arrayWithMixedValues", new Object[] { "some string", true, 1234, "another string" }),
|
||||
entry("arrayWithObjects", new Object[] {
|
||||
orderedMapOfElementsWithNullValues(
|
||||
Map.entry("name", "some name"),
|
||||
Map.entry("number", 12345)
|
||||
),
|
||||
orderedMapOfElementsWithNullValues(
|
||||
Map.entry("name", "another name"),
|
||||
Map.entry("number", 98765)
|
||||
)
|
||||
}),
|
||||
entry("emptyArray", new Object[] {}),
|
||||
entry("nullArray", null),
|
||||
entry("name", "placeholder"),
|
||||
entry("boolean", true),
|
||||
entry("numeric", 42),
|
||||
entry("simple placeholder", "einfach"),
|
||||
entry("nested placeholder", "verschachtelt"),
|
||||
entry("with-special-chars", "3&3 AG")
|
||||
)).resolve(DROP_COMMENTS);
|
||||
|
||||
assertThat(resolved).isEqualTo("""
|
||||
JSON arrays:
|
||||
- arrayWithMixedValues: ["some string", true, 1234, "another string"]
|
||||
- arrayWithObjects: [{"name": "some name", "number": 12345}, {"name": "another name", "number": 98765}]
|
||||
- emptyArray: []
|
||||
|
||||
with optional JSON quotes:
|
||||
|
||||
true,
|
||||
@@ -71,4 +98,20 @@ class TemplateResolverUnitTest {
|
||||
3%263+AG
|
||||
""".trim());
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
private Map<String, Object> orderedMapOfElementsWithNullValues(
|
||||
final Map.Entry<String, Object>... entries) {
|
||||
final var map = new LinkedHashMap<String, Object>();
|
||||
if (entries != null) {
|
||||
Arrays.stream(entries)
|
||||
.forEach(entry -> map.put(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static AbstractMap.SimpleEntry<String, Object> entry(String key, Object value) {
|
||||
return new AbstractMap.SimpleEntry<>(key, value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ class RbacSubjectControllerAcceptanceTest {
|
||||
RbacSubjectEntity givenANewUser() {
|
||||
final var givenUserName = "test-user-" + System.currentTimeMillis() + "@example.com";
|
||||
final var givenUser = jpaAttempt.transacted(() -> {
|
||||
context.define(null);
|
||||
context.define("superuser-alex@hostsharing.net");
|
||||
return rbacSubjectRepository.create(new RbacSubjectEntity(UUID.randomUUID(), givenUserName));
|
||||
}).assumeSuccessful().returnedValue();
|
||||
assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNotNull();
|
||||
|
||||
Reference in New Issue
Block a user