Merge branch 'master' into hemantvsn_SpringBootNonWebApp_30May18

This commit is contained in:
Grzegorz Piwowarek
2018-06-06 07:33:08 +02:00
committed by GitHub
2820 changed files with 377694 additions and 18480 deletions

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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");
}

View File

@@ -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);

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -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))));
}
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.autoconfiguration.example;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyUserRepository extends JpaRepository<MyUser, String> {
}

View File

@@ -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);
}
}

View File

@@ -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"));
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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());

View File

@@ -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("");
}
}

View File

@@ -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) {

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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";
}
}

View File

@@ -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";
}
}

View File

@@ -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) {

View File

@@ -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());
}
}

View File

@@ -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);

View File

@@ -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);

View File

@@ -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();
}
}

View File

@@ -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);

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -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());
}
}

View File

@@ -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);

View File

@@ -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";
}

View File

@@ -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";
}
}

View File

@@ -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";
}

View File

@@ -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);
}
}

View File

@@ -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 {

View File

@@ -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!";
}
}
}

View File

@@ -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) {

View File

@@ -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

View File

@@ -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);
}
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}

View File

@@ -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) {

View File

@@ -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 {

View File

@@ -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";
}
}

View File

@@ -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);
}
}