Spark graphx moved to a new project due to a incompatibility of scala compiler

This commit is contained in:
Norberto Ritzmann Jr
2019-10-06 21:57:54 +02:00
parent db85c8f275
commit 45be61376e
20299 changed files with 1635696 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
## Spring Boot Operations
This module contains articles about Spring Boot Operations
### Relevant Articles:
- [Deploy a Spring Boot WAR into a Tomcat Server](https://www.baeldung.com/spring-boot-war-tomcat-deploy)
- [Spring Boot Dependency Management with a Custom Parent](https://www.baeldung.com/spring-boot-dependency-management-custom-parent)
- [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder)
- [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot)
- [Introduction to WebJars](https://www.baeldung.com/maven-webjars)
- [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters)
- [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper)
- [Shutdown a Spring Boot Application](https://www.baeldung.com/spring-boot-shutdown)
- [Spring Boot Console Application](https://www.baeldung.com/spring-boot-console-app)
- [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers)
- [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app)
- [Spring Properties File Outside jar](https://www.baeldung.com/spring-properties-file-outside-jar)
- [EnvironmentPostProcessor in Spring Boot](https://www.baeldung.com/spring-boot-environmentpostprocessor)
- [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar)
- More articles: [[next -->]](/spring-boot-ops-2)
+16
View File
@@ -0,0 +1,16 @@
# Alpine Linux with OpenJDK JRE
FROM openjdk:8-jre-alpine
RUN apk add --no-cache bash
# copy fat WAR
COPY spring-boot-ops.war /app.war
# copy fat WAR
COPY logback.xml /logback.xml
COPY run.sh /run.sh
# runs application
#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"]
ENTRYPOINT ["/run.sh"]
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>/var/log/WebjarsdemoApplication/application.log</file>
<append>true</append>
<encoder>
<pattern>%-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war
+203
View File
@@ -0,0 +1,203 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-ops</artifactId>
<name>spring-boot-ops</name>
<packaging>war</packaging>
<description>Demo project for Spring Boot</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>${subethasmtp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>${jquery.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
<version>${springcloud.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/conf.properties</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<mainClass>com.baeldung.webjar.WebjarsdemoApplication</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.18</version>
<executions>
<!-- Invokes both the integration-test and the verify goals of the Failsafe
Maven plugin -->
<execution>
<id>integration-tests</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<!-- Skips integration tests if the value of skip.integration.tests
property is true -->
<includes>
<include>**/ExternalPropertyFileLoaderIntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- The main class to start by executing java -jar -->
<start-class>org.baeldung.boot.Application</start-class>
<jquery.version>3.1.1</jquery.version>
<bootstrap.version>3.3.7-1</bootstrap.version>
<jpa.version>2.2</jpa.version>
<guava.version>18.0</guava.version>
<subethasmtp.version>3.1.7</subethasmtp.version>
<springcloud.version>2.0.2.RELEASE</springcloud.version>
<httpclient.version>4.5.8</httpclient.version>
</properties>
</project>
@@ -0,0 +1,12 @@
package com.baeldung.compare;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ComparisonApplication {
public static void main(String[] args) {
SpringApplication.run(ComparisonApplication.class, args);
}
}
@@ -0,0 +1,65 @@
package com.baeldung.compare;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Statistic;
@Component
public class StartupEventHandler {
// logger, constructor
private static Logger logger = LoggerFactory.getLogger(StartupEventHandler.class);
public StartupEventHandler(MeterRegistry registry) {
this.meterRegistry = registry;
}
private String[] METRICS = {
"jvm.memory.used",
"jvm.classes.loaded",
"jvm.threads.live"};
private String METRIC_MSG_FORMAT = "Startup Metric >> {}={}";
private MeterRegistry meterRegistry;
@EventListener
public void getAndLogStartupMetrics(
ApplicationReadyEvent event) {
Arrays.asList(METRICS)
.forEach(this::getAndLogActuatorMetric);
}
private void getAndLogActuatorMetric(String metric) {
Meter meter = meterRegistry.find(metric).meter();
Map<Statistic, Double> stats = getSamples(meter);
logger.info(METRIC_MSG_FORMAT, metric, stats.get(Statistic.VALUE).longValue());
}
private Map<Statistic, Double> getSamples(Meter meter) {
Map<Statistic, Double> samples = new LinkedHashMap<>();
mergeMeasurements(samples, meter);
return samples;
}
private void mergeMeasurements(Map<Statistic, Double> samples, Meter meter) {
meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(),
measurement.getValue(), mergeFunction(measurement.getStatistic())));
}
private BiFunction<Double, Double, Double> mergeFunction(Statistic statistic) {
return Statistic.MAX.equals(statistic) ? Double::max : Double::sum;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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();
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.environmentpostprocessor.calculator;
public interface PriceCalculator {
public double calculate(double singlePrice, int quantity);
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.restart;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(Application.class, args);
}
public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(Application.class, args.getSourceArgs());
});
thread.setDaemon(false);
thread.start();
}
}
@@ -0,0 +1,23 @@
package com.baeldung.restart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestartController {
@Autowired
private RestartService restartService;
@PostMapping("/restart")
public void restart() {
Application.restart();
}
@PostMapping("/restartApp")
public void restartUsingActuator() {
restartService.restartApp();
}
}
@@ -0,0 +1,17 @@
package com.baeldung.restart;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.restart.RestartEndpoint;
@Service
public class RestartService {
@Autowired
private RestartEndpoint restartEndpoint;
public void restartApp() {
restartEndpoint.restart();
}
}
@@ -0,0 +1,50 @@
package com.baeldung.shutdown;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// closeApplication();
// exitApplication();
// writePID();
}
private static void closeApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
System.out.println("Spring Boot application started");
ctx.getBean(TerminateBean.class);
ctx.close();
}
private static void exitApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
int exitCode = SpringApplication.exit(ctx, () -> {
// return the error code
return 0;
});
System.out.println("Exit Spring Boot");
System.exit(exitCode);
}
private static void writePID() {
SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE);
app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid"));
app.run();
}
}
@@ -0,0 +1,15 @@
package com.baeldung.shutdown;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.shutdown")
public class ShutdownConfig {
@Bean
public TerminateBean getTerminateBean() {
return new TerminateBean();
}
}
@@ -0,0 +1,11 @@
package com.baeldung.shutdown;
import javax.annotation.PreDestroy;
public class TerminateBean {
@PreDestroy
public void onDestroy() throws Exception {
System.out.println("Spring Container is destroyed!");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.shutdown.shutdown;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShutdownController implements ApplicationContextAware {
private ApplicationContext context;
@PostMapping("/shutdownContext")
public void shutdownContext() {
((ConfigurableApplicationContext) context).close();
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
this.context = ctx;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.springbootnonwebapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 1. Act as main class for spring boot application
* 2. Also implements CommandLineRunner, so that code within run method
* is executed before application startup but after all beans are effectively created
* @author hemant
*
*/
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);
public static void main(String[] args) {
LOG.info("STARTING THE APPLICATION");
SpringApplication.run(SpringBootConsoleApplication.class, args);
LOG.info("APPLICATION FINISHED");
}
/**
* This method will be executed after the application context is loaded and
* right before the Spring Application main method is completed.
*/
@Override
public void run(String... args) throws Exception {
LOG.info("EXECUTING : command line runner");
for (int i = 0; i < args.length; ++i) {
LOG.info("args[{}]: {}", i, args[i]);
}
}
}
@@ -0,0 +1,13 @@
package com.baeldung.springbootsimple;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.web.servlet.support.*;
@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringBootTomcatApplication.class, args);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.springbootsimple;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.*;
@RestController
public class TomcatController {
@GetMapping(value = "/hello")
public Collection<String> sayHello() {
return IntStream.range(0, 10)
.mapToObj(i -> "Hello number " + i)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,15 @@
package com.baeldung.webjar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
@GetMapping(value = "/")
public String welcome(Model model) {
return "index";
}
}
@@ -0,0 +1,12 @@
package com.baeldung.webjar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebjarsdemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebjarsdemoApplication.class, args);
}
}
@@ -0,0 +1,14 @@
package org.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,30 @@
package org.baeldung.boot.config;
import java.util.List;
import org.baeldung.boot.converter.GenericBigDecimalConverter;
import org.baeldung.boot.converter.StringToAbstractEntityConverterFactory;
import org.baeldung.boot.converter.StringToEmployeeConverter;
import org.baeldung.boot.converter.StringToEnumConverter;
import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HeaderVersionArgumentResolver());
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToEmployeeConverter());
registry.addConverter(new StringToEnumConverter());
registry.addConverterFactory(new StringToAbstractEntityConverterFactory());
registry.addConverter(new GenericBigDecimalConverter());
}
}
@@ -0,0 +1,58 @@
package org.baeldung.boot.controller;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.domain.Modes;
import org.baeldung.boot.web.resolver.Version;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RestController
public class GenericEntityController {
private List<GenericEntity> entityList = new ArrayList<>();
{
entityList.add(new GenericEntity(1l, "entity_1"));
entityList.add(new GenericEntity(2l, "entity_2"));
entityList.add(new GenericEntity(3l, "entity_3"));
entityList.add(new GenericEntity(4l, "entity_4"));
}
@GetMapping("/entity/all")
public List<GenericEntity> findAll() {
return entityList;
}
@PostMapping("/entity")
public GenericEntity addEntity(GenericEntity entity) {
entityList.add(entity);
return entity;
}
@GetMapping("/entity/findby/{id}")
public GenericEntity findById(@PathVariable Long id) {
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
}
@GetMapping("/entity/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbymode/{mode}")
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbyversion")
public ResponseEntity findByVersion(@Version String version) {
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@@ -0,0 +1,34 @@
package org.baeldung.boot.converter;
import com.google.common.collect.ImmutableSet;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import java.math.BigDecimal;
import java.util.Set;
public class GenericBigDecimalConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
return ImmutableSet.copyOf(pairs);
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (sourceType.getType() == BigDecimal.class) {
return source;
}
if (sourceType.getType() == String.class) {
String number = (String) source;
return new BigDecimal(number);
} else {
Number number = (Number) source;
BigDecimal converted = new BigDecimal(number.doubleValue());
return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN);
}
}
}
@@ -0,0 +1,39 @@
package org.baeldung.boot.converter;
import org.baeldung.boot.domain.AbstractEntity;
import org.baeldung.boot.domain.Bar;
import org.baeldung.boot.domain.Foo;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
public class StringToAbstractEntityConverterFactory implements ConverterFactory<String, AbstractEntity>{
@Override
public <T extends AbstractEntity> Converter<String, T> getConverter(Class<T> targetClass) {
return new StringToAbstractEntityConverter<>(targetClass);
}
private static class StringToAbstractEntityConverter<T extends AbstractEntity> implements Converter<String, T> {
private Class<T> targetClass;
public StringToAbstractEntityConverter(Class<T> targetClass) {
this.targetClass = targetClass;
}
@Override
public T convert(String source) {
long id = Long.parseLong(source);
if(this.targetClass == Foo.class) {
return (T) new Foo(id);
}
else if(this.targetClass == Bar.class) {
return (T) new Bar(id);
} else {
return null;
}
}
}
}
@@ -0,0 +1,13 @@
package org.baeldung.boot.converter;
import org.baeldung.boot.domain.Employee;
import org.springframework.core.convert.converter.Converter;
public class StringToEmployeeConverter implements Converter<String, Employee> {
@Override
public Employee convert(String from) {
String[] data = from.split(",");
return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1]));
}
}
@@ -0,0 +1,12 @@
package org.baeldung.boot.converter;
import org.baeldung.boot.domain.Modes;
import org.springframework.core.convert.converter.Converter;
public class StringToEnumConverter implements Converter<String, Modes> {
@Override
public Modes convert(String from) {
return Modes.valueOf(from);
}
}
@@ -0,0 +1,16 @@
package org.baeldung.boot.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(final String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
@@ -0,0 +1,31 @@
package org.baeldung.boot.converter.controller;
import org.baeldung.boot.domain.Bar;
import org.baeldung.boot.domain.Foo;
import org.baeldung.boot.domain.Modes;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/string-to-abstract")
public class AbstractEntityController {
@GetMapping("/foo/{foo}")
public ResponseEntity<Object> getStringToFoo(@PathVariable Foo foo) {
return ResponseEntity.ok(foo);
}
@GetMapping("/bar/{bar}")
public ResponseEntity<Object> getStringToBar(@PathVariable Bar bar) {
return ResponseEntity.ok(bar);
}
@GetMapping
public ResponseEntity<Object> getStringToMode(@RequestParam("mode") Modes mode) {
return ResponseEntity.ok(mode);
}
}
@@ -0,0 +1,15 @@
package org.baeldung.boot.converter.controller;
import org.baeldung.boot.domain.Employee;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/string-to-employee")
public class StringToEmployeeConverterController {
@GetMapping
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
return ResponseEntity.ok(employee);
}
}
@@ -0,0 +1,10 @@
package org.baeldung.boot.domain;
public abstract class AbstractEntity {
long id;
public AbstractEntity(long id){
this.id = id;
}
}
@@ -0,0 +1,29 @@
package org.baeldung.boot.domain;
public class Bar extends AbstractEntity {
private int value;
public Bar(long id) {
super(id);
}
public Bar(long id, int value) {
super(id);
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "Bar [value=" + value + ", id=" + id + "]";
}
}
@@ -0,0 +1,37 @@
package org.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private long id;
private double salary;
public Employee() {
}
public Employee(long id, double salary) {
this.id = id;
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
@@ -0,0 +1,31 @@
package org.baeldung.boot.domain;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
public class Foo extends AbstractEntity {
private String name;
public Foo(long id) {
super(id);
name = randomAlphanumeric(4);
}
public Foo(long id, String name) {
super(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Foo [name=" + name + ", id=" + id + "]";
}
}
@@ -0,0 +1,42 @@
package org.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class GenericEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public GenericEntity() {
}
public GenericEntity(String value) {
this.value = value;
}
public GenericEntity(Long id, String value) {
this.id = id;
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,6 @@
package org.baeldung.boot.domain;
public enum Modes {
ALPHA, BETA;
}
@@ -0,0 +1,7 @@
package org.baeldung.boot.repository;
import org.baeldung.boot.domain.GenericEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
}
@@ -0,0 +1,26 @@
package org.baeldung.boot.web.resolver;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
@Component
public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(final MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(Version.class) != null;
}
@Override
public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
return request.getHeader("Version");
}
}
@@ -0,0 +1,11 @@
package org.baeldung.boot.web.resolver;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Version {
}
@@ -0,0 +1,6 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor
@@ -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
@@ -0,0 +1,4 @@
db.url=jdbc:postgresql://localhost:5432/
db.username=admin
db.password=root
spring.main.allow-bean-definition-overriding=true
@@ -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>
@@ -0,0 +1,19 @@
<html>
<head>
<title>WebJars Demo</title>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
</head>
<body>
<h1>Welcome Home</h1>
<div class="container"><br/>
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Success!</strong> It is working as we expected.
</div>
</div>
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
</body>
</html>
@@ -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);
}
}
@@ -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());
}
}
@@ -0,0 +1,38 @@
package com.baeldung.restart;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
/**
* We have to make sure that while running this test, 8080 and 8090 ports are free.
* Otherwise it will fail.
*/
public class RestartApplicationManualTest {
private TestRestTemplate restTemplate = new TestRestTemplate();
@Test
public void givenBootApp_whenRestart_thenOk() throws Exception {
Application.main(new String[0]);
ResponseEntity response = restTemplate.exchange("http://localhost:8080/restart",
HttpMethod.POST, null, Object.class);
assertEquals(200, response.getStatusCode().value());
}
@Test
public void givenBootApp_whenRestartUsingActuator_thenOk() throws Exception {
Application.main(new String[] { "--server.port=8090" });
ResponseEntity response = restTemplate.exchange("http://localhost:8090/restartApp",
HttpMethod.POST, null, Object.class);
assertEquals(200, response.getStatusCode().value());
}
}
@@ -0,0 +1,40 @@
package com.baeldung.shutdown;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class)
@AutoConfigureMockMvc
public class ShutdownApplicationIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
@Ignore
public void givenBootApp_whenShutdownEndpoint_thenExit() throws Exception {
mockMvc.perform(post("/shutdown")).andExpect(status().isOk());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.springbootsimple;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTomcatApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,18 @@
package com.baeldung.webjar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = WebjarsdemoApplication.class)
@WebAppConfiguration
public class WebjarsdemoApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,69 @@
package org.baeldung;
import org.baeldung.boot.Application;
import org.baeldung.boot.domain.Modes;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class SpringBootApplicationIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
}
}
@@ -0,0 +1,28 @@
package org.baeldung;
import org.baeldung.boot.Application;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,80 @@
package org.baeldung;
import org.baeldung.boot.Application;
import org.junit.After;
import org.junit.Before;
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.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootMailIntegrationTest {
@Autowired
private JavaMailSender javaMailSender;
private Wiser wiser;
private String userTo = "user2@localhost";
private String userFrom = "user1@localhost";
private String subject = "Test subject";
private String textMail = "Text subject mail";
@Before
public void setUp() throws Exception {
final int TEST_PORT = 8025;
wiser = new Wiser(TEST_PORT);
wiser.start();
}
@After
public void tearDown() throws Exception {
wiser.stop();
}
@Test
public void givenMail_whenSendAndReceived_thenCorrect() throws Exception {
SimpleMailMessage message = composeEmailMessage();
javaMailSender.send(message);
List<WiserMessage> messages = wiser.getMessages();
assertThat(messages, hasSize(1));
WiserMessage wiserMessage = messages.get(0);
assertEquals(userFrom, wiserMessage.getEnvelopeSender());
assertEquals(userTo, wiserMessage.getEnvelopeReceiver());
assertEquals(subject, getSubject(wiserMessage));
assertEquals(textMail, getMessage(wiserMessage));
}
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
return wiserMessage.getMimeMessage().getContent().toString().trim();
}
private String getSubject(WiserMessage wiserMessage) throws MessagingException {
return wiserMessage.getMimeMessage().getSubject();
}
private SimpleMailMessage composeEmailMessage() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userTo);
mailMessage.setReplyTo(userFrom);
mailMessage.setFrom(userFrom);
mailMessage.setSubject(subject);
mailMessage.setText(textMail);
return mailMessage;
}
}
@@ -0,0 +1,4 @@
spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test
spring.datasource.username=root
spring.datasource.password=root
@@ -0,0 +1,12 @@
spring.mail.host=localhost
spring.mail.port=8025
spring.mail.properties.mail.smtp.auth=false
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
endpoints.shutdown.enabled=true
management.endpoint.restart.enabled=true
spring.main.allow-bean-definition-overriding=true
spring.jmx.unique-names=true