1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.micronaut.build.services;
17
18 import io.micronaut.context.env.*;
19 import io.micronaut.context.env.yaml.YamlPropertySourceLoader;
20 import io.micronaut.core.io.file.DefaultFileSystemResourceLoader;
21 import org.apache.maven.project.MavenProject;
22
23 import javax.inject.Inject;
24 import javax.inject.Singleton;
25 import java.io.File;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Optional;
29
30
31
32
33
34
35
36 @Singleton
37 public class ApplicationConfigurationService {
38
39 public static final String DEFAULT_PORT = "8080";
40
41 private final MavenProject mavenProject;
42 private final Map<String, Object> applicationConfiguration;
43
44 @SuppressWarnings("CdiInjectionPointsInspection")
45 @Inject
46 public ApplicationConfigurationService(MavenProject mavenProject) {
47 this.mavenProject = mavenProject;
48 this.applicationConfiguration = parseApplicationConfiguration();
49 }
50
51
52
53
54
55 public String getServerPort() {
56 return applicationConfiguration.getOrDefault("MICRONAUT_SERVER_PORT", applicationConfiguration.getOrDefault("micronaut.server.port", DEFAULT_PORT)).toString();
57 }
58
59 private Map<String, Object> parseApplicationConfiguration() {
60 Map<String, Object> configuration = new HashMap<>();
61
62 PropertySourceLoader[] loaders = {
63 new YamlPropertySourceLoader(),
64 new PropertiesPropertySourceLoader()
65 };
66
67 for (PropertySourceLoader loader : loaders) {
68 Optional<PropertySource> propertySource = loader.load("application", new DefaultFileSystemResourceLoader(new File(mavenProject.getBasedir(), "src/main/resources")));
69 if (propertySource.isPresent()) {
70 MapPropertySource mapPropertySource = (MapPropertySource) propertySource.get();
71 configuration.putAll(mapPropertySource.asMap());
72 }
73 }
74
75 MapPropertySource[] propertySources = {
76 new EnvironmentPropertySource(),
77 new SystemPropertiesPropertySource()
78 };
79 for (MapPropertySource propertySource : propertySources) {
80 configuration.putAll(propertySource.asMap());
81 }
82
83 return configuration;
84 }
85 }