Skip to content

Commit 090ddc6

Browse files
committed
GH-119 - Improve rendering of application modules structure as JSON.
Introduced ApplicationModulesExporter to render an ApplicationModules instances as JSON directly. To avoid a dependency to a JSON library and as we only have to be able to render rather simple arrangements, we just build up the JSON string ourselves. ApplicationModulesEndpoint now caches the structure calculated once to avoid repeated work.
1 parent 9082ca2 commit 090ddc6

File tree

6 files changed

+254
-58
lines changed

6 files changed

+254
-58
lines changed

spring-modulith-actuator/src/main/java/org/springframework/modulith/actuator/ApplicationModulesEndpoint.java

Lines changed: 6 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -15,26 +15,17 @@
1515
*/
1616
package org.springframework.modulith.actuator;
1717

18-
import static java.util.stream.Collectors.*;
19-
20-
import java.util.LinkedHashMap;
2118
import java.util.Map;
22-
import java.util.Map.Entry;
23-
import java.util.Set;
24-
import java.util.function.Function;
2519
import java.util.function.Supplier;
26-
import java.util.stream.Collector;
27-
import java.util.stream.Collectors;
2820

2921
import org.slf4j.Logger;
3022
import org.slf4j.LoggerFactory;
3123
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
3224
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
33-
import org.springframework.modulith.core.ApplicationModule;
34-
import org.springframework.modulith.core.ApplicationModuleDependency;
3525
import org.springframework.modulith.core.ApplicationModules;
36-
import org.springframework.modulith.core.DependencyType;
26+
import org.springframework.modulith.core.util.ApplicationModulesExporter;
3727
import org.springframework.util.Assert;
28+
import org.springframework.util.function.SingletonSupplier;
3829

3930
/**
4031
* A Spring Boot actuator endpoint to expose the application module structure of a Spring Modulith based application.
@@ -46,20 +37,7 @@ public class ApplicationModulesEndpoint {
4637

4738
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModulesEndpoint.class);
4839

49-
private static final Function<Set<DependencyType>, Set<DependencyType>> REMOVE_DEFAULT_DEPENDENCY_TYPE_IF_OTHERS_PRESENT = it -> {
50-
51-
if (it.stream().anyMatch(type -> type != DependencyType.DEFAULT)) {
52-
it.remove(DependencyType.DEFAULT);
53-
}
54-
55-
return it;
56-
};
57-
58-
private static final Collector<ApplicationModuleDependency, ?, Set<DependencyType>> MAPPER = mapping(
59-
ApplicationModuleDependency::getDependencyType,
60-
collectingAndThen(toSet(), REMOVE_DEFAULT_DEPENDENCY_TYPE_IF_OTHERS_PRESENT));
61-
62-
private final Supplier<ApplicationModules> runtime;
40+
private final SingletonSupplier<String> structure;
6341

6442
/**
6543
* Creates a new {@link ApplicationModulesEndpoint} for the given {@link ApplicationModules}.
@@ -72,7 +50,7 @@ public ApplicationModulesEndpoint(Supplier<ApplicationModules> runtime) {
7250

7351
LOGGER.debug("Activating Spring Modulith actuator.");
7452

75-
this.runtime = runtime;
53+
this.structure = SingletonSupplier.of(new ApplicationModulesExporter(runtime.get())::toJson);
7654
}
7755

7856
/**
@@ -81,34 +59,7 @@ public ApplicationModulesEndpoint(Supplier<ApplicationModules> runtime) {
8159
* @return will never be {@literal null}.
8260
*/
8361
@ReadOperation
84-
Map<String, Object> getApplicationModules() {
85-
86-
var modules = runtime.get();
87-
88-
return modules.stream()
89-
.collect(
90-
Collectors.toMap(ApplicationModule::getName, it -> toInfo(it, modules), (l, r) -> r, LinkedHashMap::new));
91-
}
92-
93-
private static Map<String, Object> toInfo(ApplicationModule module, ApplicationModules modules) {
94-
95-
return Map.of( //
96-
"displayName", module.getDisplayName(), //
97-
"basePackage", module.getBasePackage().getName(), //
98-
"dependencies", module.getDependencies(modules).stream() //
99-
.collect(Collectors.groupingBy(ApplicationModuleDependency::getTargetModule, MAPPER))
100-
.entrySet() //
101-
.stream() //
102-
.map(ApplicationModulesEndpoint::toInfo) //
103-
.toList() //
104-
);
105-
}
106-
107-
private static Map<String, Object> toInfo(Entry<ApplicationModule, ? extends Set<DependencyType>> types) {
108-
109-
return Map.of( //
110-
"target", types.getKey().getName(), //
111-
"types", types.getValue() //
112-
);
62+
String getApplicationModules() {
63+
return structure.obtain();
11364
}
11465
}

