Merge branch 'master' into hemantvsn_SpringBootNonWebApp_30May18
This commit is contained in:
+1
-3
@@ -4,8 +4,6 @@ import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
/**
|
||||
* using the following annotations are equivalent:
|
||||
* <ul><li>
|
||||
@@ -16,7 +14,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
|
||||
* </li></ul>
|
||||
*/
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootAnnotatedApp {
|
||||
|
||||
|
||||
+1
-3
@@ -3,9 +3,7 @@ package com.baeldung.annotation.servletcomponentscan;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootPlainApp {
|
||||
|
||||
|
||||
+1
-2
@@ -9,8 +9,7 @@ public class AttrListener implements ServletContextListener {
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent servletContextEvent) {
|
||||
servletContextEvent.getServletContext()
|
||||
.setAttribute("servlet-context-attr", "test");
|
||||
servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test");
|
||||
System.out.println("context init");
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -16,8 +16,7 @@ public class EchoServlet extends HttpServlet {
|
||||
@Override
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
Path path = File.createTempFile("echo", "tmp")
|
||||
.toPath();
|
||||
Path path = File.createTempFile("echo", "tmp").toPath();
|
||||
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.copy(path, response.getOutputStream());
|
||||
Files.delete(path);
|
||||
|
||||
+1
-2
@@ -18,8 +18,7 @@ public class HelloFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
servletResponse.getOutputStream()
|
||||
.print(filterConfig.getInitParameter("msg"));
|
||||
servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg"));
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
+1
-3
@@ -21,9 +21,7 @@ public class HelloServlet extends HttpServlet {
|
||||
@Override
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
response.getOutputStream()
|
||||
.write(servletConfig.getInitParameter("msg")
|
||||
.getBytes());
|
||||
response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
package com.baeldung.autoconfiguration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
|
||||
import org.springframework.boot.autoconfigure.condition.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
|
||||
import org.springframework.context.annotation.*;
|
||||
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;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
|
||||
@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");
|
||||
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))));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.autoconfiguration.example;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class AutoconfigurationApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(AutoconfigurationApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.autoconfiguration.example;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class MyUser {
|
||||
@Id
|
||||
private String email;
|
||||
|
||||
public MyUser() {
|
||||
}
|
||||
|
||||
public MyUser(String email) {
|
||||
super();
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.autoconfiguration.example;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<MyUser, String> {
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.bootcustomfilters;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Boot application
|
||||
* @author hemant
|
||||
*
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class SpringBootFiltersApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootFiltersApplication.class, args);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.bootcustomfilters.controller;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.bootcustomfilters.model.User;
|
||||
|
||||
/**
|
||||
* Rest controller for User
|
||||
* @author hemant
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/users")
|
||||
public class UserController {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
|
||||
|
||||
@GetMapping("")
|
||||
public List<User> getAllUsers() {
|
||||
LOG.info("Fetching all the users");
|
||||
return Arrays.asList(
|
||||
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"),
|
||||
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"),
|
||||
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"));
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.bootcustomfilters.filters;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* A servlet filter to log request and response
|
||||
* The logging implementation is pretty native and for demonstration only
|
||||
* @author hemant
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
@Order(2)
|
||||
public class RequestResponseLoggingFilter implements Filter {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);
|
||||
|
||||
@Override
|
||||
public void init(final FilterConfig filterConfig) throws ServletException {
|
||||
LOG.info("Initializing filter :{}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
LOG.info("Logging Request {} : {}", req.getMethod(), req.getRequestURI());
|
||||
chain.doFilter(request, response);
|
||||
LOG.info("Logging Response :{}", res.getContentType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
LOG.warn("Destructing filter :{}", this);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.bootcustomfilters.filters;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* A filter to create transaction before and commit it once request completes
|
||||
* The current implemenatation is just for demo
|
||||
* @author hemant
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
@Order(1)
|
||||
public class TransactionFilter implements Filter {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(TransactionFilter.class);
|
||||
|
||||
@Override
|
||||
public void init(final FilterConfig filterConfig) throws ServletException {
|
||||
LOG.info("Initializing filter :{}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
LOG.info("Starting Transaction for req :{}", req.getRequestURI());
|
||||
chain.doFilter(request, response);
|
||||
LOG.info("Committing Transaction for req :{}", req.getRequestURI());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
LOG.warn("Destructing filter :{}", this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.bootcustomfilters.model;
|
||||
|
||||
/**
|
||||
* User model
|
||||
* @author hemant
|
||||
*
|
||||
*/
|
||||
public class User {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(String id, String name, String email) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -4,7 +4,7 @@ import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import com.baeldung.displayallbeans.service.FooService;
|
||||
|
||||
@@ -13,7 +13,7 @@ public class FooController {
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
@RequestMapping(value = "/displayallbeans")
|
||||
@GetMapping(value = "/displayallbeans")
|
||||
public String getHeaderAndBody(Map<String, Object> model) {
|
||||
model.put("header", fooService.getHeader());
|
||||
model.put("message", fooService.getBody());
|
||||
|
||||
@@ -2,7 +2,9 @@ package com.baeldung.dynamicvalidation;
|
||||
|
||||
import com.baeldung.dynamicvalidation.dao.ContactInfoExpressionRepository;
|
||||
import com.baeldung.dynamicvalidation.model.ContactInfoExpression;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.thymeleaf.util.StringUtils;
|
||||
@@ -13,7 +15,7 @@ import java.util.regex.Pattern;
|
||||
|
||||
public class ContactInfoValidator implements ConstraintValidator<ContactInfo, String> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ContactInfoValidator.class);
|
||||
private static final Logger LOG = LogManager.getLogger(ContactInfoValidator.class);
|
||||
|
||||
@Autowired
|
||||
private ContactInfoExpressionRepository expressionRepository;
|
||||
@@ -28,9 +30,7 @@ public class ContactInfoValidator implements ConstraintValidator<ContactInfo, St
|
||||
if (StringUtils.isEmptyOrWhitespace(expressionType)) {
|
||||
LOG.error("Contact info type missing!");
|
||||
} else {
|
||||
pattern = expressionRepository.findOne(expressionType)
|
||||
.map(ContactInfoExpression::getPattern)
|
||||
.orElse("");
|
||||
pattern = expressionRepository.findOne(expressionType).map(ContactInfoExpression::getPattern).orElse("");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class DynamicValidationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
+1
-4
@@ -18,10 +18,7 @@ public class PersistenceConfig {
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
|
||||
.addScript("schema-expressions.sql")
|
||||
.addScript("data-expressions.sql")
|
||||
.build();
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build();
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.errorhandling;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.errorhandling")
|
||||
public class ErrorHandlingApplication {
|
||||
|
||||
public static void main(String [] args) {
|
||||
System.setProperty("spring.profiles.active", "errorhandling");
|
||||
SpringApplication.run(ErrorHandlingApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.errorhandling.controllers;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
@Controller
|
||||
public class IndexController {
|
||||
|
||||
@GetMapping(value = {"/", ""})
|
||||
public String index() {
|
||||
return "index";
|
||||
}
|
||||
|
||||
@GetMapping(value = {"/server_error"})
|
||||
public String triggerServerError() {
|
||||
"ser".charAt(30);
|
||||
return "index";
|
||||
}
|
||||
|
||||
@PostMapping(value = {"/general_error"})
|
||||
public String triggerGeneralError() {
|
||||
return "index";
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.errorhandling.controllers;
|
||||
|
||||
import org.springframework.boot.web.servlet.error.ErrorController;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
public class MyErrorController implements ErrorController {
|
||||
|
||||
public MyErrorController() {}
|
||||
|
||||
@GetMapping(value = "/error")
|
||||
public String handleError(HttpServletRequest request) {
|
||||
|
||||
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
|
||||
|
||||
if (status != null) {
|
||||
|
||||
Integer statusCode = Integer.valueOf(status.toString());
|
||||
|
||||
if(statusCode == HttpStatus.NOT_FOUND.value()) {
|
||||
return "error-404";
|
||||
}
|
||||
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
|
||||
return "error-500";
|
||||
}
|
||||
}
|
||||
return "error";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getErrorPath() {
|
||||
return "/error";
|
||||
}
|
||||
|
||||
}
|
||||
+1
-3
@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class FailureAnalyzerApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
+2
-6
@@ -12,15 +12,11 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnaly
|
||||
}
|
||||
|
||||
private String getDescription(BeanNotOfRequiredTypeException ex) {
|
||||
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType()
|
||||
.getName(),
|
||||
ex.getActualType()
|
||||
.getName());
|
||||
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType().getName(), ex.getActualType().getName());
|
||||
}
|
||||
|
||||
private String getAction(BeanNotOfRequiredTypeException ex) {
|
||||
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType()
|
||||
.getName());
|
||||
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType().getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
|
||||
public class CommitIdApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CommitIdApplication.class, args);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.git;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -19,7 +19,7 @@ public class CommitInfoController {
|
||||
@Value("${git.commit.id}")
|
||||
private String commitId;
|
||||
|
||||
@RequestMapping("/commitId")
|
||||
@GetMapping("/commitId")
|
||||
public Map<String, String> getCommitId() {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("Commit message", commitMessage);
|
||||
|
||||
@@ -11,8 +11,6 @@ public class AuthorDao {
|
||||
}
|
||||
|
||||
public Optional<Author> getAuthor(String id) {
|
||||
return authors.stream()
|
||||
.filter(author -> id.equals(author.getId()))
|
||||
.findFirst();
|
||||
return authors.stream().filter(author -> id.equals(author.getId())).findFirst();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,7 @@ public class Mutation implements GraphQLMutationResolver {
|
||||
|
||||
public Post writePost(String title, String text, String category, String author) {
|
||||
Post post = new Post();
|
||||
post.setId(UUID.randomUUID()
|
||||
.toString());
|
||||
post.setId(UUID.randomUUID().toString());
|
||||
post.setTitle(title);
|
||||
post.setText(text);
|
||||
post.setCategory(category);
|
||||
|
||||
@@ -11,16 +11,11 @@ public class PostDao {
|
||||
}
|
||||
|
||||
public List<Post> getRecentPosts(int count, int offset) {
|
||||
return posts.stream()
|
||||
.skip(offset)
|
||||
.limit(count)
|
||||
.collect(Collectors.toList());
|
||||
return posts.stream().skip(offset).limit(count).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Post> getAuthorPosts(String author) {
|
||||
return posts.stream()
|
||||
.filter(post -> author.equals(post.getAuthorId()))
|
||||
.collect(Collectors.toList());
|
||||
return posts.stream().filter(post -> author.equals(post.getAuthorId())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void savePost(Post post) {
|
||||
|
||||
+1
-3
@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class InternationalizationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -7,13 +7,13 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = "com.baeldung.internationalization.config")
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
@@ -31,6 +31,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,7 @@ package com.baeldung.intro;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class, args);
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
package com.baeldung.intro.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class HomeController {
|
||||
|
||||
@RequestMapping("/")
|
||||
@GetMapping("/")
|
||||
public String root() {
|
||||
return "Index Page";
|
||||
}
|
||||
|
||||
@RequestMapping("/local")
|
||||
@GetMapping("/local")
|
||||
public String local() {
|
||||
return "/local";
|
||||
}
|
||||
|
||||
@@ -15,18 +15,17 @@ public class QueryController {
|
||||
private static int REQUEST_COUNTER = 0;
|
||||
|
||||
@GetMapping("/reqcount")
|
||||
public int getReqCount(){
|
||||
public int getReqCount() {
|
||||
return REQUEST_COUNTER;
|
||||
}
|
||||
|
||||
@GetMapping("/{code}")
|
||||
public String getStockPrice(@PathVariable String code){
|
||||
public String getStockPrice(@PathVariable String code) {
|
||||
REQUEST_COUNTER++;
|
||||
if("BTC".equalsIgnoreCase(code))
|
||||
if ("BTC".equalsIgnoreCase(code))
|
||||
return "10000";
|
||||
else return "N/A";
|
||||
else
|
||||
return "N/A";
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
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.RequestMethod;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/rss", produces = "application/*")
|
||||
public class ArticleRssController {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
@GetMapping
|
||||
public String articleFeed() {
|
||||
return "articleFeedView";
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomContainer implements EmbeddedServletContainerCustomizer {
|
||||
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableEmbeddedServletContainer container) {
|
||||
container.setPort(8080);
|
||||
container.setContextPath("");
|
||||
public void customize(ConfigurableServletWebServerFactory factory) {
|
||||
factory.setContextPath("");
|
||||
factory.setPort(8080);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.rss")
|
||||
public class RssApp {
|
||||
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.servletinitializer;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WarInitializerApplication extends SpringBootServletInitializer {
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
|
||||
return builder.sources(WarInitializerApplication.class);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication sa = new SpringApplication(WarInitializerApplication.class);
|
||||
sa.setLogStartupInfo(false);
|
||||
sa.run(args);
|
||||
}
|
||||
|
||||
@RestController
|
||||
public static class WarInitializerController {
|
||||
|
||||
@GetMapping("/")
|
||||
public String handler(Model model) {
|
||||
model.addAttribute("date", LocalDateTime.now());
|
||||
return "WarInitializerApplication is up and running!";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,9 @@ package com.baeldung.servlets;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class ApplicationMain extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
package com.baeldung.servlets.configuration;
|
||||
|
||||
import org.springframework.boot.web.support.ErrorPageFilter;
|
||||
import org.springframework.boot.web.servlet.support.ErrorPageFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
@Configuration
|
||||
public class WebMvcConfigure extends WebMvcConfigurerAdapter {
|
||||
public class WebMvcConfigure implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
public ViewResolver getViewResolver() {
|
||||
@@ -28,11 +28,7 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**")
|
||||
.addResourceLocations("/resources/")
|
||||
.setCachePeriod(3600)
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver());
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
+1
-2
@@ -13,7 +13,6 @@ public class AnnotationServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
request.getRequestDispatcher("/annotationservlet.jsp")
|
||||
.forward(request, response);
|
||||
request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration;
|
||||
public class SpringRegistrationBeanServlet {
|
||||
|
||||
@Bean
|
||||
public ServletRegistrationBean genericCustomServlet() {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*");
|
||||
public ServletRegistrationBean<GenericCustomServlet> genericCustomServlet() {
|
||||
ServletRegistrationBean<GenericCustomServlet> bean = new ServletRegistrationBean<>(new GenericCustomServlet(), "/springregistrationbeanservlet/*");
|
||||
bean.setLoadOnStartup(1);
|
||||
return bean;
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.servlets.servlets.springboot.embedded;
|
||||
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
|
||||
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration;
|
||||
public class EmbeddedTomcatExample {
|
||||
|
||||
@Bean
|
||||
public EmbeddedServletContainerFactory servletContainer() {
|
||||
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
|
||||
public ConfigurableServletWebServerFactory servletContainer() {
|
||||
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
|
||||
return tomcat;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.baeldung.toggle;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
@@ -10,16 +11,14 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class FeaturesAspect {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FeaturesAspect.class);
|
||||
private static final Logger LOG = LogManager.getLogger(FeaturesAspect.class);
|
||||
|
||||
@Around(value = "@within(featureAssociation) || @annotation(featureAssociation)")
|
||||
public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable {
|
||||
if (featureAssociation.value()
|
||||
.isActive()) {
|
||||
if (featureAssociation.value().isActive()) {
|
||||
return joinPoint.proceed();
|
||||
} else {
|
||||
LOG.info("Feature " + featureAssociation.value()
|
||||
.name() + " is not enabled!");
|
||||
LOG.info("Feature " + featureAssociation.value().name() + " is not enabled!");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,7 @@ public enum MyFeatures implements Feature {
|
||||
EMPLOYEE_MANAGEMENT_FEATURE;
|
||||
|
||||
public boolean isActive() {
|
||||
return FeatureContext.getFeatureManager()
|
||||
.isActive(this);
|
||||
return FeatureContext.getFeatureManager().isActive(this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ public class SalaryService {
|
||||
|
||||
@FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE)
|
||||
public void increaseSalary(long id) {
|
||||
Employee employee = employeeRepository.findOne(id);
|
||||
Employee employee = employeeRepository.findById(id).orElse(null);
|
||||
employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1);
|
||||
employeeRepository.save(employee);
|
||||
}
|
||||
|
||||
@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class ToggleApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -6,9 +6,7 @@ import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.utils")
|
||||
public class UtilsApplication {
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.webjar;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class TestController {
|
||||
|
||||
@RequestMapping(value = "/")
|
||||
public String welcome(Model model) {
|
||||
return "index";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.webjar;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class WebjarsdemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebjarsdemoApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest","org.baeldung.repository" })
|
||||
@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" })
|
||||
@PropertySource("classpath:persistence-generic-entity.properties")
|
||||
@EnableTransactionManagement
|
||||
public class H2JpaConfig {
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package org.baeldung.boot.config;
|
||||
|
||||
import org.baeldung.boot.converter.GenericBigDecimalConverter;
|
||||
import org.baeldung.boot.converter.StringToEmployeeConverter;
|
||||
import org.baeldung.boot.converter.StringToEnumConverterFactory;
|
||||
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.WebMvcConfigurerAdapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new HeaderVersionArgumentResolver());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new StringToEmployeeConverter());
|
||||
registry.addConverterFactory(new StringToEnumConverterFactory());
|
||||
registry.addConverter(new GenericBigDecimalConverter());
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
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"));
|
||||
}
|
||||
|
||||
@RequestMapping("/entity/all")
|
||||
public List<GenericEntity> findAll() {
|
||||
return entityList;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/entity", method = RequestMethod.POST)
|
||||
public GenericEntity addEntity(GenericEntity entity) {
|
||||
entityList.add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@RequestMapping("/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);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package org.baeldung.boot.converter;
|
||||
|
||||
|
||||
import com.baeldung.toggle.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]));
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package org.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(final Class<T> targetType) {
|
||||
return new StringToEnumConverter(targetType);
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package org.baeldung.boot.converter.controller;
|
||||
|
||||
import com.baeldung.toggle.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);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -36,8 +36,7 @@ public class UserCombinedSerializer {
|
||||
public static class UserJsonDeserializer extends JsonDeserializer<User> {
|
||||
@Override
|
||||
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
|
||||
TreeNode treeNode = jsonParser.getCodec()
|
||||
.readTree(jsonParser);
|
||||
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
|
||||
return new User(Color.web(favoriteColor.asText()));
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@ import java.io.IOException;
|
||||
public class UserJsonDeserializer extends JsonDeserializer<User> {
|
||||
@Override
|
||||
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
|
||||
TreeNode treeNode = jsonParser.getCodec()
|
||||
.readTree(jsonParser);
|
||||
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
|
||||
return new User(Color.web(favoriteColor.asText()));
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.baeldung.boot.monitor.jmx;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.codahale.metrics.JmxReporter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
|
||||
@Configuration
|
||||
public class MonitoringConfig {
|
||||
@Autowired
|
||||
private MetricRegistry registry;
|
||||
|
||||
@Bean
|
||||
public JmxReporter jmxReporter() {
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry)
|
||||
.build();
|
||||
reporter.start();
|
||||
return reporter;
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
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 {
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.baeldung.common.error;
|
||||
|
||||
import org.springframework.boot.autoconfigure.web.ErrorController;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.boot.web.servlet.error.ErrorController;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
public class MyCustomErrorController implements ErrorController {
|
||||
|
||||
@@ -11,7 +11,7 @@ public class MyCustomErrorController implements ErrorController {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
@RequestMapping(value = PATH)
|
||||
@GetMapping(value = PATH)
|
||||
public String error() {
|
||||
return "Error heaven";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package org.baeldung.common.error.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@@ -9,12 +9,12 @@ public class ErrorController {
|
||||
public ErrorController() {
|
||||
}
|
||||
|
||||
@RequestMapping("/400")
|
||||
@GetMapping("/400")
|
||||
String error400() {
|
||||
return "Error Code: 400 occured.";
|
||||
}
|
||||
|
||||
@RequestMapping("/errorHeaven")
|
||||
@GetMapping("/errorHeaven")
|
||||
String errorHeaven() {
|
||||
return "You have reached the heaven of errors!!!";
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,20 +1,20 @@
|
||||
package org.baeldung.common.properties;
|
||||
|
||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
|
||||
import org.springframework.boot.web.servlet.ErrorPage;
|
||||
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 EmbeddedServletContainerCustomizer {
|
||||
public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
|
||||
|
||||
public MyServletContainerCustomizationBean() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableEmbeddedServletContainer container) {
|
||||
public void customize(ConfigurableServletWebServerFactory container) {
|
||||
container.setPort(8084);
|
||||
container.setContextPath("/springbootapp");
|
||||
|
||||
|
||||
+8
-9
@@ -1,10 +1,10 @@
|
||||
package org.baeldung.common.resources;
|
||||
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
|
||||
public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator {
|
||||
|
||||
private ExecutorService executorService;
|
||||
@@ -14,16 +14,15 @@ public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator {
|
||||
|
||||
@Override
|
||||
public int getExitCode() {
|
||||
int returnCode = 0;
|
||||
try {
|
||||
if (!Objects.isNull(executorService)) {
|
||||
executorService.shutdownNow();
|
||||
returnCode = 1;
|
||||
return 1;
|
||||
}
|
||||
} catch (SecurityException ex) {
|
||||
returnCode = 0;
|
||||
}
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (SecurityException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,9 @@ import com.baeldung.graphql.GraphqlConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
@Import(GraphqlConfiguration.class)
|
||||
public class DemoApplication {
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@ package org.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
@@ -13,8 +12,6 @@ public interface EmployeeRepository extends JpaRepository<Employee, Long> {
|
||||
|
||||
public Employee findByName(String name);
|
||||
|
||||
public Employee findById(Long id);
|
||||
|
||||
public List<Employee> findAll();
|
||||
|
||||
}
|
||||
|
||||
@@ -2,10 +2,9 @@ package org.baeldung.demo.boottest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@@ -16,7 +15,7 @@ public class EmployeeServiceImpl implements EmployeeService {
|
||||
|
||||
@Override
|
||||
public Employee getEmployeeById(Long id) {
|
||||
return employeeRepository.findById(id);
|
||||
return employeeRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -12,7 +12,7 @@ public class FooService {
|
||||
private FooRepository fooRepository;
|
||||
|
||||
public Foo getFooWithId(Integer id) throws Exception {
|
||||
return fooRepository.findOne(id);
|
||||
return fooRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Foo getFooWithName(String name) {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package org.baeldung.endpoints;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomEndpoint implements Endpoint<List<String>> {
|
||||
|
||||
public CustomEndpoint() {
|
||||
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return "customEndpoint";
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isSensitive() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public List<String> invoke() {
|
||||
// Your logic to display the output
|
||||
List<String> messages = new ArrayList<String>();
|
||||
messages.add("This is message 1");
|
||||
messages.add("This is message 2");
|
||||
return messages;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package org.baeldung.endpoints;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ListEndpoints extends AbstractEndpoint<List<Endpoint>> {
|
||||
private List<Endpoint> endpoints;
|
||||
|
||||
@Autowired
|
||||
public ListEndpoints(List<Endpoint> endpoints) {
|
||||
super("listEndpoints");
|
||||
this.endpoints = endpoints;
|
||||
}
|
||||
|
||||
public List<Endpoint> invoke() {
|
||||
return this.endpoints;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package org.baeldung.endpoints;
|
||||
|
||||
import org.springframework.boot.actuate.health.Health;
|
||||
import org.springframework.boot.actuate.health.HealthIndicator;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MyHealthCheck implements HealthIndicator {
|
||||
|
||||
public Health health() {
|
||||
int errorCode = check(); // perform some specific health check
|
||||
if (errorCode != 0) {
|
||||
return Health.down()
|
||||
.withDetail("Error Code", errorCode)
|
||||
.withDetail("Description", "You custom MyHealthCheck endpoint is down")
|
||||
.build();
|
||||
}
|
||||
return Health.up()
|
||||
.build();
|
||||
}
|
||||
|
||||
public int check() {
|
||||
// Your logic to check health
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -4,34 +4,27 @@ import org.baeldung.boot.controller.servlet.HelloWorldServlet;
|
||||
import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet;
|
||||
import org.baeldung.common.error.SpringHelloServletRegistrationBean;
|
||||
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
|
||||
import org.baeldung.service.LoginService;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources","org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config"})
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" })
|
||||
public class SpringBootApplication {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Autowired
|
||||
private LoginService service;
|
||||
|
||||
@RequestMapping("/")
|
||||
@GetMapping("/")
|
||||
String home() {
|
||||
service.login("admin", "admin".toCharArray());
|
||||
return "TADA!!! You are in Spring Boot Actuator test application.";
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,14 @@ public class User {
|
||||
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;
|
||||
}
|
||||
|
||||
+1
-3
@@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(basePackageClasses = ConfigProperties.class)
|
||||
public class ConfigPropertiesDemoApplication {
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
package org.baeldung.repository;
|
||||
|
||||
import org.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;
|
||||
import java.util.stream.Stream;
|
||||
@@ -21,4 +29,54 @@ public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
@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);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package org.baeldung.service;
|
||||
|
||||
public interface LoginService {
|
||||
public boolean login(String userName, char[] password);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package org.baeldung.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.metrics.CounterService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class LoginServiceImpl implements LoginService {
|
||||
|
||||
private CounterService counterService;
|
||||
|
||||
@Autowired
|
||||
public LoginServiceImpl(CounterService counterService) {
|
||||
this.counterService = counterService;
|
||||
}
|
||||
|
||||
public boolean login(String userName, char[] password) {
|
||||
boolean success;
|
||||
if (userName.equals("admin") && "secret".toCharArray()
|
||||
.equals(password)) {
|
||||
counterService.increment("counter.login.success");
|
||||
success = true;
|
||||
} else {
|
||||
counterService.increment("counter.login.failure");
|
||||
success = false;
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,10 +7,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "exception");
|
||||
|
||||
+2
-4
@@ -14,14 +14,12 @@ public class FooRepositoryImpl implements FooRepository {
|
||||
|
||||
@Override
|
||||
public void save(Foo foo) {
|
||||
sessionFactory.getCurrentSession()
|
||||
.saveOrUpdate(foo);
|
||||
sessionFactory.getCurrentSession().saveOrUpdate(foo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Foo get(Integer id) {
|
||||
return sessionFactory.getCurrentSession()
|
||||
.get(Foo.class, id);
|
||||
return sessionFactory.getCurrentSession().get(Foo.class, id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.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++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.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++;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.baeldung.websocket.client;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaders;
|
||||
import org.springframework.messaging.simp.stomp.StompSession;
|
||||
@@ -18,7 +19,7 @@ import java.lang.reflect.Type;
|
||||
*/
|
||||
public class MyStompSessionHandler extends StompSessionHandlerAdapter {
|
||||
|
||||
private Logger logger = Logger.getLogger(MyStompSessionHandler.class);
|
||||
private Logger logger = LogManager.getLogger(MyStompSessionHandler.class);
|
||||
|
||||
@Override
|
||||
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
|
||||
|
||||
Reference in New Issue
Block a user