BAEL-20869 Move remaining spring boot modules
This commit is contained in:
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.changeport;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CustomApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication app = new SpringApplication(CustomApplication.class);
|
||||
app.setDefaultProperties(Collections.singletonMap("server.port", "8083"));
|
||||
app.run(args);
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.changeport;
|
||||
|
||||
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
//@Component
|
||||
public class ServerPortCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableWebServerFactory factory) {
|
||||
factory.setPort(8086);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.cors;
|
||||
|
||||
public class Account {
|
||||
private Long id;
|
||||
|
||||
public Account(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.cors;
|
||||
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@CrossOrigin(maxAge = 3600)
|
||||
@RestController
|
||||
@RequestMapping("/account")
|
||||
public class AccountController {
|
||||
|
||||
@CrossOrigin("http://example.com")
|
||||
@RequestMapping("/{id}")
|
||||
public Account retrieve(@PathVariable Long id) {
|
||||
return new Account(id);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
|
||||
public void remove(@PathVariable Long id) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.restart;
|
||||
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
private static ConfigurableApplicationContext context;
|
||||
|
||||
public static void main(String[] args) {
|
||||
context = SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
public static void restart() {
|
||||
ApplicationArguments args = context.getBean(ApplicationArguments.class);
|
||||
|
||||
Thread thread = new Thread(() -> {
|
||||
context.close();
|
||||
context = SpringApplication.run(Application.class, args.getSourceArgs());
|
||||
});
|
||||
|
||||
thread.setDaemon(false);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.restart;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RestartController {
|
||||
|
||||
@Autowired
|
||||
private RestartService restartService;
|
||||
|
||||
@PostMapping("/restart")
|
||||
public void restart() {
|
||||
Application.restart();
|
||||
}
|
||||
|
||||
@PostMapping("/restartApp")
|
||||
public void restartUsingActuator() {
|
||||
restartService.restartApp();
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.restart;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.restart.RestartEndpoint;
|
||||
|
||||
@Service
|
||||
public class RestartService {
|
||||
|
||||
@Autowired
|
||||
private RestartEndpoint restartEndpoint;
|
||||
|
||||
public void restartApp() {
|
||||
restartEndpoint.restart();
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.sampleapp")
|
||||
public class MainApplication implements WebMvcConfigurer {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(MainApplication.class, args);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor;
|
||||
|
||||
@Configuration
|
||||
public class RestClientConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
|
||||
if (CollectionUtils.isEmpty(interceptors)) {
|
||||
interceptors = new ArrayList<ClientHttpRequestInterceptor>();
|
||||
}
|
||||
interceptors.add(new RestTemplateHeaderModifierInterceptor());
|
||||
restTemplate.setInterceptors(interceptors);
|
||||
return restTemplate;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/*
|
||||
* Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan({ "com.baeldung.sampleapp.web" })
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
|
||||
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
|
||||
builder.indentOutput(true)
|
||||
.dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
|
||||
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
|
||||
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
|
||||
|
||||
// messageConverters.add(new MappingJackson2HttpMessageConverter());
|
||||
|
||||
// messageConverters.add(new ProtobufHttpMessageConverter());
|
||||
|
||||
}
|
||||
|
||||
*/
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.sampleapp.interceptors;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
|
||||
public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor {
|
||||
|
||||
@Override
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
|
||||
ClientHttpResponse response = execution.execute(request, body);
|
||||
response.getHeaders().add("Foo", "bar");
|
||||
return response;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.sampleapp.repository;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResource;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
|
||||
|
||||
public class HeavyResourceRepository {
|
||||
|
||||
public void save(HeavyResource heavyResource) {
|
||||
}
|
||||
|
||||
public void save(HeavyResourceAddressOnly partialUpdate) {
|
||||
|
||||
}
|
||||
|
||||
public void save(Map<String, Object> updates, String id) {
|
||||
|
||||
}
|
||||
|
||||
public void save(HeavyResource heavyResource, String id) {
|
||||
|
||||
}
|
||||
|
||||
public void save(HeavyResourceAddressOnly partialUpdate, String id) {
|
||||
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/ex")
|
||||
public class BarMappingExamplesController {
|
||||
|
||||
public BarMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// with @RequestParam
|
||||
|
||||
@RequestMapping(value = "/bars")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = "id")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = { "id", "second" })
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
|
||||
@ResponseBody
|
||||
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
|
||||
return "Get a specific Bar with id=" + numericId;
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Company;
|
||||
|
||||
@RestController
|
||||
public class CompanyController {
|
||||
|
||||
@RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Company getCompanyRest() {
|
||||
final Company company = new Company(1, "Xpto");
|
||||
return company;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.request.async.DeferredResult;
|
||||
|
||||
@RestController
|
||||
public class DeferredResultController {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
|
||||
|
||||
@GetMapping("/async-deferredresult")
|
||||
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
|
||||
LOG.info("Received request");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
|
||||
|
||||
deferredResult.onCompletion(() -> LOG.info("Processing complete"));
|
||||
|
||||
CompletableFuture.supplyAsync(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(6000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "OK";
|
||||
})
|
||||
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
|
||||
|
||||
LOG.info("Servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
@GetMapping("/process-blocking")
|
||||
public ResponseEntity<?> handleReqSync(Model model) {
|
||||
// ...
|
||||
return ResponseEntity.ok("ok");
|
||||
}
|
||||
|
||||
@GetMapping("/async-deferredresult-timeout")
|
||||
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
|
||||
LOG.info("Received async request with a configured timeout");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
|
||||
deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT)
|
||||
.body("Request timeout occurred.")));
|
||||
|
||||
CompletableFuture.supplyAsync(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(6000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "error";
|
||||
})
|
||||
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
|
||||
LOG.info("servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
@GetMapping("/async-deferredresult-error")
|
||||
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
|
||||
LOG.info("Received async request with a configured error handler");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
|
||||
deferredResult.onError(new Consumer<Throwable>() {
|
||||
@Override
|
||||
public void accept(Throwable t) {
|
||||
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("An error occurred."));
|
||||
}
|
||||
|
||||
});
|
||||
LOG.info("servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.repository.HeavyResourceRepository;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResource;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
|
||||
|
||||
@RestController
|
||||
public class HeavyResourceController {
|
||||
|
||||
private HeavyResourceRepository heavyResourceRepository = new HeavyResourceRepository();
|
||||
|
||||
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> saveResource(@RequestBody HeavyResource heavyResource, @PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(heavyResource, id);
|
||||
return ResponseEntity.ok("resource saved");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> partialUpdateName(@RequestBody HeavyResourceAddressOnly partialUpdate, @PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(partialUpdate, id);
|
||||
return ResponseEntity.ok("resource address updated");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/heavyresource2/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> partialUpdateGeneric(@RequestBody Map<String, Object> updates,
|
||||
@PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(updates, id);
|
||||
return ResponseEntity.ok("resource updated");
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Item;
|
||||
import com.baeldung.sampleapp.web.dto.ItemManager;
|
||||
import com.baeldung.sampleapp.web.dto.Views;
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
@RestController
|
||||
public class ItemController {
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
@RequestMapping("/items/{id}")
|
||||
public Item getItemPublic(@PathVariable final int id) {
|
||||
return ItemManager.getById(id);
|
||||
}
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
@RequestMapping("/items/internal/{id}")
|
||||
public Item getItemInternal(@PathVariable final int id) {
|
||||
return ItemManager.getById(id);
|
||||
}
|
||||
|
||||
@RequestMapping("/date")
|
||||
public Date getCurrentDate() throws Exception {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
@RequestMapping("/delay/{seconds}")
|
||||
public void getCurrentTime(@PathVariable final int seconds) throws Exception {
|
||||
|
||||
Thread.sleep(seconds * 1000);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Foo;
|
||||
import com.baeldung.sampleapp.web.exception.ResourceNotFoundException;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/foos")
|
||||
public class MyFooController {
|
||||
|
||||
private final Map<Long, Foo> myfoos;
|
||||
|
||||
public MyFooController() {
|
||||
super();
|
||||
myfoos = new HashMap<Long, Foo>();
|
||||
myfoos.put(1L, new Foo(1L, "sample foo"));
|
||||
}
|
||||
|
||||
// API - read
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Collection<Foo> findAll() {
|
||||
return myfoos.values();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable final long id) {
|
||||
final Foo foo = myfoos.get(id);
|
||||
if (foo == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return foo;
|
||||
}
|
||||
|
||||
// API - write
|
||||
|
||||
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
|
||||
myfoos.put(foo.getId(), foo);
|
||||
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest()
|
||||
.path("/" + foo.getId())
|
||||
.toUriString());
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void deleteById(@PathVariable final long id) {
|
||||
myfoos.remove(id);
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.PactDto;
|
||||
|
||||
@RestController
|
||||
public class PactController {
|
||||
|
||||
List<PactDto> pacts = new ArrayList<>();
|
||||
|
||||
@GetMapping(value = "/pact", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public PactDto getPact() {
|
||||
return new PactDto(true, "tom");
|
||||
}
|
||||
|
||||
@PostMapping("/pact")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void createPact(PactDto pact) {
|
||||
pacts.add(pact);
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
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.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Foo;
|
||||
|
||||
// used to test HttpClientPostingTest
|
||||
@RestController
|
||||
public class SimplePostController {
|
||||
|
||||
@RequestMapping(value = "/users", method = RequestMethod.POST)
|
||||
public String postUser(@RequestParam final String username, @RequestParam final String password) {
|
||||
return "Success" + username;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
|
||||
public String postUserDetail(@RequestBody final Foo entity) {
|
||||
return "Success" + entity.getId();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
|
||||
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded " + username;
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
|
||||
public String postMultipart(@RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded ";
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.sampleapp.web.controller.mediatypes;
|
||||
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.BaeldungItem;
|
||||
import com.baeldung.sampleapp.web.dto.BaeldungItemV2;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json")
|
||||
public class CustomMediaTypeController {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v1+json")
|
||||
public @ResponseBody BaeldungItem getItem(@PathVariable("id") String id) {
|
||||
return new BaeldungItem("itemId1");
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v2+json")
|
||||
public @ResponseBody BaeldungItemV2 getItemSecondAPIVersion(@PathVariable("id") String id) {
|
||||
return new BaeldungItemV2("itemName");
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.sampleapp.web.controller.redirect;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/")
|
||||
public class RedirectController {
|
||||
|
||||
@RequestMapping(value = "/redirectWithXMLConfig", method = RequestMethod.GET)
|
||||
public ModelAndView redirectWithUsingXMLConfig(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithXMLConfig");
|
||||
return new ModelAndView("RedirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectPrefix", method = RequestMethod.GET)
|
||||
public ModelAndView redirectWithUsingRedirectPrefix(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithRedirectPrefix");
|
||||
return new ModelAndView("redirect:/redirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectAttributes", method = RequestMethod.GET)
|
||||
public RedirectView redirectWithRedirectAttributes(final RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
|
||||
redirectAttributes.addAttribute("attribute", "redirectWithRedirectAttributes");
|
||||
return new RedirectView("redirectedUrl");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectView", method = RequestMethod.GET)
|
||||
public RedirectView redirectWithUsingRedirectView(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithRedirectView");
|
||||
return new RedirectView("redirectedUrl");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET)
|
||||
public ModelAndView forwardWithUsingForwardPrefix(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithForwardPrefix");
|
||||
return new ModelAndView("forward:/redirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET)
|
||||
public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttribute") final Object flashAttribute) {
|
||||
model.addAttribute("redirectionAttribute", flashAttribute);
|
||||
return new ModelAndView("redirection", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST)
|
||||
public ModelAndView redirectPostToPost(HttpServletRequest request) {
|
||||
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
|
||||
return new ModelAndView("redirect:/redirectedPostToPost");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST)
|
||||
public ModelAndView redirectedPostToPost() {
|
||||
return new ModelAndView("redirection");
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class BaeldungItem {
|
||||
private final String itemId;
|
||||
|
||||
public BaeldungItem(String itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class BaeldungItemV2 {
|
||||
private final String itemName;
|
||||
|
||||
public BaeldungItemV2(String itemName) {
|
||||
this.itemName = itemName;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class Company {
|
||||
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
public Company() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Company(final long id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Company [id=" + id + ", name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class Foo {
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Foo(final long id, final String name) {
|
||||
super();
|
||||
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResource {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String surname;
|
||||
private Integer age;
|
||||
private String address;
|
||||
|
||||
|
||||
public HeavyResource() {
|
||||
}
|
||||
|
||||
public HeavyResource(Integer id, String name, String surname, Integer age, String address) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
this.age = age;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResourceAddressOnly {
|
||||
private Integer id;
|
||||
private String address;
|
||||
|
||||
public HeavyResourceAddressOnly() {
|
||||
}
|
||||
|
||||
public HeavyResourceAddressOnly(Integer id, String address) {
|
||||
this.id = id;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResourceAddressPartialUpdate {
|
||||
private Integer id;
|
||||
private String address;
|
||||
|
||||
public HeavyResourceAddressPartialUpdate() {
|
||||
}
|
||||
|
||||
public HeavyResourceAddressPartialUpdate(Integer id, String address) {
|
||||
this.id = id;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class Item {
|
||||
@JsonView(Views.Public.class)
|
||||
public int id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
public String itemName;
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
public String ownerName;
|
||||
|
||||
public Item() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Item(final int id, final String itemName, final String ownerName) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.ownerName = ownerName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class ItemManager {
|
||||
|
||||
public static Item getById(final int id) {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
return item;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class PactDto {
|
||||
|
||||
private boolean condition;
|
||||
private String name;
|
||||
|
||||
public PactDto() {
|
||||
}
|
||||
|
||||
public PactDto(boolean condition, String name) {
|
||||
super();
|
||||
this.condition = condition;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isCondition() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
public void setCondition(boolean condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Internal extends Public {
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.sampleapp.web.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.shutdown;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.context.ApplicationPidFileWriter;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
SpringApplication.run(Application.class, args);
|
||||
// closeApplication();
|
||||
// exitApplication();
|
||||
// writePID();
|
||||
|
||||
}
|
||||
|
||||
private static void closeApplication() {
|
||||
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
|
||||
System.out.println("Spring Boot application started");
|
||||
ctx.getBean(TerminateBean.class);
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
private static void exitApplication() {
|
||||
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
|
||||
|
||||
int exitCode = SpringApplication.exit(ctx, () -> {
|
||||
// return the error code
|
||||
return 0;
|
||||
});
|
||||
|
||||
System.out.println("Exit Spring Boot");
|
||||
|
||||
System.exit(exitCode);
|
||||
}
|
||||
|
||||
private static void writePID() {
|
||||
SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE);
|
||||
app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid"));
|
||||
app.run();
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.shutdown;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = "com.baeldung.shutdown")
|
||||
public class ShutdownConfig {
|
||||
|
||||
@Bean
|
||||
public TerminateBean getTerminateBean() {
|
||||
return new TerminateBean();
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.shutdown;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
public class TerminateBean {
|
||||
|
||||
@PreDestroy
|
||||
public void onDestroy() throws Exception {
|
||||
System.out.println("Spring Container is destroyed!");
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.shutdown.shutdown;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ShutdownController implements ApplicationContextAware {
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
@PostMapping("/shutdownContext")
|
||||
public void shutdownContext() {
|
||||
((ConfigurableApplicationContext) context).close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
|
||||
this.context = ctx;
|
||||
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.spring.boot.management.logging;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Profile("logging")
|
||||
@SpringBootApplication
|
||||
public class LoggingApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LoggingApplication.class);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.spring.boot.management.logging;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/log")
|
||||
public class LoggingController {
|
||||
private Log log = LogFactory.getLog(LoggingController.class);
|
||||
|
||||
@GetMapping
|
||||
public String log() {
|
||||
log.trace("This is a TRACE level message");
|
||||
log.debug("This is a DEBUG level message");
|
||||
log.info("This is an INFO level message");
|
||||
log.warn("This is a WARN level message");
|
||||
log.error("This is an ERROR level message");
|
||||
|
||||
return "See the log for details";
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.spring.boot.management.logging;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.ignoringAntMatchers("/actuator/**");
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.spring.boot.management.trace;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Profile("logging")
|
||||
@SpringBootApplication
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class);
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.spring.boot.management.trace;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.springframework.boot.actuate.trace.http.HttpTrace;
|
||||
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class CustomTraceRepository implements HttpTraceRepository {
|
||||
|
||||
AtomicReference<HttpTrace> lastTrace = new AtomicReference<>();
|
||||
|
||||
@Override
|
||||
public List<HttpTrace> findAll() {
|
||||
return Collections.singletonList(lastTrace.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(HttpTrace trace) {
|
||||
if ("GET".equals(trace.getRequest()
|
||||
.getMethod())) {
|
||||
lastTrace.set(trace);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.spring.boot.management.trace;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController("echo")
|
||||
public class EchoController {
|
||||
|
||||
@GetMapping
|
||||
public String echo(@RequestParam("msg") String msg) {
|
||||
return "echoing " + msg;
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.spring.boot.management.trace;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.boot.actuate.trace.http.HttpExchangeTracer;
|
||||
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
|
||||
import org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class TraceRequestFilter extends HttpTraceFilter {
|
||||
/**
|
||||
* Create a new {@link HttpTraceFilter} instance.
|
||||
*
|
||||
* @param repository the trace repository
|
||||
* @param tracer used to trace exchanges
|
||||
*/
|
||||
public TraceRequestFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) {
|
||||
super(repository, tracer);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
|
||||
return request.getServletPath().contains("actuator");
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.web.log.app;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import com.baeldung.web.log.config.CustomeRequestLoggingFilter;
|
||||
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.web.log")
|
||||
@PropertySource("application-log.properties")
|
||||
@SpringBootApplication
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStartup(ServletContext container) throws ServletException {
|
||||
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
context.setConfigLocation("com.baeldung.web.log");
|
||||
container.addListener(new ContextLoaderListener(context));
|
||||
|
||||
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context));
|
||||
dispatcher.setLoadOnStartup(1);
|
||||
dispatcher.addMapping("/");
|
||||
|
||||
container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher");
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.web.log.app;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||
|
||||
import com.baeldung.web.log.util.RequestLoggingUtil;
|
||||
|
||||
@Component
|
||||
public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter {
|
||||
|
||||
private final static Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class);
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String postData;
|
||||
HttpServletRequest requestCacheWrapperObject = null;
|
||||
try {
|
||||
// Uncomment to produce the stream closed issue
|
||||
// postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream());
|
||||
|
||||
// To overcome request stream closed issue
|
||||
requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
|
||||
requestCacheWrapperObject.getParameterMap();
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
} finally {
|
||||
postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject);
|
||||
LOGGER.info("REQUEST DATA: " + postData);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
LOGGER.info("RESPONSE: " + response.getStatus());
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.web.log.config;
|
||||
|
||||
import org.springframework.web.filter.CommonsRequestLoggingFilter;
|
||||
|
||||
public class CustomeRequestLoggingFilter extends CommonsRequestLoggingFilter {
|
||||
|
||||
public CustomeRequestLoggingFilter() {
|
||||
super.setIncludeQueryString(true);
|
||||
super.setIncludePayload(true);
|
||||
super.setMaxPayloadLength(10000);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.web.log.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.filter.CommonsRequestLoggingFilter;
|
||||
|
||||
@Configuration
|
||||
public class RequestLoggingFilterConfig {
|
||||
|
||||
@Bean
|
||||
public CommonsRequestLoggingFilter logFilter() {
|
||||
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
|
||||
filter.setIncludeQueryString(true);
|
||||
filter.setIncludePayload(true);
|
||||
filter.setMaxPayloadLength(10000);
|
||||
filter.setIncludeHeaders(false);
|
||||
filter.setAfterMessagePrefix("REQUEST DATA : ");
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.web.log.config;
|
||||
|
||||
import com.baeldung.web.log.app.TaxiFareRequestInterceptor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class TaxiFareMVCConfig implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private TaxiFareRequestInterceptor taxiFareRequestInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/");
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.web.log.controller;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
|
||||
import com.baeldung.web.log.data.RateCard;
|
||||
import com.baeldung.web.log.data.TaxiRide;
|
||||
import com.baeldung.web.log.service.TaxiFareCalculatorService;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class TaxiFareController {
|
||||
|
||||
@Autowired
|
||||
private TaxiFareCalculatorService taxiFareCalculatorService;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class);
|
||||
|
||||
@GetMapping("/taxifare/get/")
|
||||
public RateCard getTaxiFare() {
|
||||
LOGGER.debug("getTaxiFare() - START");
|
||||
return new RateCard();
|
||||
}
|
||||
|
||||
@PostMapping("/taxifare/calculate/")
|
||||
public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) {
|
||||
LOGGER.debug("calculateTaxiFare() - START");
|
||||
String totalFare = taxiFareCalculatorService.calculateFare(taxiRide);
|
||||
LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare);
|
||||
LOGGER.debug("calculateTaxiFare() - END");
|
||||
return totalFare;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.web.log.data;
|
||||
|
||||
public class RateCard {
|
||||
|
||||
private String nightSurcharge;
|
||||
private String ratePerMile;
|
||||
|
||||
public RateCard() {
|
||||
nightSurcharge = "Extra $ 100";
|
||||
ratePerMile = "$ 10 Per Mile";
|
||||
}
|
||||
|
||||
|
||||
public String getNightSurcharge() {
|
||||
return nightSurcharge;
|
||||
}
|
||||
|
||||
public void setNightSurcharge(String nightSurcharge) {
|
||||
this.nightSurcharge = nightSurcharge;
|
||||
}
|
||||
|
||||
public String getRatePerMile() {
|
||||
return ratePerMile;
|
||||
}
|
||||
|
||||
public void setRatePerMile(String ratePerMile) {
|
||||
this.ratePerMile = ratePerMile;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.web.log.data;
|
||||
|
||||
public class TaxiRide {
|
||||
|
||||
private Boolean isNightSurcharge;
|
||||
private Long distanceInMile;
|
||||
|
||||
public TaxiRide() {
|
||||
}
|
||||
|
||||
public TaxiRide(Boolean isNightSurcharge, Long distanceInMile) {
|
||||
this.isNightSurcharge = isNightSurcharge;
|
||||
this.distanceInMile = distanceInMile;
|
||||
}
|
||||
|
||||
|
||||
public Boolean getIsNightSurcharge() {
|
||||
return isNightSurcharge;
|
||||
}
|
||||
|
||||
public void setIsNightSurcharge(Boolean isNightSurcharge) {
|
||||
this.isNightSurcharge = isNightSurcharge;
|
||||
}
|
||||
|
||||
public Long getDistanceInMile() {
|
||||
return distanceInMile;
|
||||
}
|
||||
|
||||
public void setDistanceInMile(Long distanceInMile) {
|
||||
this.distanceInMile = distanceInMile;
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.web.log.service;
|
||||
|
||||
import com.baeldung.web.log.data.TaxiRide;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class TaxiFareCalculatorService {
|
||||
|
||||
public String calculateFare(TaxiRide taxiRide) {
|
||||
return String.valueOf((Long) (taxiRide.getIsNightSurcharge()
|
||||
? taxiRide.getDistanceInMile() * 10 + 100
|
||||
: taxiRide.getDistanceInMile() * 10));
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.web.log.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
public class RequestLoggingUtil {
|
||||
|
||||
public static String getStringFromInputStream(InputStream is) {
|
||||
StringWriter writer = new StringWriter();
|
||||
String encoding = "UTF-8";
|
||||
try {
|
||||
IOUtils.copy(is, writer, encoding);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return writer.toString();
|
||||
}
|
||||
|
||||
public static String readPayload(final HttpServletRequest request) throws IOException {
|
||||
String payloadData = null;
|
||||
ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
|
||||
if (null != contentCachingRequestWrapper) {
|
||||
byte[] buf = contentCachingRequestWrapper.getContentAsByteArray();
|
||||
if (buf.length > 0) {
|
||||
payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding());
|
||||
}
|
||||
}
|
||||
return payloadData;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user