BAEL-20869 Move remaining spring boot modules

This commit is contained in:
mikr
2020-02-02 20:44:54 +01:00
parent 80a2cfec65
commit 56a9403564
704 changed files with 1303 additions and 1501 deletions

View File

@@ -0,0 +1,59 @@
package com.baeldung.environmentpostprocessor;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
@SpringBootApplication
public class PriceCalculationApplication implements CommandLineRunner {
@Autowired
PriceCalculationService priceCalculationService;
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationApplication.class);
public static void main(String[] args) {
SpringApplication.run(PriceCalculationApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
List<String> params = Arrays.stream(args)
.collect(Collectors.toList());
if (verifyArguments(params)) {
double singlePrice = Double.valueOf(params.get(0));
int quantity = Integer.valueOf(params.get(1));
priceCalculationService.productTotalPrice(singlePrice, quantity);
} else {
logger.warn("Invalid arguments " + params.toString());
}
}
private boolean verifyArguments(List<String> args) {
boolean successful = true;
if (args.size() != 2) {
successful = false;
return successful;
}
try {
double singlePrice = Double.valueOf(args.get(0));
int quantity = Integer.valueOf(args.get(1));
} catch (NumberFormatException e) {
successful = false;
}
return successful;
}
}

View File

@@ -0,0 +1,81 @@
package com.baeldung.environmentpostprocessor;
import static org.springframework.core.env.StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
@Order(Ordered.LOWEST_PRECEDENCE)
public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class);
private static final String PREFIX = "com.baeldung.environmentpostprocessor.";
private static final String CALCUATION_MODE = "calculation_mode";
private static final String GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate";
private static final String CALCUATION_MODE_DEFAULT_VALUE = "NET";
private static final double GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0;
List<String> names = Arrays.asList(CALCUATION_MODE, GROSS_CALCULATION_TAX_RATE);
private static Map<String, Object> defaults = new LinkedHashMap<>();
static {
defaults.put(CALCUATION_MODE, CALCUATION_MODE_DEFAULT_VALUE);
defaults.put(GROSS_CALCULATION_TAX_RATE, GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
PropertySource<?> system = environment.getPropertySources()
.get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
Map<String, Object> prefixed = new LinkedHashMap<>();
if (!hasOurPriceProperties(system)) {
// Baeldung-internal code so this doesn't break other examples
logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
prefixed = names.stream()
.collect(Collectors.toMap(this::rename, this::getDefaultValue));
environment.getPropertySources()
.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
return;
}
prefixed = names.stream()
.collect(Collectors.toMap(this::rename, system::getProperty));
environment.getPropertySources()
.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
}
private Object getDefaultValue(String key) {
return defaults.get(key);
}
private String rename(String key) {
return PREFIX + key.replaceAll("\\_", ".");
}
private boolean hasOurPriceProperties(PropertySource<?> system) {
if (system.containsProperty(CALCUATION_MODE) && system.containsProperty(GROSS_CALCULATION_TAX_RATE)) {
return true;
} else
return false;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.environmentpostprocessor.autoconfig;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import com.baeldung.environmentpostprocessor.calculator.GrossPriceCalculator;
import com.baeldung.environmentpostprocessor.calculator.NetPriceCalculator;
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class PriceCalculationAutoConfig {
@Bean
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "NET")
@ConditionalOnMissingBean
public PriceCalculator getNetPriceCalculator() {
return new NetPriceCalculator();
}
@Bean
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "GROSS")
@ConditionalOnMissingBean
public PriceCalculator getGrossPriceCalculator() {
return new GrossPriceCalculator();
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.environmentpostprocessor.calculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
public class GrossPriceCalculator implements PriceCalculator {
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
@Value("${com.baeldung.environmentpostprocessor.gross.calculation.tax.rate}")
double taxRate;
@Override
public double calculate(double singlePrice, int quantity) {
logger.info("Gross based price calculation with input parameters [singlePrice = {},quantity= {} ], {} percent tax applied.", singlePrice, quantity, taxRate * 100);
double netPrice = singlePrice * quantity;
double result = Math.round(netPrice * (1 + taxRate));
logger.info("Calcuation result is {}", result);
return result;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.environmentpostprocessor.calculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NetPriceCalculator implements PriceCalculator {
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
@Override
public double calculate(double singlePrice, int quantity) {
logger.info("Net based price calculation with input parameters [singlePrice = {},quantity= {} ], NO tax applied.", singlePrice, quantity);
double result = Math.round(singlePrice * quantity);
logger.info("Calcuation result is {}", result);
return result;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.environmentpostprocessor.calculator;
public interface PriceCalculator {
public double calculate(double singlePrice, int quantity);
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.environmentpostprocessor.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
@Service
public class PriceCalculationService {
@Autowired
PriceCalculator priceCalculator;
public double productTotalPrice(double singlePrice, int quantity) {
return priceCalculator.calculate(singlePrice, quantity);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConfProperties {
@Value("${db.url}")
private String url;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
@Configuration
public class ExternalPropertyConfigurer {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new FileSystemResource("src/main/resources/external/conf.properties"));
properties.setIgnoreResourceNotFound(false);
return properties;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class ExternalPropertyFileLoader {
@Autowired
ConfProperties prop;
public static void main(String[] args) {
new SpringApplicationBuilder(ExternalPropertyFileLoader.class).build()
.run(args);
}
}

View File

@@ -0,0 +1,6 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor

View File

@@ -0,0 +1,7 @@
management.endpoints.web.exposure.include=*
management.metrics.enable.root=true
management.metrics.enable.jvm=true
management.endpoint.restart.enabled=true
spring.datasource.jmx-enabled=false
spring.main.allow-bean-definition-overriding=true
management.endpoint.shutdown.enabled=true

View File

@@ -0,0 +1,4 @@
db.url=jdbc:postgresql://localhost:5432/
db.username=admin
db.password=root
spring.main.allow-bean-definition-overriding=true

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,26 @@
package com.baeldung.environmentpostprocessor;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PriceCalculationApplication.class)
public class PriceCalculationEnvironmentPostProcessorLiveTest {
@Autowired
PriceCalculationService pcService;
@Test
public void whenSetNetEnvironmentVariablebyDefault_thenNoTaxApplied() {
double total = pcService.productTotalPrice(100, 4);
assertEquals(400.0, total, 0);
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.properties;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ExternalPropertyFileLoader.class)
public class ExternalPropertyFileLoaderIntegrationTest {
@Autowired
ConfProperties props;
@Test
public void whenExternalisedPropertiesLoaded_thenReadValues() throws IOException {
assertEquals("jdbc:postgresql://localhost:5432/", props.getUrl());
assertEquals("admin", props.getUsername());
assertEquals("root", props.getPassword());
}
}