minor formatting cleanup
This commit is contained in:
+1
-1
@@ -16,7 +16,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(exclude = MySQLAutoconfiguration.class)
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootAnnotatedApp {
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootPlainApp {
|
||||
|
||||
|
||||
+2
-3
@@ -9,9 +9,8 @@ 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");
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -16,9 +16,8 @@ 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);
|
||||
|
||||
+2
-3
@@ -18,9 +18,8 @@ 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);
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -8,22 +8,22 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")})
|
||||
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") })
|
||||
public class HelloServlet extends HttpServlet {
|
||||
|
||||
private ServletConfig servletConfig;
|
||||
|
||||
@Override
|
||||
public void init(ServletConfig servletConfig){
|
||||
public void init(ServletConfig servletConfig) {
|
||||
this.servletConfig = servletConfig;
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
+7
-9
@@ -92,21 +92,19 @@ public class MySQLAutoconfiguration {
|
||||
|
||||
static class HibernateCondition extends SpringBootCondition {
|
||||
|
||||
private static final String[] CLASS_NAMES = {
|
||||
"org.hibernate.ejb.HibernateEntityManager",
|
||||
"org.hibernate.jpa.HibernateEntityManager" };
|
||||
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))));
|
||||
.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))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -2,6 +2,6 @@ package com.baeldung.autoconfiguration.example;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<MyUser, String>{
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<MyUser, String> {
|
||||
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(Application.class, args);
|
||||
|
||||
|
||||
displayAllBeans();
|
||||
}
|
||||
|
||||
|
||||
public static void displayAllBeans() {
|
||||
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
|
||||
for(String beanName : allBeanNames) {
|
||||
for (String beanName : allBeanNames) {
|
||||
System.out.println(beanName);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -12,9 +12,9 @@ import com.baeldung.displayallbeans.service.FooService;
|
||||
public class FooController {
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
@RequestMapping(value="/displayallbeans")
|
||||
public String getHeaderAndBody (Map<String, Object> model){
|
||||
|
||||
@RequestMapping(value = "/displayallbeans")
|
||||
public String getHeaderAndBody(Map<String, Object> model) {
|
||||
model.put("header", fooService.getHeader());
|
||||
model.put("message", fooService.getBody());
|
||||
return "displayallbeans";
|
||||
|
||||
@@ -4,15 +4,13 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class FooService {
|
||||
|
||||
|
||||
public String getHeader() {
|
||||
return "Display All Beans";
|
||||
}
|
||||
|
||||
|
||||
public String getBody() {
|
||||
return "This is a sample application that displays all beans "
|
||||
+ "in Spring IoC container using ListableBeanFactory interface "
|
||||
+ "and Spring Boot Actuators.";
|
||||
return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators.";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+4
-1
@@ -18,7 +18,10 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class FailureAnalyzerApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
+7
-9
@@ -4,8 +4,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
|
||||
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
||||
import org.springframework.boot.diagnostics.FailureAnalysis;
|
||||
|
||||
public class MyBeanNotOfRequiredTypeFailureAnalyzer
|
||||
extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
|
||||
public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
|
||||
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) {
|
||||
@@ -13,16 +12,15 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class)
|
||||
public class CommitIdApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CommitIdApplication.class, args);
|
||||
|
||||
@@ -23,7 +23,7 @@ public class GraphqlConfiguration {
|
||||
}
|
||||
return new PostDao(posts);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AuthorDao authorDao() {
|
||||
List<Author> authors = new ArrayList<>();
|
||||
@@ -36,12 +36,12 @@ public class GraphqlConfiguration {
|
||||
}
|
||||
return new AuthorDao(authors);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public PostResolver postResolver(AuthorDao authorDao) {
|
||||
return new PostResolver(authorDao);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AuthorResolver authorResolver(PostDao postDao) {
|
||||
return new AuthorResolver(postDao);
|
||||
|
||||
@@ -13,7 +13,8 @@ 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);
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class InternationalizationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class HomeController {
|
||||
|
||||
@RequestMapping("/")
|
||||
public String root(){
|
||||
public String root() {
|
||||
return "Index Page";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping("/local")
|
||||
public String local(){
|
||||
public String local() {
|
||||
return "/local";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class ApplicationMain extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -26,10 +26,13 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
|
||||
@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
|
||||
|
||||
@@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.servlets.*" })
|
||||
@PropertySource("classpath:custom.properties") public class PropertySourcesLoader {
|
||||
@PropertySource("classpath:custom.properties")
|
||||
public class PropertySourcesLoader {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class);
|
||||
|
||||
|
||||
+3
-4
@@ -7,14 +7,13 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(name = "AnnotationServlet",
|
||||
description = "Example Servlet Using Annotations",
|
||||
urlPatterns = { "/annotationservlet" })
|
||||
@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" })
|
||||
public class AnnotationServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@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,6 +2,6 @@ package com.baeldung.toggle;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface EmployeeRepository extends CrudRepository<Employee, Long>{
|
||||
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
|
||||
|
||||
}
|
||||
|
||||
@@ -10,13 +10,15 @@ import org.togglz.core.context.FeatureContext;
|
||||
|
||||
public enum MyFeatures implements Feature {
|
||||
|
||||
@Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID,
|
||||
parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"),
|
||||
@ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") })
|
||||
@Label("Employee Management Feature")
|
||||
@EnabledByDefault
|
||||
@DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"),
|
||||
@ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") })
|
||||
EMPLOYEE_MANAGEMENT_FEATURE;
|
||||
|
||||
public boolean isActive() {
|
||||
return FeatureContext.getFeatureManager().isActive(this);
|
||||
return FeatureContext.getFeatureManager()
|
||||
.isActive(this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,13 +8,13 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages="com.baeldung.utils")
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages = "com.baeldung.utils")
|
||||
public class UtilsApplication {
|
||||
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UtilsApplication.class, args);
|
||||
}
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UtilsApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,37 +13,37 @@ import org.springframework.web.util.WebUtils;
|
||||
@Controller
|
||||
public class UtilsController {
|
||||
|
||||
@GetMapping("/utils")
|
||||
public String webUtils(Model model) {
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@PostMapping("/setParam")
|
||||
public String post(HttpServletRequest request, Model model) {
|
||||
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
|
||||
|
||||
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
|
||||
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
|
||||
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
|
||||
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
|
||||
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
|
||||
|
||||
// try {
|
||||
// ServletRequestUtils.getRequiredStringParameter(request, "param");
|
||||
// } catch (ServletRequestBindingException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
|
||||
WebUtils.setSessionAttribute(request, "parameter", param);
|
||||
model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter"));
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@GetMapping("/other")
|
||||
public String other(HttpServletRequest request, Model model) {
|
||||
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
|
||||
model.addAttribute("parameter", param);
|
||||
return "other";
|
||||
}
|
||||
|
||||
@GetMapping("/utils")
|
||||
public String webUtils(Model model) {
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@PostMapping("/setParam")
|
||||
public String post(HttpServletRequest request, Model model) {
|
||||
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
|
||||
|
||||
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
|
||||
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
|
||||
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
|
||||
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
|
||||
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
|
||||
|
||||
// try {
|
||||
// ServletRequestUtils.getRequiredStringParameter(request, "param");
|
||||
// } catch (ServletRequestBindingException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
|
||||
WebUtils.setSessionAttribute(request, "parameter", param);
|
||||
model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter"));
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@GetMapping("/other")
|
||||
public String other(HttpServletRequest request, Model model) {
|
||||
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
|
||||
model.addAttribute("parameter", param);
|
||||
return "other";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class WebjarsdemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@Import(GraphqlConfiguration.class)
|
||||
public class DemoApplication {
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ public class FooService {
|
||||
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
|
||||
public Foo getFooWithId(Integer id) throws Exception {
|
||||
return fooRepository.findOne(id);
|
||||
}
|
||||
|
||||
|
||||
public Foo getFooWithName(String name) {
|
||||
return fooRepository.findByName(name);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class CommonException extends RuntimeException{
|
||||
public class CommonException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 3080004140659213332L;
|
||||
|
||||
public CommonException(String message){
|
||||
public CommonException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class FooNotFoundException extends RuntimeException{
|
||||
public class FooNotFoundException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 9042200028456133589L;
|
||||
|
||||
public FooNotFoundException(String message){
|
||||
public FooNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ public class Foo implements Serializable {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public Foo(Integer id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
|
||||
@@ -18,7 +18,7 @@ public class FooController {
|
||||
public Foo getFooWithId(@PathVariable Integer id) throws Exception {
|
||||
return fooService.getFooWithId(id);
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/")
|
||||
public Foo getFooWithName(@RequestParam String name) throws Exception {
|
||||
return fooService.getFooWithName(name);
|
||||
|
||||
@@ -39,21 +39,31 @@ public class GenericEntityController {
|
||||
|
||||
@RequestMapping("/entity/findby/{id}")
|
||||
public GenericEntity findById(@PathVariable Long id) {
|
||||
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
|
||||
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();
|
||||
return entityList.stream()
|
||||
.findFirst()
|
||||
.get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbymode/{mode}")
|
||||
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
|
||||
return entityList.stream().findFirst().get();
|
||||
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);
|
||||
return version != null ? new ResponseEntity(entityList.stream()
|
||||
.findFirst()
|
||||
.get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,13 @@ 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.down()
|
||||
.withDetail("Error Code", errorCode)
|
||||
.withDetail("Description", "You custom MyHealthCheck endpoint is down")
|
||||
.build();
|
||||
}
|
||||
return Health.up().build();
|
||||
return Health.up()
|
||||
.build();
|
||||
}
|
||||
|
||||
public int check() {
|
||||
|
||||
@@ -21,8 +21,7 @@ public class UserCombinedSerializer {
|
||||
@Override
|
||||
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("favoriteColor",
|
||||
getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeEndObject();
|
||||
}
|
||||
|
||||
@@ -37,7 +36,8 @@ 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,7 +15,8 @@ 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()));
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@ public class UserJsonSerializer extends JsonSerializer<User> {
|
||||
@Override
|
||||
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("favoriteColor",
|
||||
getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeEndObject();
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class)
|
||||
@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.service" })
|
||||
public class SpringBootApplication {
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ public class MonitoringConfig {
|
||||
|
||||
@Bean
|
||||
public JmxReporter jmxReporter() {
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry).build();
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry)
|
||||
.build();
|
||||
reporter.start();
|
||||
return reporter;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ public class LoginServiceImpl implements LoginService {
|
||||
|
||||
public boolean login(String userName, char[] password) {
|
||||
boolean success;
|
||||
if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
|
||||
if (userName.equals("admin") && "secret".toCharArray()
|
||||
.equals(password)) {
|
||||
counterService.increment("counter.login.success");
|
||||
success = true;
|
||||
} else {
|
||||
|
||||
@@ -10,7 +10,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "exception");
|
||||
|
||||
+4
-2
@@ -14,12 +14,14 @@ 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,6 +20,5 @@ public class Message {
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -17,12 +17,12 @@ import java.lang.reflect.Type;
|
||||
*
|
||||
*/
|
||||
public class MyStompSessionHandler extends StompSessionHandlerAdapter {
|
||||
|
||||
|
||||
private Logger logger = Logger.getLogger(MyStompSessionHandler.class);
|
||||
|
||||
|
||||
@Override
|
||||
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
|
||||
logger.info("New session established : "+session.getSessionId());
|
||||
logger.info("New session established : " + session.getSessionId());
|
||||
session.subscribe("/topic/messages", this);
|
||||
logger.info("Subscribed to /topic/messages");
|
||||
session.send("/app/chat", getSampleMessage());
|
||||
@@ -41,15 +41,15 @@ public class MyStompSessionHandler extends StompSessionHandlerAdapter {
|
||||
|
||||
@Override
|
||||
public void handleFrame(StompHeaders headers, Object payload) {
|
||||
Message msg = (Message)payload;
|
||||
logger.info("Received : "+ msg.getText()+ " from : "+msg.getFrom());
|
||||
Message msg = (Message) payload;
|
||||
logger.info("Received : " + msg.getText() + " from : " + msg.getFrom());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A sample message instance.
|
||||
* @return instance of <code>Message</code>
|
||||
*/
|
||||
private Message getSampleMessage(){
|
||||
private Message getSampleMessage() {
|
||||
Message msg = new Message();
|
||||
msg.setFrom("Nicky");
|
||||
msg.setText("Howdy!!");
|
||||
|
||||
@@ -19,9 +19,9 @@ public class StompClient {
|
||||
public static void main(String[] args) {
|
||||
WebSocketClient client = new StandardWebSocketClient();
|
||||
WebSocketStompClient stompClient = new WebSocketStompClient(client);
|
||||
|
||||
|
||||
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
|
||||
|
||||
|
||||
StompSessionHandler sessionHandler = new MyStompSessionHandler();
|
||||
stompClient.connect(URL, sessionHandler);
|
||||
|
||||
|
||||
+3
-7
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
public class SpringBootWithServletComponentIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
@@ -40,9 +40,8 @@ public class SpringBootWithServletComponentIntegrationTest {
|
||||
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
|
||||
|
||||
assertNotNull(filterRegistration);
|
||||
assertTrue(filterRegistration
|
||||
.getServletNameMappings()
|
||||
.contains("echo servlet"));
|
||||
assertTrue(filterRegistration.getServletNameMappings()
|
||||
.contains("echo servlet"));
|
||||
}
|
||||
|
||||
@Autowired
|
||||
@@ -62,7 +61,4 @@ public class SpringBootWithServletComponentIntegrationTest {
|
||||
assertEquals("filtering echo", responseEntity.getBody());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-3
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertNull;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
public class SpringBootWithoutServletComponentIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
@@ -50,5 +50,3 @@ public class SpringBootWithoutServletComponentIntegrationTest {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = AutoconfigurationApplication.class)
|
||||
@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"})
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" })
|
||||
public class AutoconfigurationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+9
-9
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@TestPropertySource(properties = {"management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false"})
|
||||
@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" })
|
||||
public class DisplayBeanIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
@@ -42,8 +42,7 @@ public class DisplayBeanIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
|
||||
ResponseEntity<String> entity = this.testRestTemplate.getForEntity(
|
||||
"http://localhost:" + this.port + "/displayallbeans", String.class);
|
||||
ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class);
|
||||
|
||||
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
@@ -51,8 +50,7 @@ public class DisplayBeanIntegrationTest {
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
|
||||
@SuppressWarnings("rawtypes")
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity(
|
||||
"http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
|
||||
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
@@ -60,11 +58,13 @@ public class DisplayBeanIntegrationTest {
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception {
|
||||
@SuppressWarnings("rawtypes")
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity(
|
||||
"http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
|
||||
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
|
||||
List<String> beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList());
|
||||
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody()
|
||||
.get(0)).get("beans");
|
||||
List<String> beanNamesList = allBeans.stream()
|
||||
.map(x -> (String) x.get("bean"))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(beanNamesList, hasItem("fooController"));
|
||||
assertThat(beanNamesList, hasItem("fooService"));
|
||||
|
||||
@@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = {"security.basic.enabled=false"})
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
public class AppLiveTest {
|
||||
|
||||
@Autowired
|
||||
@@ -26,16 +26,18 @@ public class AppLiveTest {
|
||||
|
||||
@Test
|
||||
public void getIndex() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
mvc.perform(MockMvcRequestBuilders.get("/")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocal() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
mvc.perform(MockMvcRequestBuilders.get("/local")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -35,7 +35,8 @@ public class ToggleIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -45,7 +46,8 @@ public class ToggleIntegrationTest {
|
||||
|
||||
System.setProperty("employee.feature", "false");
|
||||
|
||||
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
|
||||
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + ""))
|
||||
.andExpect(status().is(200));
|
||||
|
||||
emp = employeeRepository.findOne(1L);
|
||||
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
|
||||
@@ -58,7 +60,8 @@ public class ToggleIntegrationTest {
|
||||
|
||||
System.setProperty("employee.feature", "true");
|
||||
|
||||
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
|
||||
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + ""))
|
||||
.andExpect(status().is(200));
|
||||
|
||||
emp = employeeRepository.findOne(1L);
|
||||
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);
|
||||
|
||||
@@ -22,18 +22,16 @@ public class UtilsControllerIntegrationTest {
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController)
|
||||
.build();
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
|
||||
String param = "testparam";
|
||||
this.mockMvc.perform(
|
||||
post("/setParam")
|
||||
.param("param", param)
|
||||
this.mockMvc.perform(post("/setParam").param("param", param)
|
||||
.sessionAttr("parameter", param))
|
||||
.andExpect(status().isOk());
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+4
-3
@@ -14,8 +14,9 @@ public class MyStompSessionHandlerIntegrationTest {
|
||||
StompHeaders mockHeader = Mockito.mock(StompHeaders.class);
|
||||
MyStompSessionHandler sessionHandler = new MyStompSessionHandler();
|
||||
sessionHandler.afterConnected(mockSession, mockHeader);
|
||||
Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler);
|
||||
Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject());
|
||||
Mockito.verify(mockSession)
|
||||
.subscribe("/topic/messages", sessionHandler);
|
||||
Mockito.verify(mockSession)
|
||||
.send(Mockito.anyString(), Mockito.anyObject());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,36 +33,56 @@ public class SpringBootApplicationIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setupMockMvc() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all"))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isOk())
|
||||
.andExpect(MockMvcResultMatchers.content()
|
||||
.contentType(contentType))
|
||||
.andExpect(jsonPath("$", hasSize(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
|
||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30"))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isOk())
|
||||
.andExpect(MockMvcResultMatchers.content()
|
||||
.contentType(contentType))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
|
||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1)));
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name()))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isOk())
|
||||
.andExpect(MockMvcResultMatchers.content()
|
||||
.contentType(contentType))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
|
||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion")
|
||||
.header("Version", "1.0.0"))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isOk())
|
||||
.andExpect(MockMvcResultMatchers.content()
|
||||
.contentType(contentType))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
}
|
||||
@@ -62,11 +62,15 @@ public class SpringBootMailIntegrationTest {
|
||||
}
|
||||
|
||||
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
|
||||
return wiserMessage.getMimeMessage().getContent().toString().trim();
|
||||
return wiserMessage.getMimeMessage()
|
||||
.getContent()
|
||||
.toString()
|
||||
.trim();
|
||||
}
|
||||
|
||||
private String getSubject(WiserMessage wiserMessage) throws MessagingException {
|
||||
return wiserMessage.getMimeMessage().getSubject();
|
||||
return wiserMessage.getMimeMessage()
|
||||
.getSubject();
|
||||
}
|
||||
|
||||
private SimpleMailMessage composeEmailMessage() {
|
||||
|
||||
+8
-8
@@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest {
|
||||
given(service.save(Mockito.anyObject())).willReturn(alex);
|
||||
|
||||
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(JsonUtil.toJson(alex)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.name", is("alex")));
|
||||
.content(JsonUtil.toJson(alex)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.name", is("alex")));
|
||||
verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject());
|
||||
reset(service);
|
||||
}
|
||||
@@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest {
|
||||
given(service.getAllEmployees()).willReturn(allEmployees);
|
||||
|
||||
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(3)))
|
||||
.andExpect(jsonPath("$[0].name", is(alex.getName())))
|
||||
.andExpect(jsonPath("$[1].name", is(john.getName())))
|
||||
.andExpect(jsonPath("$[2].name", is(bob.getName())));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(3)))
|
||||
.andExpect(jsonPath("$[0].name", is(alex.getName())))
|
||||
.andExpect(jsonPath("$[1].name", is(john.getName())))
|
||||
.andExpect(jsonPath("$[2].name", is(bob.getName())));
|
||||
verify(service, VerificationModeFactory.times(1)).getAllEmployees();
|
||||
reset(service);
|
||||
}
|
||||
|
||||
+2
-2
@@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest {
|
||||
List<Employee> allEmployees = employeeRepository.findAll();
|
||||
|
||||
assertThat(allEmployees).hasSize(3)
|
||||
.extracting(Employee::getName)
|
||||
.containsOnly(alex.getName(), ron.getName(), bob.getName());
|
||||
.extracting(Employee::getName)
|
||||
.containsOnly(alex.getName(), ron.getName(), bob.getName());
|
||||
}
|
||||
}
|
||||
|
||||
+8
-8
@@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest {
|
||||
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
|
||||
Employee bob = new Employee("bob");
|
||||
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(JsonUtil.toJson(bob)));
|
||||
.content(JsonUtil.toJson(bob)));
|
||||
|
||||
List<Employee> found = repository.findAll();
|
||||
assertThat(found).extracting(Employee::getName)
|
||||
.containsOnly("bob");
|
||||
.containsOnly("bob");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest {
|
||||
createTestEmployee("alex");
|
||||
|
||||
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
|
||||
.andExpect(jsonPath("$[0].name", is("bob")))
|
||||
.andExpect(jsonPath("$[1].name", is("alex")));
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
|
||||
.andExpect(jsonPath("$[0].name", is("bob")))
|
||||
.andExpect(jsonPath("$[1].name", is("alex")));
|
||||
}
|
||||
|
||||
private void createTestEmployee(String name) {
|
||||
|
||||
+12
-13
@@ -44,17 +44,17 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
List<Employee> allEmployees = Arrays.asList(john, bob, alex);
|
||||
|
||||
Mockito.when(employeeRepository.findByName(john.getName()))
|
||||
.thenReturn(john);
|
||||
.thenReturn(john);
|
||||
Mockito.when(employeeRepository.findByName(alex.getName()))
|
||||
.thenReturn(alex);
|
||||
.thenReturn(alex);
|
||||
Mockito.when(employeeRepository.findByName("wrong_name"))
|
||||
.thenReturn(null);
|
||||
.thenReturn(null);
|
||||
Mockito.when(employeeRepository.findById(john.getId()))
|
||||
.thenReturn(john);
|
||||
.thenReturn(john);
|
||||
Mockito.when(employeeRepository.findAll())
|
||||
.thenReturn(allEmployees);
|
||||
.thenReturn(allEmployees);
|
||||
Mockito.when(employeeRepository.findById(-99L))
|
||||
.thenReturn(null);
|
||||
.thenReturn(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,8 +62,7 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
String name = "alex";
|
||||
Employee found = employeeService.getEmployeeByName(name);
|
||||
|
||||
assertThat(found.getName())
|
||||
.isEqualTo(name);
|
||||
assertThat(found.getName()).isEqualTo(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,25 +113,25 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
List<Employee> allEmployees = employeeService.getAllEmployees();
|
||||
verifyFindAllEmployeesIsCalledOnce();
|
||||
assertThat(allEmployees).hasSize(3)
|
||||
.extracting(Employee::getName)
|
||||
.contains(alex.getName(), john.getName(), bob.getName());
|
||||
.extracting(Employee::getName)
|
||||
.contains(alex.getName(), john.getName(), bob.getName());
|
||||
}
|
||||
|
||||
private void verifyFindByNameIsCalledOnce(String name) {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findByName(name);
|
||||
.findByName(name);
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
|
||||
private void verifyFindByIdIsCalledOnce() {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findById(Mockito.anyLong());
|
||||
.findById(Mockito.anyLong());
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
|
||||
private void verifyFindAllEmployeesIsCalledOnce() {
|
||||
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
|
||||
.findAll();
|
||||
.findAll();
|
||||
Mockito.reset(employeeRepository);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -30,7 +30,8 @@ public class DetailsServiceClientIntegrationTest {
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
|
||||
this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
||||
this.server.expect(requestTo("/john/details"))
|
||||
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package org.baeldung.jsoncomponent;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
Reference in New Issue
Block a user