JAVA-117 Standardize spring-boot-modules/spring-boot
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package com.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);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.boot.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
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.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" })
|
||||
@PropertySource("classpath:persistence-generic-entity.properties")
|
||||
@EnableTransactionManagement
|
||||
public class H2JpaConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
|
||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||
dataSource.setUsername(env.getProperty("jdbc.user"));
|
||||
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" });
|
||||
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
|
||||
em.setJpaProperties(additionalProperties());
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.boot.config;
|
||||
|
||||
import com.baeldung.boot.converter.StringToEmployeeConverter;
|
||||
import com.baeldung.boot.converter.StringToEnumConverterFactory;
|
||||
import com.baeldung.boot.converter.GenericBigDecimalConverter;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new StringToEmployeeConverter());
|
||||
registry.addConverterFactory(new StringToEnumConverterFactory());
|
||||
registry.addConverter(new GenericBigDecimalConverter());
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.boot.controller.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class HelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public HelloWorldServlet() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("HelloWorldServlet: GET METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("HelloWorldServlet: POST METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.boot.controller.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class SpringHelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public SpringHelloWorldServlet() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("SpringHelloWorldServlet: GET METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("SpringHelloWorldServlet: POST METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
import com.baeldung.toggle.Employee;
|
||||
|
||||
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]));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.converter.ConverterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class StringToEnumConverterFactory
|
||||
implements ConverterFactory<String, Enum> {
|
||||
|
||||
private static class StringToEnumConverter<T extends Enum>
|
||||
implements Converter<String, T> {
|
||||
|
||||
private Class<T> enumType;
|
||||
|
||||
public StringToEnumConverter(Class<T> enumType) {
|
||||
this.enumType = enumType;
|
||||
}
|
||||
|
||||
public T convert(String source) {
|
||||
return (T) Enum.valueOf(this.enumType, source.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Enum> Converter<String, T> getConverter(
|
||||
Class<T> targetType) {
|
||||
return new StringToEnumConverter(targetType);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.boot.converter.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.toggle.Employee;
|
||||
|
||||
@RestController
|
||||
public class StringToEmployeeConverterController {
|
||||
|
||||
@GetMapping("/string-to-employee")
|
||||
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
|
||||
return ResponseEntity.ok(employee);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public enum Modes {
|
||||
|
||||
ALPHA, BETA;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.common.error;
|
||||
|
||||
import org.springframework.boot.web.servlet.error.ErrorController;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
public class MyCustomErrorController implements ErrorController {
|
||||
|
||||
private static final String PATH = "/error";
|
||||
|
||||
public MyCustomErrorController() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
@GetMapping(value = PATH)
|
||||
public String error() {
|
||||
return "Error haven";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getErrorPath() {
|
||||
return PATH;
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.common.error;
|
||||
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
|
||||
public class SpringHelloServletRegistrationBean extends ServletRegistrationBean {
|
||||
|
||||
public SpringHelloServletRegistrationBean() {
|
||||
}
|
||||
|
||||
public SpringHelloServletRegistrationBean(Servlet servlet, String... urlMappings) {
|
||||
super(servlet, urlMappings);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.common.error.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ErrorController {
|
||||
|
||||
public ErrorController() {
|
||||
}
|
||||
|
||||
@GetMapping("/400")
|
||||
String error400() {
|
||||
return "Error Code: 400 occured.";
|
||||
}
|
||||
|
||||
@GetMapping("/errorHaven")
|
||||
String errorHeaven() {
|
||||
return "You have reached the haven of errors!!!";
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.common.properties;
|
||||
|
||||
import org.springframework.boot.web.server.ErrorPage;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
|
||||
|
||||
public MyServletContainerCustomizationBean() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableServletWebServerFactory container) {
|
||||
container.setPort(8084);
|
||||
container.setContextPath("/springbootapp");
|
||||
|
||||
container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
|
||||
container.addErrorPages(new ErrorPage("/errorHaven"));
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.common.resources;
|
||||
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
public ExecutorServiceExitCodeGenerator(ExecutorService executorService) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getExitCode() {
|
||||
try {
|
||||
if (!Objects.isNull(executorService)) {
|
||||
executorService.shutdownNow();
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (SecurityException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.demo;
|
||||
|
||||
import com.baeldung.graphql.GraphqlConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootApplication
|
||||
@Import(GraphqlConfiguration.class)
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "demo");
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.demo.boottest;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Date;
|
||||
|
||||
@Entity
|
||||
@Table(name = "person")
|
||||
public class Employee {
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Size(min = 3, max = 20)
|
||||
private String name;
|
||||
|
||||
private Date birthday;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
|
||||
|
||||
public Employee findByName(String name);
|
||||
|
||||
public List<Employee> findAll();
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class EmployeeRestController {
|
||||
|
||||
@Autowired
|
||||
private EmployeeService employeeService;
|
||||
|
||||
@PostMapping("/employees")
|
||||
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
|
||||
HttpStatus status = HttpStatus.CREATED;
|
||||
Employee saved = employeeService.save(employee);
|
||||
return new ResponseEntity<>(saved, status);
|
||||
}
|
||||
|
||||
@GetMapping("/employees")
|
||||
public List<Employee> getAllEmployees() {
|
||||
return employeeService.getAllEmployees();
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface EmployeeService {
|
||||
|
||||
public Employee getEmployeeById(Long id);
|
||||
|
||||
public Employee getEmployeeByName(String name);
|
||||
|
||||
public List<Employee> getAllEmployees();
|
||||
|
||||
public boolean exists(String email);
|
||||
|
||||
public Employee save(Employee employee);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class EmployeeServiceImpl implements EmployeeService {
|
||||
|
||||
@Autowired
|
||||
private EmployeeRepository employeeRepository;
|
||||
|
||||
@Override
|
||||
public Employee getEmployeeById(Long id) {
|
||||
return employeeRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Employee getEmployeeByName(String name) {
|
||||
return employeeRepository.findByName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(String name) {
|
||||
if (employeeRepository.findByName(name) != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Employee save(Employee employee) {
|
||||
return employeeRepository.save(employee);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Employee> getAllEmployees() {
|
||||
return employeeRepository.findAll();
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.demo.components;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
import com.baeldung.demo.repository.FooRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class FooService {
|
||||
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
public Foo getFooWithId(Integer id) throws Exception {
|
||||
return fooRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Foo getFooWithName(String name) {
|
||||
return fooRepository.findByName(name);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.demo.exceptions;
|
||||
|
||||
public class CommonException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 3080004140659213332L;
|
||||
|
||||
public CommonException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.demo.exceptions;
|
||||
|
||||
public class FooNotFoundException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 9042200028456133589L;
|
||||
|
||||
public FooNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.demo.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
}
|
||||
|
||||
public Foo(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Foo(Integer id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.demo.repository;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface FooRepository extends JpaRepository<Foo, Integer> {
|
||||
public Foo findByName(String name);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.demo.service;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
import com.baeldung.demo.components.FooService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public Foo getFooWithId(@PathVariable Integer id) throws Exception {
|
||||
return fooService.getFooWithId(id);
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public Foo getFooWithName(@RequestParam String name) throws Exception {
|
||||
return fooService.getFooWithName(name);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.endpoints.info;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.info.Info;
|
||||
import org.springframework.boot.actuate.info.InfoContributor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class TotalUsersInfoContributor implements InfoContributor {
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public void contribute(Info.Builder builder) {
|
||||
Map<String, Integer> userDetails = new HashMap<>();
|
||||
userDetails.put("active", userRepository.countByStatus(1));
|
||||
userDetails.put("inactive", userRepository.countByStatus(0));
|
||||
|
||||
builder.withDetail("users", userDetails);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.main;
|
||||
|
||||
import com.baeldung.boot.controller.servlet.HelloWorldServlet;
|
||||
import com.baeldung.boot.controller.servlet.SpringHelloWorldServlet;
|
||||
import com.baeldung.common.error.SpringHelloServletRegistrationBean;
|
||||
import com.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan({ "org.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" })
|
||||
public class SpringBootApplication {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@GetMapping("/")
|
||||
String home() {
|
||||
return "TADA!!! You are in Spring Boot Actuator test application.";
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(SpringBootApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ExecutorService executorService() {
|
||||
return Executors.newFixedThreadPool(10);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HelloWorldServlet helloWorldServlet() {
|
||||
return new HelloWorldServlet();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringHelloServletRegistrationBean servletRegistrationBean() {
|
||||
SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*");
|
||||
bean.setLoadOnStartup(1);
|
||||
bean.addInitParameter("message", "SpringHelloWorldServlet special message");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Autowired
|
||||
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {
|
||||
return new ExecutorServiceExitCodeGenerator(executorService);
|
||||
}
|
||||
|
||||
public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) {
|
||||
SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Integer status;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, Integer status) {
|
||||
this.name = name;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.repository;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Repository("userRepository")
|
||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
int countByStatus(int status);
|
||||
|
||||
Optional<User> findOneByName(String name);
|
||||
|
||||
@Async
|
||||
CompletableFuture<User> findOneByStatus(Integer status);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||
Collection<User> findAllActiveUsers();
|
||||
|
||||
@Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)
|
||||
Collection<User> findAllActiveUsersNative();
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1")
|
||||
User findUserByStatus(Integer status);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
|
||||
User findUserByStatusNative(Integer status);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
|
||||
User findUserByStatusAndName(Integer status, String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
|
||||
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like ?1%")
|
||||
User findUserByNameLike(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like :name%")
|
||||
User findUserByNameLikeNamedParam(@Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
|
||||
User findUserByNameLikeNative(String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u")
|
||||
List<User> findAllUsers(Sort sort);
|
||||
|
||||
@Query(value = "SELECT u FROM User u ORDER BY id")
|
||||
Page<User> findAllUsersWithPagination(Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
||||
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
@Query("update User u set u.status = :status where u.name = :name")
|
||||
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNative(Integer status, String name);
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.session.exception;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "exception");
|
||||
System.setProperty("spring.profiles.active", "exception");
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.session.exception.repository;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
|
||||
public interface FooRepository {
|
||||
|
||||
void save(Foo foo);
|
||||
|
||||
Foo get(Integer id);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.session.exception.repository;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import com.baeldung.demo.model.Foo;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Profile("exception")
|
||||
@Repository
|
||||
public class FooRepositoryImpl implements FooRepository {
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@Override
|
||||
public void save(Foo foo) {
|
||||
emf.unwrap(SessionFactory.class).getCurrentSession().saveOrUpdate(foo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Foo get(Integer id) {
|
||||
return emf.unwrap(SessionFactory.class).getCurrentSession().get(Foo.class, id);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.startup;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AppStartupRunner implements ApplicationRunner {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AppStartupRunner.class);
|
||||
public static int counter;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
LOG.info("Application started with option names : {}", args.getOptionNames());
|
||||
LOG.info("Increment counter");
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.startup;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CommandLineAppStartupRunner implements CommandLineRunner {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
|
||||
public static int counter;
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
LOG.info("Increment counter");
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user