BAEL-20869 Move remaining spring boot modules

This commit is contained in:
mikr
2020-02-02 20:44:54 +01:00
parent 3e26f588fc
commit 06161e1bae
704 changed files with 1303 additions and 1501 deletions
@@ -0,0 +1,12 @@
package com.baeldung.accessparamsjs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.accessparamsjs;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* Sample rest controller for the tutorial article
* "Access Spring MVC Model object in JavaScript".
*
* @author Andrew Shcherbakov
*
*/
@RestController
public class Controller {
/**
* Define two model objects (one integer and one string) and pass them to the view.
*
* @param model
* @return
*/
@RequestMapping("/index")
public ModelAndView thymeleafView(Map<String, Object> model) {
model.put("number", 1234);
model.put("message", "Hello from Spring MVC");
return new ModelAndView("thymeleaf/index");
}
}
@@ -0,0 +1,20 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.DependsOn;
@DependsOn
public class Bike implements Vehicle {
private String color;
@Required
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Biker {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
@Autowired
public Biker(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}
@Autowired
public void setVehicle(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
@DependsOn("engine")
public class Car implements Vehicle {
@Autowired
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
public Engine getEngine() {
return engine;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.annotations;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@Lazy
public class CarMechanic {
}
@@ -0,0 +1,7 @@
package com.baeldung.annotations;
import org.springframework.stereotype.Component;
@Component
public class CarUtility {
}
@@ -0,0 +1,8 @@
package com.baeldung.annotations;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public class CustomException extends RuntimeException {
}
@@ -0,0 +1,32 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Driver {
@Autowired
private Vehicle vehicle;
@Autowired
public Driver(Vehicle vehicle) {
this.vehicle = vehicle;
}
@Autowired
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Vehicle getVehicle() {
return vehicle;
}
@Scheduled(fixedRate = 10000)
@Scheduled(cron = "0 * * * * MON-FRI")
public void checkVehicle() {
}
}
@@ -0,0 +1,26 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Value;
public class Engine {
@Value("8")
private int cylinderCount;
@Value("${engine.fuelType}")
private String fuelType;
public Engine() {
this(8);
}
public Engine(@Value("8") int cylinderCount) {
this.cylinderCount = cylinderCount;
}
@Value("8")
public void setCylinderCount(int cylinderCount) {
this.cylinderCount = cylinderCount;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.annotations;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
@Aspect
@Component
public class PerformanceAspect {
private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
@Pointcut("within(@org.springframework.stereotype.Repository *)")
public void repositoryClassMethods() {
}
@Around("repositoryClassMethods()")
public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
Object retval = pjp.proceed();
long end = System.nanoTime();
String methodName = pjp.getSignature().getName();
logger.info("Execution of " + methodName + " took " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
return retval;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.annotations;
public interface Vehicle {
}
@@ -0,0 +1,66 @@
package com.baeldung.annotations;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
public class VehicleController {
@CrossOrigin
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
@RequestMapping("/home")
public String home() {
return "home";
}
@PostMapping("/save")
public void saveVehicle(@RequestBody Vehicle vehicle) {
}
@RequestMapping("/{id}")
public Vehicle getVehicle(@PathVariable("id") long id) {
return null;
}
@RequestMapping
public Vehicle getVehicleByParam(@RequestParam("id") long id) {
return null;
}
@RequestMapping("/buy")
public Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
return null;
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void onIllegalArgumentException(IllegalArgumentException exception) {
}
@PostMapping("/assemble")
public void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicle) {
}
@ModelAttribute("vehicle")
public Vehicle getVehicle() {
return null;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.annotations;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class VehicleFactoryApplication {
public static void main(String[] args) {
SpringApplication.run(VehicleFactoryApplication.class, args);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.annotations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
@ImportResource("classpath:/annotations.xml")
@PropertySource("classpath:/annotations.properties")
@Lazy
@EnableAutoConfiguration
@EnableAsync
@EnableScheduling
public class VehicleFactoryConfig {
@Bean
@Lazy(false)
public Engine engine() {
return new Engine();
}
}
@@ -0,0 +1,8 @@
package com.baeldung.annotations;
import org.springframework.stereotype.Repository;
@Repository
public class VehicleRepository {
}
@@ -0,0 +1,8 @@
package com.baeldung.annotations;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class VehicleRestController {
}
@@ -0,0 +1,13 @@
package com.baeldung.annotations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class VehicleService {
@Async
public void repairCar() {
}
}
@@ -0,0 +1,12 @@
package com.baeldung.nosuchbeandefinitionexception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanA {
@Autowired
BeanB dependency;
}
@@ -0,0 +1,5 @@
package com.baeldung.nosuchbeandefinitionexception;
public class BeanB {
}
@@ -0,0 +1,12 @@
package com.baeldung.nosuchbeandefinitionexception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NoSuchBeanDefinitionDemoApp {
public static void main(String[] args) {
SpringApplication.run(NoSuchBeanDefinitionDemoApp.class, args);
}
}
@@ -0,0 +1,62 @@
package com.baeldung.responseentity;
import java.io.IOException;
import java.time.Year;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/customResponse")
public class CustomResponseController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
@GetMapping("/age")
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK);
}
private int calculateAge(int yearOfBirth) {
return currentYear() - yearOfBirth;
}
private boolean isInFuture(int year) {
return currentYear() < year;
}
private int currentYear() {
return Year.now().getValue();
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
}
@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter()
.println("Hello World!");
}
}
@@ -0,0 +1,52 @@
package com.baeldung.responseentity;
import java.time.Year;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/customResponseWithBuilder")
public class CustomResponseWithBuilderController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World!");
}
@GetMapping("/age")
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return ResponseEntity.badRequest()
.body("Year of birth cannot be in the future");
}
return ResponseEntity.status(HttpStatus.OK)
.body("Your age is " + calculateAge(yearOfBirth));
}
private int calculateAge(int yearOfBirth) {
return currentYear() - yearOfBirth;
}
private boolean isInFuture(int year) {
return currentYear() < year;
}
private int currentYear() {
return Year.now()
.getValue();
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set");
}
}
@@ -0,0 +1,23 @@
package com.baeldung.rss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot launcher for an application which exposes an RSS Feed.
*
* @author Donato Rimenti
*
*/
@SpringBootApplication
public class RssFeedApplication {
/**
* Launches a Spring Boot application which exposes an RSS Feed.
*
* @param args null
*/
public static void main(final String[] args) {
SpringApplication.run(RssFeedApplication.class, args);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.rss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;
/**
* REST Controller which returns an RSS Feed created by {@link RssFeedView}.
*
* @author Donato Rimenti
*
*/
@RestController
public class RssFeedController {
/**
* View used by this controller.
*/
@Autowired
private RssFeedView view;
/**
* Returns an RSS Feed created by {@link #view}.
*
* @return an RSS Feed
*/
@GetMapping("/rss")
public View getFeed() {
return view;
}
}
@@ -0,0 +1,98 @@
package com.baeldung.rss;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Item;
/**
* View for a RSS feed.
*
* @author Donato Rimenti
*/
@Component
public class RssFeedView extends AbstractRssFeedView {
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractFeedView#
* buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed,
* javax.servlet.http.HttpServletRequest)
*/
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
feed.setTitle("Baeldung RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.baeldung.com");
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
// Builds the single entries.
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("donatohan.rimenti@gmail.com");
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
Item entryTwo = new Item();
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
entryTwo.setAuthor("donatohan.rimenti@gmail.com");
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
Item entryThree = new Item();
entryThree.setTitle("Flyweight Pattern in Java");
entryThree.setAuthor("donatohan.rimenti@gmail.com");
entryThree.setLink("http://www.baeldung.com/java-flyweight");
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
Item entryFour = new Item();
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
entryFour.setAuthor("donatohan.rimenti@gmail.com");
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z")));
Item entryFive = new Item();
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
entryFive.setAuthor("donatohan.rimenti@gmail.com");
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item();
entrySix.setTitle("Double-Checked Locking with Singleton");
entrySix.setAuthor("donatohan.rimenti@gmail.com");
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
Item entrySeven = new Item();
entrySeven.setTitle("Introduction to Dagger 2");
entrySeven.setAuthor("donatohan.rimenti@gmail.com");
entrySeven.setLink("http://www.baeldung.com/dagger-2");
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
// Creates the feed.
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class ScheduleJobsByProfile {
private final static Logger LOG = LoggerFactory.getLogger(ScheduleJobsByProfile.class);
@Profile("prod")
@Bean
public ScheduledJob scheduledJob()
{
return new ScheduledJob("@Profile");
}
}
@@ -0,0 +1,21 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
public class ScheduledJob {
private String source;
public ScheduledJob(String source) {
this.source = source;
}
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJob.class);
@Scheduled(fixedDelay = 60000)
public void cleanTempDir() {
LOG.info("Cleaning temp directory via {}", source);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithBoolean {
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJobsWithBoolean.class);
@Value("${jobs.enabled:true}")
private boolean isEnabled;
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(fixedDelay = 60000)
public void cleanTempDirectory() {
if(isEnabled) {
LOG.info("Cleaning temp directory via boolean flag");
}
}
}
@@ -0,0 +1,20 @@
package com.baeldung.scheduling;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ScheduledJobsWithConditional
{
/**
* This uses @ConditionalOnProperty to conditionally create a bean, which itself
* is a scheduled job.
* @return ScheduledJob
*/
@Bean
@ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true")
public ScheduledJob runMyCronTask() {
return new ScheduledJob("@ConditionalOnProperty");
}
}
@@ -0,0 +1,23 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithExpression
{
private final static Logger LOG =
LoggerFactory.getLogger(ScheduledJobsWithExpression.class);
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(cron = "${jobs.cronSchedule:-}")
public void cleanTempDirectory() {
LOG.info("Cleaning temp directory via placeholder");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.scheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}
@@ -0,0 +1,118 @@
package com.baeldung.springbootannotations;
import java.util.Arrays;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.util.ClassUtils;
@Configuration
@ConditionalOnClass(DataSource.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@PropertySource("classpath:mysql.properties")
public class MySQLAutoconfiguration {
@Autowired
private Environment env;
@Bean
@ConditionalOnProperty(name = "usemysql", havingValue = "local")
@ConditionalOnMissingBean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=UTC");
dataSource.setUsername("mysqluser");
dataSource.setPassword("mysqlpass");
return dataSource;
}
@Bean(name = "dataSource")
@ConditionalOnProperty(name = "usemysql", havingValue = "custom")
@ConditionalOnMissingBean
public DataSource dataSource2() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(env.getProperty("mysql.url"));
dataSource.setUsername(env.getProperty("mysql.user") != null ? env.getProperty("mysql.user") : "");
dataSource.setPassword(env.getProperty("mysql.pass") != null ? env.getProperty("mysql.pass") : "");
return dataSource;
}
@Bean
@ConditionalOnBean(name = "dataSource")
@ConditionalOnMissingBean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.autoconfiguration.example");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
if (additionalProperties() != null) {
em.setJpaProperties(additionalProperties());
}
return em;
}
@Bean
@ConditionalOnMissingBean(type = "JpaTransactionManager")
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
@Conditional(HibernateCondition.class)
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");
return hibernateProperties;
}
static class HibernateCondition extends SpringBootCondition {
private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" };
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.springbootmvc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggingController {
Logger logger = LoggerFactory.getLogger(LoggingController.class);
@GetMapping("/")
public String index() {
logger.trace("A TRACE Message");
logger.debug("A DEBUG Message");
logger.info("An INFO Message");
logger.warn("A WARN Message");
logger.error("An ERROR Message");
return "Howdy! Check out the Logs to see the output...";
}
}
@@ -0,0 +1,20 @@
package com.baeldung.springbootmvc;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.springbootmvc.model.LoginForm;
@RestController
@RequestMapping("/")
public class LoginController {
@PostMapping("loginform")
public String processLogin(@Valid LoginForm form) {
return "Success";
}
}
@@ -0,0 +1,12 @@
package com.baeldung.springbootmvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMvcApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMvcApplication.class, args);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.springbootmvc.config;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
public class CustomMessageSourceConfiguration {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.springbootmvc.config;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
@Configuration
public class FaviconConfiguration {
@Bean
public SimpleUrlHandlerMapping myFaviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("/favicon.ico", faviconRequestHandler()));
return mapping;
}
@Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images");
List<Resource> locations = Arrays.asList(classPathResource);
requestHandler.setLocations(locations);
return requestHandler;
}
// @Controller
static class FaviconController {
@RequestMapping(value = "favicon.ico", method = RequestMethod.GET)
@ResponseBody
void favicon() {
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.springbootmvc.jsfapplication;
import javax.faces.webapp.FacesServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.baeldung.springbootmvc.jsfapplication.controller.JsfController;
import com.baeldung.springbootmvc.jsfapplication.model.TodoDao;
import com.baeldung.springbootmvc.jsfapplication.service.TodoService;
@SpringBootApplication
@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class })
public class JsfApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(JsfApplication.class, args);
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf");
return servletRegistrationBean;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.springbootmvc.jsfapplication.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope(value = "session")
@Component(value = "jsfController")
public class JsfController {
public String loadTodoPage() {
checkPermission();
return "/todo.xhtml";
}
private void checkPermission() {
// Details omitted
}
}
@@ -0,0 +1,17 @@
package com.baeldung.springbootmvc.jsfapplication.model;
import java.util.Collection;
import java.util.Optional;
public interface Dao<T> {
Optional<T> get(int id);
Collection<T> getAll();
int save(T t);
void update(T t);
void delete(T t);
}
@@ -0,0 +1,32 @@
package com.baeldung.springbootmvc.jsfapplication.model;
public class Todo {
private int id;
private String message;
private int priority;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.springbootmvc.jsfapplication.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
@Component
public class TodoDao implements Dao<Todo> {
private List<Todo> todoList = new ArrayList<>();
@Override
public Optional<Todo> get(int id) {
return Optional.ofNullable(todoList.get(id));
}
@Override
public Collection<Todo> getAll() {
return todoList.stream()
.filter(Objects::nonNull)
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
@Override
public int save(Todo todo) {
todoList.add(todo);
int index = todoList.size() - 1;
todo.setId(index);
return index;
}
@Override
public void update(Todo todo) {
todoList.set(todo.getId(), todo);
}
@Override
public void delete(Todo todo) {
todoList.set(todo.getId(), null);
}
}
@@ -0,0 +1,50 @@
package com.baeldung.springbootmvc.jsfapplication.service;
import java.util.Collection;
import java.util.Comparator;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.baeldung.springbootmvc.jsfapplication.model.Dao;
import com.baeldung.springbootmvc.jsfapplication.model.Todo;
@Scope(value = "session")
@Component(value = "todoService")
public class TodoService {
@Autowired
private Dao<Todo> todoDao;
private Todo todo = new Todo();
public void save() {
todoDao.save(todo);
todo = new Todo();
}
public Collection<Todo> getAllTodo() {
return todoDao.getAll();
}
public Collection<Todo> getAllTodoSortedByPriority() {
return todoDao.getAll()
.stream()
.sorted(Comparator.comparingInt(Todo::getId))
.collect(Collectors.toList());
}
public int saveTodo(Todo todo) {
validate(todo);
return todoDao.save(todo);
}
private void validate(Todo todo) {
// Details omitted
}
public Todo getTodo() {
return todo;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.springbootmvc.model;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class LoginForm {
@NotEmpty(message = "{email.notempty}")
@Email
private String email;
@NotNull
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.swagger2boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,79 @@
package com.baeldung.swagger2boot.configuration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.util.Collections;
@Configuration
@EnableSwagger2WebMvc
@Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class})
public class SpringFoxConfig {
private ApiInfo apiInfo() {
return new ApiInfo(
"My REST API",
"Some custom description of API.",
"API TOS",
"Terms of service",
new Contact("John Doe", "www.example.com", "myeaddress@company.com"),
"License of API",
"API license URL",
Collections.emptyList());
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
/**
* SwaggerUI information
*/
@Bean
UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.EXAMPLE)
.displayRequestDuration(false)
.docExpansion(DocExpansion.NONE)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
.validatorUrl(null)
.build();
}
@Bean
public EmailAnnotationPlugin emailPlugin() {
return new EmailAnnotationPlugin();
}
}
@@ -0,0 +1,14 @@
package com.baeldung.swagger2boot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RegularRestController {
@GetMapping("home")
public String getSession() {
return "Hello";
}
}
@@ -0,0 +1,58 @@
package com.baeldung.swagger2boot.model;
import javax.persistence.Id;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.persistence.Entity;
@Entity
public class User {
@Id
private Long id;
@NotNull(message = "First Name cannot be null")
private String firstName;
@Min(value = 15, message = "Age should not be less than 15")
@Max(value = 65, message = "Age should not be greater than 65")
private int age;
@Email(regexp=".@.\\..*", message = "Email should be valid")
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.swagger2boot.plugin;
import static springfox.bean.validators.plugins.Validators.annotationFromBean;
import java.util.Optional;
import javax.validation.constraints.Email;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.bean.validators.plugins.Validators;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
@Component
@Order(Validators.BEAN_VALIDATOR_PLUGIN_ORDER)
public class EmailAnnotationPlugin implements ModelPropertyBuilderPlugin {
@Override
public boolean supports(DocumentationType delimiter) {
return true;
}
/**
* read Email annotation
*/
@Override
public void apply(ModelPropertyContext context) {
Optional<Email> email = annotationFromBean(context, Email.class);
if (email.isPresent()) {
context.getBuilder().pattern(email.get().regexp());
context.getBuilder().example("email@email.com");
}
}
}
@@ -0,0 +1,11 @@
package com.baeldung.swagger2boot.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.swagger2boot.model.User;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}