BAEL-20869 Move remaining spring boot modules
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
/**
|
||||
* Sample rest controller for the tutorial article
|
||||
* "Access Spring MVC Model object in JavaScript".
|
||||
*
|
||||
* @author Andrew Shcherbakov
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class Controller {
|
||||
|
||||
/**
|
||||
* Define two model objects (one integer and one string) and pass them to the view.
|
||||
*
|
||||
* @param model
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/index")
|
||||
public ModelAndView thymeleafView(Map<String, Object> model) {
|
||||
model.put("number", 1234);
|
||||
model.put("message", "Hello from Spring MVC");
|
||||
return new ModelAndView("thymeleaf/index");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Required;
|
||||
import org.springframework.context.annotation.DependsOn;
|
||||
|
||||
@DependsOn
|
||||
public class Bike implements Vehicle {
|
||||
|
||||
private String color;
|
||||
|
||||
@Required
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Biker {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("bike")
|
||||
private Vehicle vehicle;
|
||||
|
||||
@Autowired
|
||||
public Biker(@Qualifier("bike") Vehicle vehicle) {
|
||||
this.vehicle = vehicle;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setVehicle(@Qualifier("bike") Vehicle vehicle) {
|
||||
this.vehicle = vehicle;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.DependsOn;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Primary
|
||||
@DependsOn("engine")
|
||||
public class Car implements Vehicle {
|
||||
|
||||
@Autowired
|
||||
private Engine engine;
|
||||
|
||||
@Autowired
|
||||
public Car(Engine engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setEngine(Engine engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
public Engine getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Lazy
|
||||
public class CarMechanic {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CarUtility {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Driver {
|
||||
|
||||
@Autowired
|
||||
private Vehicle vehicle;
|
||||
|
||||
@Autowired
|
||||
public Driver(Vehicle vehicle) {
|
||||
this.vehicle = vehicle;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setVehicle(Vehicle vehicle) {
|
||||
this.vehicle = vehicle;
|
||||
}
|
||||
|
||||
public Vehicle getVehicle() {
|
||||
return vehicle;
|
||||
}
|
||||
|
||||
@Scheduled(fixedRate = 10000)
|
||||
@Scheduled(cron = "0 * * * * MON-FRI")
|
||||
public void checkVehicle() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
public class Engine {
|
||||
|
||||
@Value("8")
|
||||
private int cylinderCount;
|
||||
|
||||
@Value("${engine.fuelType}")
|
||||
private String fuelType;
|
||||
|
||||
public Engine() {
|
||||
this(8);
|
||||
}
|
||||
|
||||
public Engine(@Value("8") int cylinderCount) {
|
||||
this.cylinderCount = cylinderCount;
|
||||
}
|
||||
|
||||
@Value("8")
|
||||
public void setCylinderCount(int cylinderCount) {
|
||||
this.cylinderCount = cylinderCount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class PerformanceAspect {
|
||||
|
||||
private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
|
||||
|
||||
@Pointcut("within(@org.springframework.stereotype.Repository *)")
|
||||
public void repositoryClassMethods() {
|
||||
}
|
||||
|
||||
@Around("repositoryClassMethods()")
|
||||
public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
|
||||
long start = System.nanoTime();
|
||||
Object retval = pjp.proceed();
|
||||
long end = System.nanoTime();
|
||||
String methodName = pjp.getSignature().getName();
|
||||
logger.info("Execution of " + methodName + " took " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
|
||||
return retval;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
public interface Vehicle {
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
|
||||
public class VehicleController {
|
||||
|
||||
@CrossOrigin
|
||||
@ResponseBody
|
||||
@RequestMapping("/hello")
|
||||
public String hello() {
|
||||
return "Hello World!";
|
||||
}
|
||||
|
||||
@RequestMapping("/home")
|
||||
public String home() {
|
||||
return "home";
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
public void saveVehicle(@RequestBody Vehicle vehicle) {
|
||||
}
|
||||
|
||||
@RequestMapping("/{id}")
|
||||
public Vehicle getVehicle(@PathVariable("id") long id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@RequestMapping
|
||||
public Vehicle getVehicleByParam(@RequestParam("id") long id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@RequestMapping("/buy")
|
||||
public Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public void onIllegalArgumentException(IllegalArgumentException exception) {
|
||||
}
|
||||
|
||||
@PostMapping("/assemble")
|
||||
public void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicle) {
|
||||
}
|
||||
|
||||
@ModelAttribute("vehicle")
|
||||
public Vehicle getVehicle() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class VehicleFactoryApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(VehicleFactoryApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = "com.baeldung.annotations")
|
||||
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
|
||||
@ImportResource("classpath:/annotations.xml")
|
||||
@PropertySource("classpath:/annotations.properties")
|
||||
@Lazy
|
||||
@EnableAutoConfiguration
|
||||
@EnableAsync
|
||||
@EnableScheduling
|
||||
public class VehicleFactoryConfig {
|
||||
|
||||
@Bean
|
||||
@Lazy(false)
|
||||
public Engine engine() {
|
||||
return new Engine();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class VehicleRepository {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class VehicleRestController {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class VehicleService {
|
||||
|
||||
@Async
|
||||
public void repairCar() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.nosuchbeandefinitionexception;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class BeanA {
|
||||
|
||||
@Autowired
|
||||
BeanB dependency;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.nosuchbeandefinitionexception;
|
||||
|
||||
public class BeanB {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.nosuchbeandefinitionexception;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class NoSuchBeanDefinitionDemoApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(NoSuchBeanDefinitionDemoApp.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.responseentity;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Year;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/customResponse")
|
||||
public class CustomResponseController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
public ResponseEntity<String> hello() {
|
||||
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/age")
|
||||
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
|
||||
if (isInFuture(yearOfBirth)) {
|
||||
return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK);
|
||||
}
|
||||
|
||||
private int calculateAge(int yearOfBirth) {
|
||||
return currentYear() - yearOfBirth;
|
||||
}
|
||||
|
||||
private boolean isInFuture(int year) {
|
||||
return currentYear() < year;
|
||||
}
|
||||
|
||||
private int currentYear() {
|
||||
return Year.now().getValue();
|
||||
}
|
||||
|
||||
@GetMapping("/customHeader")
|
||||
public ResponseEntity<String> customHeader() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("Custom-Header", "foo");
|
||||
|
||||
return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/manual")
|
||||
public void manual(HttpServletResponse response) throws IOException {
|
||||
response.setHeader("Custom-Header", "foo");
|
||||
response.setStatus(200);
|
||||
response.getWriter()
|
||||
.println("Hello World!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.responseentity;
|
||||
|
||||
import java.time.Year;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/customResponseWithBuilder")
|
||||
public class CustomResponseWithBuilderController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
public ResponseEntity<String> hello() {
|
||||
return ResponseEntity.ok("Hello World!");
|
||||
}
|
||||
|
||||
@GetMapping("/age")
|
||||
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
|
||||
if (isInFuture(yearOfBirth)) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body("Year of birth cannot be in the future");
|
||||
}
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body("Your age is " + calculateAge(yearOfBirth));
|
||||
}
|
||||
|
||||
private int calculateAge(int yearOfBirth) {
|
||||
return currentYear() - yearOfBirth;
|
||||
}
|
||||
|
||||
private boolean isInFuture(int year) {
|
||||
return currentYear() < year;
|
||||
}
|
||||
|
||||
private int currentYear() {
|
||||
return Year.now()
|
||||
.getValue();
|
||||
}
|
||||
|
||||
@GetMapping("/customHeader")
|
||||
public ResponseEntity<String> customHeader() {
|
||||
return ResponseEntity.ok()
|
||||
.header("Custom-Header", "foo")
|
||||
.body("Custom header set");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Spring Boot launcher for an application which exposes an RSS Feed.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class RssFeedApplication {
|
||||
|
||||
/**
|
||||
* Launches a Spring Boot application which exposes an RSS Feed.
|
||||
*
|
||||
* @param args null
|
||||
*/
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(RssFeedApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.View;
|
||||
|
||||
/**
|
||||
* REST Controller which returns an RSS Feed created by {@link RssFeedView}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class RssFeedController {
|
||||
|
||||
/**
|
||||
* View used by this controller.
|
||||
*/
|
||||
@Autowired
|
||||
private RssFeedView view;
|
||||
|
||||
/**
|
||||
* Returns an RSS Feed created by {@link #view}.
|
||||
*
|
||||
* @return an RSS Feed
|
||||
*/
|
||||
@GetMapping("/rss")
|
||||
public View getFeed() {
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
|
||||
|
||||
import com.rometools.rome.feed.rss.Channel;
|
||||
import com.rometools.rome.feed.rss.Item;
|
||||
|
||||
/**
|
||||
* View for a RSS feed.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
@Component
|
||||
public class RssFeedView extends AbstractRssFeedView {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.web.servlet.view.feed.AbstractFeedView#
|
||||
* buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed,
|
||||
* javax.servlet.http.HttpServletRequest)
|
||||
*/
|
||||
@Override
|
||||
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
|
||||
feed.setTitle("Baeldung RSS Feed");
|
||||
feed.setDescription("Learn how to program in Java");
|
||||
feed.setLink("http://www.baeldung.com");
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
|
||||
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
|
||||
// Builds the single entries.
|
||||
Item entryOne = new Item();
|
||||
entryOne.setTitle("JUnit 5 @Test Annotation");
|
||||
entryOne.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
|
||||
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
|
||||
|
||||
Item entryTwo = new Item();
|
||||
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
|
||||
entryTwo.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
|
||||
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
|
||||
|
||||
Item entryThree = new Item();
|
||||
entryThree.setTitle("Flyweight Pattern in Java");
|
||||
entryThree.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entryThree.setLink("http://www.baeldung.com/java-flyweight");
|
||||
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
|
||||
|
||||
Item entryFour = new Item();
|
||||
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
|
||||
entryFour.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
|
||||
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z")));
|
||||
|
||||
Item entryFive = new Item();
|
||||
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
|
||||
entryFive.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
|
||||
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
|
||||
|
||||
Item entrySix = new Item();
|
||||
entrySix.setTitle("Double-Checked Locking with Singleton");
|
||||
entrySix.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
|
||||
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
|
||||
|
||||
Item entrySeven = new Item();
|
||||
entrySeven.setTitle("Introduction to Dagger 2");
|
||||
entrySeven.setAuthor("donatohan.rimenti@gmail.com");
|
||||
entrySeven.setLink("http://www.baeldung.com/dagger-2");
|
||||
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
|
||||
|
||||
// Creates the feed.
|
||||
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Configuration
|
||||
public class ScheduleJobsByProfile {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(ScheduleJobsByProfile.class);
|
||||
|
||||
@Profile("prod")
|
||||
@Bean
|
||||
public ScheduledJob scheduledJob()
|
||||
{
|
||||
return new ScheduledJob("@Profile");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
public class ScheduledJob {
|
||||
|
||||
private String source;
|
||||
|
||||
public ScheduledJob(String source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJob.class);
|
||||
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public void cleanTempDir() {
|
||||
LOG.info("Cleaning temp directory via {}", source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
@Configuration
|
||||
public class ScheduledJobsWithBoolean {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJobsWithBoolean.class);
|
||||
|
||||
@Value("${jobs.enabled:true}")
|
||||
private boolean isEnabled;
|
||||
|
||||
/**
|
||||
* A scheduled job controlled via application property. The job always
|
||||
* executes, but the logic inside is protected by a configurable boolean
|
||||
* flag.
|
||||
*/
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public void cleanTempDirectory() {
|
||||
if(isEnabled) {
|
||||
LOG.info("Cleaning temp directory via boolean flag");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ScheduledJobsWithConditional
|
||||
{
|
||||
/**
|
||||
* This uses @ConditionalOnProperty to conditionally create a bean, which itself
|
||||
* is a scheduled job.
|
||||
* @return ScheduledJob
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true")
|
||||
public ScheduledJob runMyCronTask() {
|
||||
return new ScheduledJob("@ConditionalOnProperty");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
@Configuration
|
||||
public class ScheduledJobsWithExpression
|
||||
{
|
||||
private final static Logger LOG =
|
||||
LoggerFactory.getLogger(ScheduledJobsWithExpression.class);
|
||||
|
||||
/**
|
||||
* A scheduled job controlled via application property. The job always
|
||||
* executes, but the logic inside is protected by a configurable boolean
|
||||
* flag.
|
||||
*/
|
||||
@Scheduled(cron = "${jobs.cronSchedule:-}")
|
||||
public void cleanTempDirectory() {
|
||||
LOG.info("Cleaning temp directory via placeholder");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.scheduling;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class SchedulingApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SchedulingApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.springbootannotations;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
|
||||
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnClass(DataSource.class)
|
||||
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
|
||||
@PropertySource("classpath:mysql.properties")
|
||||
public class MySQLAutoconfiguration {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "usemysql", havingValue = "local")
|
||||
@ConditionalOnMissingBean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
|
||||
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||
dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=UTC");
|
||||
dataSource.setUsername("mysqluser");
|
||||
dataSource.setPassword("mysqlpass");
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean(name = "dataSource")
|
||||
@ConditionalOnProperty(name = "usemysql", havingValue = "custom")
|
||||
@ConditionalOnMissingBean
|
||||
public DataSource dataSource2() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
|
||||
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||
dataSource.setUrl(env.getProperty("mysql.url"));
|
||||
dataSource.setUsername(env.getProperty("mysql.user") != null ? env.getProperty("mysql.user") : "");
|
||||
dataSource.setPassword(env.getProperty("mysql.pass") != null ? env.getProperty("mysql.pass") : "");
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(name = "dataSource")
|
||||
@ConditionalOnMissingBean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan("com.baeldung.autoconfiguration.example");
|
||||
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
|
||||
if (additionalProperties() != null) {
|
||||
em.setJpaProperties(additionalProperties());
|
||||
}
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(type = "JpaTransactionManager")
|
||||
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@ConditionalOnResource(resources = "classpath:mysql.properties")
|
||||
@Conditional(HibernateCondition.class)
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
|
||||
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
static class HibernateCondition extends SpringBootCondition {
|
||||
|
||||
private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" };
|
||||
|
||||
@Override
|
||||
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
|
||||
|
||||
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
|
||||
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.springbootmvc;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class LoggingController {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(LoggingController.class);
|
||||
|
||||
@GetMapping("/")
|
||||
public String index() {
|
||||
logger.trace("A TRACE Message");
|
||||
logger.debug("A DEBUG Message");
|
||||
logger.info("An INFO Message");
|
||||
logger.warn("A WARN Message");
|
||||
logger.error("An ERROR Message");
|
||||
|
||||
return "Howdy! Check out the Logs to see the output...";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.springbootmvc;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.springbootmvc.model.LoginForm;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/")
|
||||
public class LoginController {
|
||||
|
||||
@PostMapping("loginform")
|
||||
public String processLogin(@Valid LoginForm form) {
|
||||
return "Success";
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.springbootmvc;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringBootMvcApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootMvcApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.springbootmvc.config;
|
||||
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
|
||||
@Configuration
|
||||
public class CustomMessageSourceConfiguration {
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
|
||||
messageSource.setBasename("classpath:messages");
|
||||
messageSource.setDefaultEncoding("UTF-8");
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalValidatorFactoryBean getValidator() {
|
||||
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
|
||||
bean.setValidationMessageSource(messageSource());
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.springbootmvc.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
|
||||
|
||||
@Configuration
|
||||
public class FaviconConfiguration {
|
||||
@Bean
|
||||
public SimpleUrlHandlerMapping myFaviconHandlerMapping() {
|
||||
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
|
||||
mapping.setOrder(Integer.MIN_VALUE);
|
||||
mapping.setUrlMap(Collections.singletonMap("/favicon.ico", faviconRequestHandler()));
|
||||
return mapping;
|
||||
}
|
||||
|
||||
@Bean
|
||||
protected ResourceHttpRequestHandler faviconRequestHandler() {
|
||||
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
|
||||
ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images");
|
||||
List<Resource> locations = Arrays.asList(classPathResource);
|
||||
requestHandler.setLocations(locations);
|
||||
return requestHandler;
|
||||
}
|
||||
|
||||
// @Controller
|
||||
static class FaviconController {
|
||||
|
||||
@RequestMapping(value = "favicon.ico", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
void favicon() {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication;
|
||||
|
||||
import javax.faces.webapp.FacesServlet;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.springbootmvc.jsfapplication.controller.JsfController;
|
||||
import com.baeldung.springbootmvc.jsfapplication.model.TodoDao;
|
||||
import com.baeldung.springbootmvc.jsfapplication.service.TodoService;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class })
|
||||
public class JsfApplication extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JsfApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ServletRegistrationBean servletRegistrationBean() {
|
||||
FacesServlet servlet = new FacesServlet();
|
||||
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf");
|
||||
return servletRegistrationBean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication.controller;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Scope(value = "session")
|
||||
@Component(value = "jsfController")
|
||||
public class JsfController {
|
||||
|
||||
public String loadTodoPage() {
|
||||
checkPermission();
|
||||
return "/todo.xhtml";
|
||||
}
|
||||
|
||||
private void checkPermission() {
|
||||
// Details omitted
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface Dao<T> {
|
||||
|
||||
Optional<T> get(int id);
|
||||
|
||||
Collection<T> getAll();
|
||||
|
||||
int save(T t);
|
||||
|
||||
void update(T t);
|
||||
|
||||
void delete(T t);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||
|
||||
public class Todo {
|
||||
|
||||
private int id;
|
||||
private String message;
|
||||
private int priority;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public int getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
public void setPriority(int priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class TodoDao implements Dao<Todo> {
|
||||
|
||||
private List<Todo> todoList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public Optional<Todo> get(int id) {
|
||||
return Optional.ofNullable(todoList.get(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Todo> getAll() {
|
||||
return todoList.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int save(Todo todo) {
|
||||
todoList.add(todo);
|
||||
int index = todoList.size() - 1;
|
||||
todo.setId(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Todo todo) {
|
||||
todoList.set(todo.getId(), todo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Todo todo) {
|
||||
todoList.set(todo.getId(), null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.springbootmvc.jsfapplication.service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.springbootmvc.jsfapplication.model.Dao;
|
||||
import com.baeldung.springbootmvc.jsfapplication.model.Todo;
|
||||
|
||||
@Scope(value = "session")
|
||||
@Component(value = "todoService")
|
||||
public class TodoService {
|
||||
|
||||
@Autowired
|
||||
private Dao<Todo> todoDao;
|
||||
private Todo todo = new Todo();
|
||||
|
||||
public void save() {
|
||||
todoDao.save(todo);
|
||||
todo = new Todo();
|
||||
}
|
||||
|
||||
public Collection<Todo> getAllTodo() {
|
||||
return todoDao.getAll();
|
||||
}
|
||||
|
||||
public Collection<Todo> getAllTodoSortedByPriority() {
|
||||
return todoDao.getAll()
|
||||
.stream()
|
||||
.sorted(Comparator.comparingInt(Todo::getId))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public int saveTodo(Todo todo) {
|
||||
validate(todo);
|
||||
return todoDao.save(todo);
|
||||
}
|
||||
|
||||
private void validate(Todo todo) {
|
||||
// Details omitted
|
||||
}
|
||||
|
||||
public Todo getTodo() {
|
||||
return todo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.springbootmvc.model;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class LoginForm {
|
||||
|
||||
@NotEmpty(message = "{email.notempty}")
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
private String password;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.swagger2boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.swagger2boot.configuration;
|
||||
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin;
|
||||
|
||||
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger.web.*;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2WebMvc
|
||||
@Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class})
|
||||
public class SpringFoxConfig {
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfo(
|
||||
"My REST API",
|
||||
"Some custom description of API.",
|
||||
"API TOS",
|
||||
"Terms of service",
|
||||
new Contact("John Doe", "www.example.com", "myeaddress@company.com"),
|
||||
"License of API",
|
||||
"API license URL",
|
||||
Collections.emptyList());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Docket api() {
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.any())
|
||||
.paths(PathSelectors.any())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* SwaggerUI information
|
||||
*/
|
||||
|
||||
@Bean
|
||||
UiConfiguration uiConfig() {
|
||||
return UiConfigurationBuilder.builder()
|
||||
.deepLinking(true)
|
||||
.displayOperationId(false)
|
||||
.defaultModelsExpandDepth(1)
|
||||
.defaultModelExpandDepth(1)
|
||||
.defaultModelRendering(ModelRendering.EXAMPLE)
|
||||
.displayRequestDuration(false)
|
||||
.docExpansion(DocExpansion.NONE)
|
||||
.filter(false)
|
||||
.maxDisplayedTags(null)
|
||||
.operationsSorter(OperationsSorter.ALPHA)
|
||||
.showExtensions(false)
|
||||
.tagsSorter(TagsSorter.ALPHA)
|
||||
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
|
||||
.validatorUrl(null)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EmailAnnotationPlugin emailPlugin() {
|
||||
return new EmailAnnotationPlugin();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.swagger2boot.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RegularRestController {
|
||||
|
||||
@GetMapping("home")
|
||||
public String getSession() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.swagger2boot.model;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@NotNull(message = "First Name cannot be null")
|
||||
private String firstName;
|
||||
|
||||
@Min(value = 15, message = "Age should not be less than 15")
|
||||
@Max(value = 65, message = "Age should not be greater than 65")
|
||||
private int age;
|
||||
|
||||
@Email(regexp=".@.\\..*", message = "Email should be valid")
|
||||
private String email;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.swagger2boot.plugin;
|
||||
|
||||
import static springfox.bean.validators.plugins.Validators.annotationFromBean;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import springfox.bean.validators.plugins.Validators;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
|
||||
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
|
||||
|
||||
@Component
|
||||
@Order(Validators.BEAN_VALIDATOR_PLUGIN_ORDER)
|
||||
public class EmailAnnotationPlugin implements ModelPropertyBuilderPlugin {
|
||||
|
||||
@Override
|
||||
public boolean supports(DocumentationType delimiter) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* read Email annotation
|
||||
*/
|
||||
@Override
|
||||
public void apply(ModelPropertyContext context) {
|
||||
Optional<Email> email = annotationFromBean(context, Email.class);
|
||||
if (email.isPresent()) {
|
||||
context.getBuilder().pattern(email.get().regexp());
|
||||
context.getBuilder().example("email@email.com");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.swagger2boot.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.swagger2boot.model.User;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends CrudRepository<User, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
spring.thymeleaf.view-names=thymeleaf/*
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1 @@
|
||||
email.notempty=Please provide valid email id.
|
||||
@@ -0,0 +1 @@
|
||||
email.notempty=Veuillez fournir un identifiant de messagerie valide.
|
||||
@@ -0,0 +1,5 @@
|
||||
usemysql=local
|
||||
|
||||
mysql-hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
|
||||
mysql-hibernate.show_sql=true
|
||||
mysql-hibernate.hbm2ddl.auto=create-drop
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1 @@
|
||||
Welcome to Baeldung
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Access Spring MVC params</title>
|
||||
<script src="/js/jquery.js"></script>
|
||||
<script src="/js/script-async.js"></script>
|
||||
<script src="/js/script-async-jquery.js"></script>
|
||||
<script>
|
||||
var number = [[${number}]];
|
||||
var message = "[[${message}]]";
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
Number=
|
||||
<span th:text="${number}" th:remove="tag"></span>
|
||||
<br /> Message=
|
||||
<span th:text="${message}" th:remove="tag"></span>
|
||||
<h2>Data from the external JS file (due to loading order)</h2>
|
||||
<div id="number-ext"></div>
|
||||
<div id="message-ext"></div>
|
||||
<h2>Asynchronous loading from external JS file (plain JS)</h2>
|
||||
<div id="number-async"></div>
|
||||
<div id="message-async"></div>
|
||||
<h2>Asynchronous loading from external JS file (jQuery)</h2>
|
||||
<div id="number-async-jquery"></div>
|
||||
<div id="message-async-jquery"></div>
|
||||
</body>
|
||||
<script src="/js/script.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
|
||||
version="2.2">
|
||||
<application>
|
||||
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
|
||||
</application>
|
||||
</faces-config>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
version="3.0">
|
||||
|
||||
<servlet>
|
||||
<servlet-name>Faces Servlet</servlet-name>
|
||||
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>Faces Servlet</servlet-name>
|
||||
<url-pattern>*.jsf</url-pattern>
|
||||
</servlet-mapping>
|
||||
<context-param>
|
||||
<param-name>com.sun.faces.forceLoadConfiguration</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
</web-app>
|
||||
@@ -0,0 +1,20 @@
|
||||
<f:view xmlns="http://www.w3c.org/1999/xhtml"
|
||||
xmlns:f="http://java.sun.com/jsf/core"
|
||||
xmlns:h="http://java.sun.com/jsf/html">
|
||||
<h:head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
|
||||
<title>TO-DO application</title>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<div>
|
||||
<p>Welcome in the TO-DO application!</p>
|
||||
<p style="height:50px">
|
||||
This is a static message rendered from xhtml.
|
||||
<h:form>
|
||||
<h:commandButton value="Load To-do page!" action="#{jsfController.loadTodoPage}" />
|
||||
</h:form>
|
||||
</p>
|
||||
</div>
|
||||
</h:body>
|
||||
</f:view>
|
||||
2
spring-boot-modules/spring-boot-mvc/src/main/webapp/js/jquery.js
vendored
Normal file
2
spring-boot-modules/spring-boot-mvc/src/main/webapp/js/jquery.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
|
||||
$(function() {
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-async-jquery').append(node1);
|
||||
document.getElementById('number-async-jquery').append(node2);
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
window.onload = function() {
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-async').append(node1);
|
||||
document.getElementById('number-async').append(node2);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-ext').append(node1);
|
||||
document.getElementById('number-ext').append(node2);
|
||||
@@ -0,0 +1,38 @@
|
||||
<f:view xmlns="http://www.w3c.org/1999/xhtml"
|
||||
xmlns:f="http://java.sun.com/jsf/core"
|
||||
xmlns:h="http://java.sun.com/jsf/html">
|
||||
<h:head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
|
||||
<title>TO-DO application</title>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<div>
|
||||
<div>
|
||||
List of TO-DO items
|
||||
</div>
|
||||
<h:dataTable value="#{todoService.allTodo}" var="item">
|
||||
<h:column>
|
||||
<f:facet name="header"> Message</f:facet>
|
||||
#{item.message}
|
||||
</h:column>
|
||||
<h:column>
|
||||
<f:facet name="header"> Priority</f:facet>
|
||||
#{item.priority}
|
||||
</h:column>
|
||||
</h:dataTable>
|
||||
</div>
|
||||
<div>
|
||||
<div>
|
||||
Add new to-do item:
|
||||
</div>
|
||||
<h:form>
|
||||
<h:outputLabel for="message" value="Message: "/>
|
||||
<h:inputText id="message" value="#{todoService.todo.message}"/>
|
||||
<h:outputLabel for="priority" value="Priority: "/>
|
||||
<h:inputText id="priority" value="#{todoService.todo.priority}" converterMessage="Please enter digits only."/>
|
||||
<h:commandButton value="Save" action="#{todoService.save}"/>
|
||||
</h:form>
|
||||
</div>
|
||||
</h:body>
|
||||
</f:view>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class ControllerUnitTest {
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void whenRequestThymeleaf_thenStatusOk() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/index")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.rss;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
/**
|
||||
* Test for {@link RssFeedApplication}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = RssFeedApplication.class)
|
||||
public class RssFeedUnitTest {
|
||||
|
||||
/**
|
||||
* Application context.
|
||||
*/
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
|
||||
/**
|
||||
* Mock to perform tests on Spring Web Controller.
|
||||
*/
|
||||
private MockMvc mvc;
|
||||
|
||||
/**
|
||||
* Sets the test up.
|
||||
*/
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(context).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the RSS feed endpoint and checks that the result matches an
|
||||
* expected one.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenRssFeed_whenComparedWithExisting_thenEquals() throws Exception {
|
||||
// The expected response.
|
||||
String expectedResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\"> <channel> <title>Baeldung RSS Feed</title> <link>http://www.baeldung.com</link> <description>Learn how to program in Java</description> <item> <title>JUnit 5 @Test Annotation</title> <link>http://www.baeldung.com/junit-5-test-annotation</link> <pubDate>Tue, 19 Dec 2017 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Creating and Configuring Jetty 9 Server in Java</title> <link>http://www.baeldung.com/jetty-java-programmatic</link> <pubDate>Tue, 23 Jan 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Flyweight Pattern in Java</title> <link>http://www.baeldung.com/java-flyweight</link> <pubDate>Thu, 01 Feb 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Multi-Swarm Optimization Algorithm in Java</title> <link>http://www.baeldung.com/java-multi-swarm-algorithm</link> <pubDate>Fri, 09 Mar 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>A Simple Tagging Implementation with MongoDB</title> <link>http://www.baeldung.com/mongodb-tagging</link> <pubDate>Tue, 27 Mar 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Double-Checked Locking with Singleton</title> <link>http://www.baeldung.com/java-singleton-double-checked-locking</link> <pubDate>Mon, 23 Apr 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Introduction to Dagger 2</title> <link>http://www.baeldung.com/dagger-2</link> <pubDate>Sat, 30 Jun 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> </channel></rss>";
|
||||
|
||||
// Performs a post against the RSS feed endpoint and checks that the
|
||||
// result is equals to the expected one.
|
||||
mvc.perform(MockMvcRequestBuilders.get("/rss")).andExpect(status().isOk())
|
||||
.andExpect(content().xml(expectedResult));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.springbootmvc;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.RequestBuilder;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
import com.baeldung.springbootmvc.config.CustomMessageSourceConfiguration;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(value = LoginController.class)
|
||||
@ContextConfiguration(classes = { SpringBootMvcApplication.class, CustomMessageSourceConfiguration.class })
|
||||
public class LoginControllerUnitTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void givenLoginForm_whenEmailFieldNotProvided_testCustomValidMessageIsReturned() throws Exception {
|
||||
|
||||
RequestBuilder builder = MockMvcRequestBuilders.post("/loginform").param("email", "").param("password", "helo");
|
||||
|
||||
// header("accept-language", "fr").
|
||||
MvcResult perform = mockMvc.perform(builder).andReturn();
|
||||
Assert.assertTrue(perform.getResolvedException().getMessage().contains("valid email"));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.springbootannotations.MySQLAutoconfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MySQLAutoconfiguration.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.springbootmvc.SpringBootMvcApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = SpringBootMvcApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user