Skip to content

Commit c9ac3be

Browse files
letcodespeakmaibin
authored andcommitted
BAEL-2569 : EnvironmentPostProcessor in Spring Boot (eugenp#6479)
* BAEL-2569 : EnvironmentPostProcessor in Spring Boot * BAEL-2569 add test * BAEL-2569 update test
1 parent 8ecfd8d commit c9ac3be

9 files changed

Lines changed: 257 additions & 1 deletion

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.environmentpostprocessor;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
import java.util.stream.Collectors;
6+
7+
import org.slf4j.Logger;
8+
import org.slf4j.LoggerFactory;
9+
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.boot.CommandLineRunner;
11+
import org.springframework.boot.SpringApplication;
12+
import org.springframework.boot.autoconfigure.SpringBootApplication;
13+
14+
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
15+
16+
@SpringBootApplication
17+
public class PriceCalculationApplication implements CommandLineRunner {
18+
19+
@Autowired
20+
PriceCalculationService priceCalculationService;
21+
22+
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationApplication.class);
23+
24+
public static void main(String[] args) {
25+
SpringApplication.run(PriceCalculationApplication.class, args);
26+
}
27+
28+
@Override
29+
public void run(String... args) throws Exception {
30+
31+
List<String> params = Arrays.stream(args)
32+
.collect(Collectors.toList());
33+
if (verifyArguments(params)) {
34+
double singlePrice = Double.valueOf(params.get(0));
35+
int quantity = Integer.valueOf(params.get(1));
36+
priceCalculationService.productTotalPrice(singlePrice, quantity);
37+
} else {
38+
logger.error("Invalid arguments " + params.toString());
39+
}
40+
41+
}
42+
43+
private boolean verifyArguments(List<String> args) {
44+
boolean successful = true;
45+
if (args.size() != 2) {
46+
successful = false;
47+
return successful;
48+
}
49+
try {
50+
double singlePrice = Double.valueOf(args.get(0));
51+
int quantity = Integer.valueOf(args.get(1));
52+
} catch (NumberFormatException e) {
53+
successful = false;
54+
}
55+
return successful;
56+
57+
}
58+
59+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.baeldung.environmentpostprocessor;
2+
3+
import java.util.LinkedHashMap;
4+
import java.util.Map;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.boot.SpringApplication;
9+
import org.springframework.boot.env.EnvironmentPostProcessor;
10+
import org.springframework.core.Ordered;
11+
import org.springframework.core.env.ConfigurableEnvironment;
12+
import org.springframework.core.env.MapPropertySource;
13+
import org.springframework.core.env.PropertySource;
14+
import org.springframework.core.env.StandardEnvironment;
15+
16+
public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
17+
18+
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class);
19+
20+
public static final int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE;
21+
private int order = DEFAULT_ORDER;
22+
private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor.";
23+
private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode";
24+
private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate";
25+
private static final String OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE = "NET";
26+
private static final double OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0;
27+
28+
@Override
29+
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
30+
31+
PropertySource<?> systemEnvironmentPropertySource = environment.getPropertySources()
32+
.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
33+
34+
Map<String, Object> priceCalculationConfiguration = new LinkedHashMap<>();
35+
if (isActive(systemEnvironmentPropertySource)) {
36+
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE));
37+
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE));
38+
} else {
39+
logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE,
40+
OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
41+
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE);
42+
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
43+
}
44+
45+
PropertySource<?> priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", priceCalculationConfiguration);
46+
environment.getPropertySources()
47+
.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource);
48+
49+
}
50+
51+
private String key(String key) {
52+
return PROPERTY_PREFIX + key.replaceAll("\\_", ".");
53+
}
54+
55+
private boolean isActive(PropertySource<?> systemEnvpropertySource) {
56+
if (systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_CALCUATION_MODE) && systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)) {
57+
return true;
58+
} else
59+
return false;
60+
}
61+
62+
public void setOrder(int order) {
63+
this.order = order;
64+
}
65+
66+
@Override
67+
public int getOrder() {
68+
return order;
69+
}
70+
71+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.environmentpostprocessor.autoconfig;
2+
3+
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
4+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
5+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.core.Ordered;
9+
10+
import com.baeldung.environmentpostprocessor.calculator.GrossPriceCalculator;
11+
import com.baeldung.environmentpostprocessor.calculator.NetPriceCalculator;
12+
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
13+
14+
@Configuration
15+
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
16+
public class PriceCalculationAutoConfig {
17+
18+
@Bean
19+
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "NET")
20+
@ConditionalOnMissingBean
21+
public PriceCalculator getNetPriceCalculator() {
22+
return new NetPriceCalculator();
23+
}
24+
25+
@Bean
26+
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "GROSS")
27+
@ConditionalOnMissingBean
28+
public PriceCalculator getGrossPriceCalculator() {
29+
return new GrossPriceCalculator();
30+
}
31+
32+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.environmentpostprocessor.calculator;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.beans.factory.annotation.Value;
6+
7+
public class GrossPriceCalculator implements PriceCalculator {
8+
9+
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
10+
11+
@Value("${com.baeldung.environmentpostprocessor.gross.calculation.tax.rate}")
12+
double taxRate;
13+
14+
@Override
15+
public double calculate(double singlePrice, int quantity) {
16+
logger.info("Gross based price calculation with input parameters [singlePrice = {},quantity= {} ], {} percent tax applied.", singlePrice, quantity, taxRate * 100);
17+
double netPrice = singlePrice * quantity;
18+
double result = Math.round(netPrice * (1 + taxRate));
19+
logger.info("Calcuation result is {}", result);
20+
return result;
21+
}
22+
23+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.environmentpostprocessor.calculator;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
public class NetPriceCalculator implements PriceCalculator {
7+
8+
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
9+
10+
@Override
11+
public double calculate(double singlePrice, int quantity) {
12+
logger.info("Net based price calculation with input parameters [singlePrice = {},quantity= {} ], NO tax applied.", singlePrice, quantity);
13+
double result = Math.round(singlePrice * quantity);
14+
logger.info("Calcuation result is {}", result);
15+
return result;
16+
}
17+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package com.baeldung.environmentpostprocessor.calculator;
2+
3+
public interface PriceCalculator {
4+
public double calculate(double singlePrice, int quantity);
5+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.environmentpostprocessor.service;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.stereotype.Service;
5+
6+
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
7+
8+
@Service
9+
public class PriceCalculationService {
10+
11+
@Autowired
12+
PriceCalculator priceCalculator;
13+
14+
public double productTotalPrice(double singlePrice, int quantity) {
15+
return priceCalculator.calculate(singlePrice, quantity);
16+
}
17+
}
Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
1-
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
1+
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
2+
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
3+
com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig
4+
5+
org.springframework.boot.env.EnvironmentPostProcessor=\
6+
com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor
7+
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.environmentpostprocessor;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
import org.junit.runner.RunWith;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.boot.test.context.SpringBootTest;
9+
import org.springframework.test.context.junit4.SpringRunner;
10+
11+
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
12+
13+
@RunWith(SpringRunner.class)
14+
@SpringBootTest(classes = PriceCalculationApplication.class)
15+
public class PriceCalculationEnvironmentPostProcessorLiveTest {
16+
17+
@Autowired
18+
PriceCalculationService pcService;
19+
20+
@Test
21+
public void whenSetNetEnvironmentVariablebyDefault_thenNoTaxApplied() {
22+
double total = pcService.productTotalPrice(100, 4);
23+
assertEquals(400.0, total, 0);
24+
}
25+
26+
}

0 commit comments

Comments
 (0)