spring-modulith-actuator/src/test/java/org/springframework/modulith/actuator/ApplicationModulesEndpointIntegrationTests.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import org.junit.jupiter.api.Test;
2323
import org.springframework.modulith.test.TestApplicationModules;
2424

25-
import com.fasterxml.jackson.databind.ObjectMapper;
2625
import com.jayway.jsonpath.JsonPath;
2726

2827
/**
@@ -38,7 +37,7 @@ void exposesApplicationModulesAsMap() throws Exception {
3837
var modules = TestApplicationModules.of("example");
3938
var endpoint = new ApplicationModulesEndpoint(() -> modules);
4039
var result = endpoint.getApplicationModules();
41-
var context = JsonPath.parse(new ObjectMapper().writeValueAsString(result));
40+
var context = JsonPath.parse(result);
4241

4342
assertThat(context.<String> read("$.a.basePackage")).isEqualTo("example.a");
4443
assertThat(context.<JSONArray> read("$.a.dependencies")).isEmpty();
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.modulith.core.util;
17+
18+
import static java.util.stream.Collectors.*;
19+
20+
import java.util.LinkedHashMap;
21+
import java.util.Map;
22+
import java.util.Map.Entry;
23+
import java.util.Set;
24+
import java.util.function.Function;
25+
import java.util.stream.Collector;
26+
import java.util.stream.Collectors;
27+
28+
import org.springframework.modulith.core.ApplicationModule;
29+
import org.springframework.modulith.core.ApplicationModuleDependency;
30+
import org.springframework.modulith.core.ApplicationModules;
31+
import org.springframework.modulith.core.DependencyType;
32+
import org.springframework.util.Assert;
33+
34+
/**
35+
* Export the structure of {@link ApplicationModules} as JSON.
36+
*
37+
* @author Oliver Drotbohm
38+
*/
39+
public class ApplicationModulesExporter {
40+
41+
private static final Function<Set<DependencyType>, Set<DependencyType>> REMOVE_DEFAULT_DEPENDENCY_TYPE_IF_OTHERS_PRESENT = it -> {
42+
43+
if (it.stream().anyMatch(type -> type != DependencyType.DEFAULT)) {
44+
it.remove(DependencyType.DEFAULT);
45+
}
46+
47+
return it;
48+
};
49+
50+
private static final Collector<ApplicationModuleDependency, ?, Set<DependencyType>> MAPPER = mapping(
51+
ApplicationModuleDependency::getDependencyType,
52+
collectingAndThen(toSet(), REMOVE_DEFAULT_DEPENDENCY_TYPE_IF_OTHERS_PRESENT));
53+
54+
private final ApplicationModules modules;
55+
56+
/**
57+
* Creates a new {@link ApplicationModulesExporter} for the given {@link ApplicationModules}.
58+
*
59+
* @param modules must not be {@literal null}.
60+
*/
61+
public ApplicationModulesExporter(ApplicationModules modules) {
62+
63+
Assert.notNull(modules, "ApplicationModules must not be null!");
64+
65+
this.modules = modules;
66+
}
67+
68+
/**
69+
* Simple main method to render the {@link ApplicationModules} instance defined for the Java package given as first
70+
* argument.
71+
*
72+
* @param args a single-element array containing a Java package name to bootstrap an {@link ApplicationModules}
73+
* instance from.
74+
*/
75+
public static void main(String[] args) {
76+
77+
Assert.notNull(args, "Arguments must not be null!");
78+
Assert.isTrue(args.length == 1, "A java package name is required as only argument!");
79+
80+
System.out.println(new ApplicationModulesExporter(ApplicationModules.of(args[0])).toJson());
81+
}
82+
83+
/**
84+
* Returns the {@link ApplicationModules} structure as JSON String.
85+
*
86+
* @return will never be {@literal null}.
87+
*/
88+
public String toJson() {
89+
return Json.toString(toMap());
90+
}
91+
92+
private Map<String, Object> toMap() {
93+
94+
return modules.stream()
95+
.collect(
96+
Collectors.toMap(ApplicationModule::getName, it -> toInfo(it, modules), (l, r) -> r, LinkedHashMap::new));
97+
}
98+
99+
private static Map<String, Object> toInfo(ApplicationModule module, ApplicationModules modules) {
100+
101+
return Map.of( //
102+
"displayName", module.getDisplayName(), //
103+
"basePackage", module.getBasePackage().getName(), //
104+
"dependencies", module.getDependencies(modules).stream() //
105+
.collect(Collectors.groupingBy(ApplicationModuleDependency::getTargetModule, MAPPER))
106+
.entrySet() //
107+
.stream() //
108+
.map(ApplicationModulesExporter::toInfo) //
109+
.toList() //
110+
);
111+
}
112+
113+
private static Map<String, Object> toInfo(Entry<ApplicationModule, ? extends Set<DependencyType>> types) {
114+
115+
return Map.of( //
116+
"target", types.getKey().getName(), //
117+
"types", types.getValue() //
118+
);
119+
}
120+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.modulith.core.util;
17+
18+
import java.util.Collection;
19+
import java.util.Map;
20+
import java.util.Map.Entry;
21+
import java.util.stream.Collectors;
22+
23+
/**
24+
* Helper to render a {@link Map} as JSON. Key need to be {@link #toString()}-able, values need to be
25+
* {@link #toString()}-able, too, be an enum, a {@link Collection} or {@link Map}.
26+
*
27+
* @author Oliver Drotbohm
28+
*/
29+
class Json {
30+
31+
@SuppressWarnings({ "rawtypes", "unchecked" })
32+
static String toString(Object object) {
33+
34+
if (object instanceof String string) {
35+
return quote(string);
36+
}
37+
38+
if (object instanceof Collection collection) {
39+
return toString(collection);
40+
}
41+
42+
if (object instanceof Map map) {
43+
return toString(map);
44+
}
45+
46+
if (object instanceof Enum value) {
47+
return quote(value.name());
48+
}
49+
50+
return object.toString();
51+
}
52+
53+
private static String toString(Map<Object, Object> map) {
54+
55+
return map.isEmpty()
56+
? "{}"
57+
: map.entrySet().stream()
58+
.map(Json::toString)
59+
.collect(Collectors.joining(", ", "{ ", " }"));
60+
}
61+
62+
private static String toString(Entry<Object, Object> entry) {
63+
return "\"" + entry.getKey() + "\" : " + toString(entry.getValue());
64+
}
65+
66+
private static String toString(Collection<Object> collection) {
67+
68+
return collection.isEmpty()
69+
? "[]"
70+
: collection.stream().map(Json::toString).collect(Collectors.joining(", ", "[ ", " ]"));
71+
}
72+
73+
private static String quote(String string) {
74+
return "\"" + string + "\"";
75+
}
76+
}

spring-modulith-integration-test/pom.xml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,20 @@
5252
<artifactId>spring-tx</artifactId>
5353
</dependency>
5454

55+
<!-- Test -->
56+
5557
<dependency>
5658
<groupId>org.springframework.boot</groupId>
5759
<artifactId>spring-boot-starter-test</artifactId>
5860
<scope>test</scope>
5961
</dependency>
60-
62+
63+
<dependency>
64+
<groupId>com.fasterxml.jackson.core</groupId>
65+
<artifactId>jackson-databind</artifactId>
66+
<scope>test</scope>
67+
</dependency>
68+
6169
<dependency>
6270
<groupId>org.jgrapht</groupId>
6371
<artifactId>jgrapht-core</artifactId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.modulith.core.util;
17+
18+
import static org.assertj.core.api.Assertions.*;
19+
20+
import org.junit.jupiter.api.Test;
21+
import org.springframework.modulith.core.ApplicationModules;
22+
23+
import com.acme.myproject.Application;
24+
import com.fasterxml.jackson.databind.ObjectMapper;
25+
26+
/**
27+
* Unit tests for {@link ApplicationModulesExporter}.
28+
*
29+
* @author Oliver Drotbohm
30+
*/
31+
public class ApplicationModulesExporterUnitTests {
32+
33+
@Test // #119
34+
void rendersApplicationModulesAsJson() {
35+
36+
var json = new ApplicationModulesExporter(ApplicationModules.of(Application.class)).toJson();
37+
38+
assertThatNoException().isThrownBy(() -> {
39+
new ObjectMapper().readTree(json);
40+
});
41+
}
42+
}

0 commit comments

Comments
 (0)