repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java | package com.baeldung.resttemplate.lists.client;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.lists.dto.Employee;
import com.baeldung.resttemplate.lists.dto.EmployeeList;
/**
* Application that shows how to use Lists with RestTemplate.
*/
public class EmployeeClient {
public static void main(String[] args) {
EmployeeClient employeeClient = new EmployeeClient();
System.out.println("Calling GET for entity using arrays");
employeeClient.getForEntityEmployeesAsArray();
System.out.println("Calling GET using ParameterizedTypeReference");
employeeClient.getAllEmployeesUsingParameterizedTypeReference();
System.out.println("Calling GET using wrapper class");
employeeClient.getAllEmployeesUsingWrapperClass();
System.out.println("Calling POST using normal lists");
employeeClient.createEmployeesUsingLists();
System.out.println("Calling POST using wrapper class");
employeeClient.createEmployeesUsingWrapperClass();
}
public EmployeeClient() {
}
public Employee[] getForEntityEmployeesAsArray() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Employee[]> response =
restTemplate.getForEntity(
"http://localhost:8080/spring-rest/employees/",
Employee[].class);
Employee[] employees = response.getBody();
assert employees != null;
asList(employees).forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingParameterizedTypeReference() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response =
restTemplate.exchange(
"http://localhost:8080/spring-rest/employees/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Employee>>() {
});
List<Employee> employees = response.getBody();
assert employees != null;
employees.forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
EmployeeList response =
restTemplate.getForObject(
"http://localhost:8080/spring-rest/employees/v2",
EmployeeList.class);
List<Employee> employees = response.getEmployees();
employees.forEach(System.out::println);
return employees;
}
public void createEmployeesUsingLists() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8080/spring-rest/employees/",
newEmployees,
ResponseEntity.class);
}
public void createEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8080/spring-rest/employees/v2",
new EmployeeList(newEmployees),
ResponseEntity.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/logging/web/controller/PersonController.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/logging/web/controller/PersonController.java | package com.baeldung.resttemplate.logging.web.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@PostMapping("/persons")
public List<String> getPersons() {
return Arrays.asList(new String[] { "Lucie", "Jackie", "Danesh", "Tao" });
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/restcallscompletablefuture/Purchase.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/restcallscompletablefuture/Purchase.java | package com.baeldung.resttemplate.restcallscompletablefuture;
public class Purchase {
private String orderDescription;
private String paymentDescription;
private String buyerName;
private final String orderId;
private final String paymentId;
private final String userId;
public Purchase(String orderId, String paymentId, String userId) {
this.orderId = orderId;
this.paymentId = paymentId;
this.userId = userId;
}
public void setOrderDescription(String orderDescription) {
this.orderDescription = orderDescription;
}
public void setPaymentDescription(String paymentDescription) {
this.paymentDescription = paymentDescription;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
public String getOrderId() {
return orderId;
}
public String getPaymentId() {
return paymentId;
}
public String getUserId() {
return userId;
}
public String getOrderDescription() {
return orderDescription;
}
public String getPaymentDescription() {
return paymentDescription;
}
public String getBuyerName() {
return buyerName;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/restcallscompletablefuture/PurchaseRestCallsAsyncExecutor.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/restcallscompletablefuture/PurchaseRestCallsAsyncExecutor.java | package com.baeldung.resttemplate.restcallscompletablefuture;
import static java.lang.String.format;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class PurchaseRestCallsAsyncExecutor {
private final RestTemplate restTemplate;
private static final String BASE_URL = "https://internal-api.com";
public PurchaseRestCallsAsyncExecutor(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void updatePurchases(List<Purchase> purchases) {
purchases.forEach(this::updatePurchase);
}
public void updatePurchasesHandlingExceptions(List<Purchase> purchases) {
purchases.forEach(this::updatePurchaseHandlingExceptions);
}
public void updatePurchase(Purchase purchase) {
CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
.thenAccept(purchase::setOrderDescription),
CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
.thenAccept(purchase::setPaymentDescription),
CompletableFuture.supplyAsync(() -> getUserName(purchase.getUserId()))
.thenAccept(purchase::setBuyerName))
.join();
}
public void updatePurchaseHandlingExceptions(Purchase purchase) {
CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
.thenAccept(purchase::setOrderDescription)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()),
CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
.thenAccept(purchase::setPaymentDescription)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()),
CompletableFuture.supplyAsync(() -> getUserName(purchase.getUserId()))
.thenAccept(purchase::setBuyerName)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()))
.join();
}
public String getOrderDescription(String orderId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/orders/%s", BASE_URL, orderId), String.class);
return result.getBody();
}
public String getPaymentDescription(String paymentId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/payments/%s", BASE_URL, paymentId), String.class);
return result.getBody();
}
public String getUserName(String userId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/users/%s", BASE_URL, userId), String.class);
return result.getBody();
}
private static BiFunction<Void, Throwable, Void> handleGracefully() {
return (result, exception) -> {
if (exception != null) {
// handle exception
return null;
}
return result;
};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java | package com.baeldung.resttemplate.web.controller;
import jakarta.servlet.http.HttpServletResponse;
import com.baeldung.resttemplate.web.service.PersonService;
import com.baeldung.resttemplate.web.dto.Person;
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 org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
public class PersonAPI {
@Autowired
private PersonService personService;
@GetMapping("/")
public String home() {
return "Spring boot is working!";
}
@PostMapping(value = "/createPerson", consumes = "application/json", produces = "application/json")
public Person createPerson(@RequestBody Person person) {
return personService.saveUpdatePerson(person);
}
@PostMapping(value = "/updatePerson", consumes = "application/json", produces = "application/json")
public Person updatePerson(@RequestBody Person person, HttpServletResponse response) {
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findPerson/" + person.getId())
.toUriString());
return personService.saveUpdatePerson(person);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/redirect/RedirectController.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/redirect/RedirectController.java | package com.baeldung.resttemplate.web.controller.redirect;
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;
import jakarta.servlet.http.HttpServletRequest;
@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");
}
@RequestMapping(value="/forwardWithParams", method = RequestMethod.GET)
public ModelAndView forwardWithParams(HttpServletRequest request) {
request.setAttribute("param1", "one");
request.setAttribute("param2", "two");
return new ModelAndView("forward:/forwardedWithParams");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/redirect/RedirectParamController.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/redirect/RedirectParamController.java | package com.baeldung.resttemplate.web.controller.redirect;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import jakarta.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/")
public class RedirectParamController {
@RequestMapping(value = "/forwardedWithParams", method = RequestMethod.GET)
public RedirectView forwardedWithParams(final RedirectAttributes redirectAttributes, HttpServletRequest request) {
redirectAttributes.addAttribute("param1", request.getAttribute("param1"));
redirectAttributes.addAttribute("param2", request.getAttribute("param2"));
redirectAttributes.addAttribute("attribute", "forwardedWithParams");
return new RedirectView("redirectedUrl");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/https/WelcomeController.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/https/WelcomeController.java | package com.baeldung.resttemplate.web.https;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WelcomeController {
@GetMapping(value = "/welcome")
public String welcome() {
return "Welcome To Secured REST Service";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/https/HttpsEnabledApplication.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/https/HttpsEnabledApplication.java | package com.baeldung.resttemplate.web.https;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan(basePackages = "com.baeldung.web.https")
@PropertySource("classpath:application.properties")
@SpringBootApplication
public class HttpsEnabledApplication {
public static void main(String... args) {
SpringApplication application = new SpringApplication(HttpsEnabledApplication.class);
application.setAdditionalProfiles("ssl");
application.run(args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/dto/Person.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/dto/Person.java | package com.baeldung.resttemplate.web.dto;
public class Person {
private Integer id;
private String name;
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java | package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.dto.Person;
public interface PersonService {
public Person saveUpdatePerson(Person person);
public Person findPersonById(Integer id);
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java | package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.dto.Person;
import org.springframework.stereotype.Component;
@Component
public class PersonServiceImpl implements PersonService {
@Override
public Person saveUpdatePerson(Person person) {
return person;
}
@Override
public Person findPersonById(Integer id) {
return new Person(id, "John");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/controller/FileServerResource.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/controller/FileServerResource.java | package com.baeldung.resttemplate.web.upload.controller;
import java.io.IOException;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
@RestController
@RequestMapping("/fileserver")
public class FileServerResource {
@RequestMapping(path = "/singlefileupload/", method = RequestMethod.POST)
public ResponseEntity<String> processFile(@RequestParam("file") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
System.out.println("File Name: " + file.getOriginalFilename());
System.out.println("File Content Type: " + file.getContentType());
System.out.println("File Content:\n" + new String(bytes));
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
}
@RequestMapping(path = "/multiplefileupload/", method = RequestMethod.POST)
public ResponseEntity<String> processFile(@RequestParam("files") List<MultipartFile> files) throws IOException {
for (MultipartFile file : files) {
byte[] bytes = file.getBytes();
System.out.println("File Name: " + file.getOriginalFilename());
System.out.println("File Content Type: " + file.getContentType());
System.out.println("File Content:\n" + new String(bytes));
}
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/app/UploadApplication.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/app/UploadApplication.java | package com.baeldung.resttemplate.web.upload.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.resttemplate.web.upload")
@SpringBootApplication
public class UploadApplication extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(UploadApplication.class, args);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/client/MultipartFileUploadClient.java | spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/upload/client/MultipartFileUploadClient.java | package com.baeldung.resttemplate.web.upload.client;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class MultipartFileUploadClient {
public static void main(String[] args) throws IOException {
uploadSingleFile();
uploadMultipleFile();
}
private static void uploadSingleFile() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8080/spring-rest/fileserver/singlefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
System.out.println("Response code: " + response.getStatusCode());
}
private static void uploadMultipleFile() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("files", getTestFile());
body.add("files", getTestFile());
body.add("files", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8080/spring-rest/fileserver/multiplefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
System.out.println("Response code: " + response.getStatusCode());
}
public static Resource getTestFile() throws IOException {
Path testFile = Files.createTempFile("test-file", ".txt");
System.out.println("Creating and Uploading Test File: " + testFile);
Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
return new FileSystemResource(testFile.toFile());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java | spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java | package com.baeldung.accessparamsjs;
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;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@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());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/filters/HttpRequestUnitTest.java | spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/filters/HttpRequestUnitTest.java | package com.baeldung.filters;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.util.ContentCachingRequestWrapper;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class HttpRequestUnitTest {
@Test
public void givenHttpServletRequest_whenCalling_getReaderAfter_getInputStream_thenThrowIllegalStateException() throws IOException {
HttpServletRequest request = new MockHttpServletRequest();
try (ServletInputStream ignored = request.getInputStream()) {
IllegalStateException exception = assertThrows(IllegalStateException.class, request::getReader);
assertEquals("Cannot call getReader() after getInputStream() has already been called for the current request",
exception.getMessage());
}
}
@Test
public void givenServletRequest_whenDoFilter_thenCanCallBoth() throws ServletException, IOException {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
Filter filter = new CacheRequestContentFilter();
filter.doFilter(req, res, chain);
ServletRequest request = chain.getRequest();
assertTrue(request instanceof ContentCachingRequestWrapper);
// now we can call both getInputStream() and getReader()
request.getInputStream();
request.getReader();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/accessparamsjs/Controller.java | spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/accessparamsjs/Controller.java | package com.baeldung.accessparamsjs;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* 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");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/accessparamsjs/App.java | spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/accessparamsjs/App.java | 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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/filters/CacheRequestContentFilter.java | spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/filters/CacheRequestContentFilter.java | package com.baeldung.filters;
import org.springframework.web.util.ContentCachingRequestWrapper;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class CacheRequestContentFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
if (request instanceof HttpServletRequest) {
String contentType = request.getContentType();
if (contentType == null || !contentType.contains("multipart/form-data")) {
request = new ContentCachingRequestWrapper((HttpServletRequest) request);
}
}
chain.doFilter(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java | spring-web-modules/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java | package com.baeldung.mvc.velocity.test;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.mvc.velocity.spring.config.WebConfig;
import com.baeldung.mvc.velocity.test.config.TestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
@ContextConfiguration(classes = { TestConfig.class, WebConfig.class })
@WebAppConfiguration
public class DataContentControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void whenCallingList_ThenModelAndContentOK() throws Exception {
mockMvc.perform(get("/list")).andExpect(status().isOk()).andExpect(view().name("list")).andExpect(model().attribute("tutorials", hasSize(2)))
.andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")), hasProperty("title", is("Guava"))))))
.andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android"))))));
mockMvc.perform(get("/list")).andExpect(xpath("//table").exists());
mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists());
}
@Test
public void whenCallingIndex_thenViewOK() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java | spring-web-modules/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java | package com.baeldung.mvc.velocity.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
public class TestConfig {
@Bean
public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
bean.setCache(true);
bean.setPrefix("/WEB-INF/views/");
bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
bean.setSuffix(".vm");
return bean;
}
@Bean
public VelocityConfigurer velocityConfig() {
VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
velocityConfigurer.setResourceLoaderPath("/");
return velocityConfigurer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java | spring-web-modules/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java | package com.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.mvc.velocity.spring.config.WebConfig;
import com.baeldung.mvc.velocity.test.config.TestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class, WebConfig.class })
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java | package com.baeldung.mvc.velocity.controller;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller
@RequestMapping("/")
public class MainController {
@Autowired
private ITutorialsService tutService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String welcomePage() {
return "index";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listTutorialsPage(Model model) {
List<Tutorial> list = tutService.listTutorials();
model.addAttribute("tutorials", list);
return "list";
}
public ITutorialsService getTutService() {
return tutService;
}
public void setTutService(ITutorialsService tutService) {
this.tutService = tutService;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java | package com.baeldung.mvc.velocity.service;
import com.baeldung.mvc.velocity.domain.Tutorial;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class TutorialsService implements ITutorialsService {
public List<Tutorial> listTutorials() {
return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java | package com.baeldung.mvc.velocity.service;
import com.baeldung.mvc.velocity.domain.Tutorial;
import java.util.List;
public interface ITutorialsService {
List<Tutorial> listTutorials();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java | package com.baeldung.mvc.velocity.domain;
public class Tutorial {
private final Integer tutId;
private final String title;
private final String description;
private final String author;
public Tutorial(Integer tutId, String title, String description, String author) {
this.tutId = tutId;
this.title = title;
this.description = description;
this.author = author;
}
public Integer getTutId() {
return tutId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getAuthor() {
return author;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java | package com.baeldung.mvc.velocity.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
bean.setCache(true);
bean.setPrefix("/WEB-INF/views/");
bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
bean.setSuffix(".vm");
return bean;
}
@Bean
public VelocityConfigurer velocityConfig() {
VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
velocityConfigurer.setResourceLoaderPath("/");
return velocityConfigurer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java | spring-web-modules/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java | package com.baeldung.mvc.velocity.spring.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;
public class MainWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/test/java/com/baeldung/hateoasvsswagger/HateoasControllerIntegrationTest.java | spring-web-modules/spring-boot-rest-2/src/test/java/com/baeldung/hateoasvsswagger/HateoasControllerIntegrationTest.java | package com.baeldung.hateoasvsswagger;
import com.baeldung.hateoasvsswagger.model.NewUser;
import com.baeldung.hateoasvsswagger.model.User;
import com.baeldung.hateoasvsswagger.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(UserHateoasController.class)
@AutoConfigureMockMvc
class HateoasControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userService;
@Test
void whenAllUsersRequested_thenReturnAllUsersWithLinks() throws Exception {
User user1 = new User(1, "John Doe", "john.doe@example.com", LocalDateTime.now());
User user2 = new User(2, "Jane Smith", "jane.smith@example.com", LocalDateTime.now());
when(userService.getAllUsers()).thenReturn(List.of(user1, user2));
mockMvc.perform(get("/api/hateoas/users").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.userList[0].id").value(1))
.andExpect(jsonPath("$._embedded.userList[0].name").value("John Doe"))
.andExpect(jsonPath("$._embedded.userList[0]._links.self.href").exists())
.andExpect(jsonPath("$._embedded.userList[1].id").value(2))
.andExpect(jsonPath("$._embedded.userList[1].name").value("Jane Smith"))
.andExpect(jsonPath("$._links.self.href").exists());
}
@Test
void whenUserByIdRequested_thenReturnUserByIdWithLinks() throws Exception {
User user = new User(1, "John Doe", "john.doe@example.com", LocalDateTime.now());
when(userService.getUserById(1)).thenReturn(user);
mockMvc.perform(get("/api/hateoas/users/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.email").value("john.doe@example.com"))
.andExpect(jsonPath("$._links.self.href").exists())
.andExpect(jsonPath("$._links.all-users.href").exists());
}
@Test
void whenUserCreationRequested_thenReturnUserByIdWithLinks() throws Exception {
User user = new User(1, "John Doe", "john.doe@example.com", LocalDateTime.now());
when(userService.createUser(any(NewUser.class))).thenReturn(user);
mockMvc.perform(post("/api/hateoas/users").contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$._links.self.href").exists());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/UserHateoasController.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/UserHateoasController.java | package com.baeldung.hateoasvsswagger;
import com.baeldung.hateoasvsswagger.model.NewUser;
import com.baeldung.hateoasvsswagger.model.User;
import com.baeldung.hateoasvsswagger.repository.UserRepository;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@RestController
@RequestMapping("/api/hateoas/users")
public class UserHateoasController {
private final UserRepository userService; // Assume a service layer handles business logic
public UserHateoasController(UserRepository userService) {
this.userService = userService;
}
@GetMapping
public CollectionModel<User> getAllUsers() {
List<User> users = userService.getAllUsers();
users.forEach(user -> {
user.add(linkTo(methodOn(UserController.class).getUserById(user.getId())).withSelfRel());
});
return CollectionModel.of(users, linkTo(methodOn(UserController.class).getAllUsers()).withSelfRel());
}
@GetMapping("/{id}")
public EntityModel<User> getUserById(@PathVariable Integer id) {
User user = userService.getUserById(id);
user.add(linkTo(methodOn(UserController.class).getUserById(id)).withSelfRel());
user.add(linkTo(methodOn(UserController.class).getAllUsers()).withRel("all-users"));
return EntityModel.of(user);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EntityModel<User>> createUser(@RequestBody NewUser user) {
User createdUser = userService.createUser(user);
createdUser.add(linkTo(methodOn(UserController.class).getUserById(createdUser.getId())).withSelfRel());
return ResponseEntity.created(linkTo(methodOn(UserController.class).getUserById(createdUser.getId())).toUri())
.body(EntityModel.of(createdUser));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/UserController.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/UserController.java | package com.baeldung.hateoasvsswagger;
import com.baeldung.hateoasvsswagger.model.NewUser;
import com.baeldung.hateoasvsswagger.model.User;
import com.baeldung.hateoasvsswagger.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository = new UserRepository();
@Operation(summary = "Get all users", description = "Retrieve a list of all users")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "List of users", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "500", description = "Internal server error") })
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok()
.body(userRepository.getAllUsers());
}
@Operation(summary = "Create a new user", description = "Add a new user to the system")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "User created", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Invalid input") })
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> createUser(
@RequestBody(description = "User data", required = true, content = @Content(schema = @Schema(implementation = NewUser.class))) NewUser user) {
return new ResponseEntity<>(userRepository.createUser(user), HttpStatus.CREATED);
}
@Operation(summary = "Get user by ID", description = "Retrieve a user by their unique ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User found", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "404", description = "User not found") })
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Integer id) {
return ResponseEntity.ok()
.body(userRepository.getUserById(id));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/SpringBootRestApplication.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/SpringBootRestApplication.java | package com.baeldung.hateoasvsswagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/model/NewUser.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/model/NewUser.java | package com.baeldung.hateoasvsswagger.model;
public record NewUser(String name, String email) {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/model/User.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/model/User.java | package com.baeldung.hateoasvsswagger.model;
import org.springframework.hateoas.RepresentationModel;
import java.time.LocalDateTime;
public class User extends RepresentationModel<User> {
private Integer id;
private String name;
private String email;
private LocalDateTime createdAt;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public User(int id, String name, String email, LocalDateTime createdAt) {
this.id = id;
this.name = name;
this.email = email;
this.createdAt = createdAt;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/repository/UserRepository.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoasvsswagger/repository/UserRepository.java | package com.baeldung.hateoasvsswagger.repository;
import com.baeldung.hateoasvsswagger.model.NewUser;
import com.baeldung.hateoasvsswagger.model.User;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class UserRepository {
private final Map<Integer, User> users = new HashMap<>();
public UserRepository() {
users.put(1, new User(1, "Baeldung", "baeldung@gmail.com", LocalDateTime.now()));
}
public List<User> getAllUsers() {
return users.values().stream().map(u -> new User(u.getId(), u.getName(), u.getEmail(), LocalDateTime.now())).toList();
}
public User getUserById(int id) {
return users.get(id);
}
public User createUser(NewUser user) {
int id = users.size() + 1;
return users.put(id, new User(id, user.name(), user.email(), LocalDateTime.now()));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/OrderService.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/OrderService.java | package com.baeldung.hateoas.services;
import java.util.List;
import com.baeldung.hateoas.persistence.model.Order;
public interface OrderService {
List<Order> getAllOrdersForCustomer(String customerId);
Order getOrderByIdForCustomer(String customerId, String orderId);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/CustomerServiceImpl.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/CustomerServiceImpl.java | package com.baeldung.hateoas.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.hateoas.persistence.model.Customer;
@Service
public class CustomerServiceImpl implements CustomerService {
private HashMap<String, Customer> customerMap;
public CustomerServiceImpl() {
customerMap = new HashMap<>();
final Customer customerOne = new Customer("10A", "Jane", "ABC Company");
final Customer customerTwo = new Customer("20B", "Bob", "XYZ Company");
final Customer customerThree = new Customer("30C", "Tim", "CKV Company");
customerMap.put("10A", customerOne);
customerMap.put("20B", customerTwo);
customerMap.put("30C", customerThree);
}
@Override
public List<Customer> allCustomers() {
return new ArrayList<>(customerMap.values());
}
@Override
public Customer getCustomerDetail(final String customerId) {
return customerMap.get(customerId);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/OrderServiceImpl.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/OrderServiceImpl.java | package com.baeldung.hateoas.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.baeldung.hateoas.persistence.model.Customer;
import com.baeldung.hateoas.persistence.model.Order;
@Service
public class OrderServiceImpl implements OrderService {
private HashMap<String, Customer> customerMap;
private HashMap<String, Order> customerOneOrderMap;
private HashMap<String, Order> customerTwoOrderMap;
private HashMap<String, Order> customerThreeOrderMap;
public OrderServiceImpl() {
customerMap = new HashMap<>();
customerOneOrderMap = new HashMap<>();
customerTwoOrderMap = new HashMap<>();
customerThreeOrderMap = new HashMap<>();
customerOneOrderMap.put("001A", new Order("001A", 150.00, 25));
customerOneOrderMap.put("002A", new Order("002A", 250.00, 15));
customerTwoOrderMap.put("002B", new Order("002B", 550.00, 325));
customerTwoOrderMap.put("002B", new Order("002B", 450.00, 525));
final Customer customerOne = new Customer("10A", "Jane", "ABC Company");
final Customer customerTwo = new Customer("20B", "Bob", "XYZ Company");
final Customer customerThree = new Customer("30C", "Tim", "CKV Company");
customerOne.setOrders(customerOneOrderMap);
customerTwo.setOrders(customerTwoOrderMap);
customerThree.setOrders(customerThreeOrderMap);
customerMap.put("10A", customerOne);
customerMap.put("20B", customerTwo);
customerMap.put("30C", customerThree);
}
@Override
public List<Order> getAllOrdersForCustomer(final String customerId) {
return new ArrayList<>(customerMap.get(customerId).getOrders().values());
}
@Override
public Order getOrderByIdForCustomer(final String customerId, final String orderId) {
final Map<String, Order> orders = customerMap.get(customerId).getOrders();
Order selectedOrder = orders.get(orderId);
return selectedOrder;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/CustomerService.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/services/CustomerService.java | package com.baeldung.hateoas.services;
import java.util.List;
import com.baeldung.hateoas.persistence.model.Customer;
public interface CustomerService {
List<Customer> allCustomers();
Customer getCustomerDetail(final String id);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/util/RestPreconditions.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/util/RestPreconditions.java | package com.baeldung.hateoas.util;
import org.springframework.http.HttpStatus;
import com.baeldung.hateoas.web.exception.MyResourceNotFoundException;
/**
* Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown
*/
public final class RestPreconditions {
private RestPreconditions() {
throw new AssertionError();
}
// API
/**
* Check if some value was found, otherwise throw exception.
*
* @param expression
* has value true if found, otherwise false
* @throws MyResourceNotFoundException
* if expression is false, means value not found.
*/
public static void checkFound(final boolean expression) {
if (!expression) {
throw new MyResourceNotFoundException();
}
}
/**
* Check if some value was found, otherwise throw exception.
*
* @param expression
* has value true if found, otherwise false
* @throws MyResourceNotFoundException
* if expression is false, means value not found.
*/
public static <T> T checkFound(final T resource) {
if (resource == null) {
throw new MyResourceNotFoundException();
}
return resource;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/util/LinkUtil.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/util/LinkUtil.java | package com.baeldung.hateoas.util;
import jakarta.servlet.http.HttpServletResponse;
/**
* Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object
*/
public final class LinkUtil {
public static final String REL_COLLECTION = "collection";
public static final String REL_NEXT = "next";
public static final String REL_PREV = "prev";
public static final String REL_FIRST = "first";
public static final String REL_LAST = "last";
private LinkUtil() {
throw new AssertionError();
}
//
/**
* Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user
*
* @param uri
* the base uri
* @param rel
* the relative path
*
* @return the complete url
*/
public static String createLinkHeader(final String uri, final String rel) {
return "<" + uri + ">; rel=\"" + rel + "\"";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/IOperations.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/IOperations.java | package com.baeldung.hateoas.persistence;
import java.io.Serializable;
import java.util.List;
public interface IOperations<T extends Serializable> {
// read - one
T findById(final long id);
// read - all
List<T> findAll();
// write
T create(final T entity);
T update(final T entity);
void delete(final T entity);
void deleteById(final long entityId);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/dao/IFooDao.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/dao/IFooDao.java | package com.baeldung.hateoas.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.hateoas.persistence.model.Foo;
public interface IFooDao extends JpaRepository<Foo, Long> {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/IFooService.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/IFooService.java | package com.baeldung.hateoas.persistence.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.baeldung.hateoas.persistence.IOperations;
import com.baeldung.hateoas.persistence.model.Foo;
public interface IFooService extends IOperations<Foo> {
Page<Foo> findPaginated(Pageable pageable);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/impl/FooService.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/impl/FooService.java | package com.baeldung.hateoas.persistence.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.hateoas.persistence.dao.IFooDao;
import com.baeldung.hateoas.persistence.model.Foo;
import com.baeldung.hateoas.persistence.service.IFooService;
import com.baeldung.hateoas.persistence.service.common.AbstractService;
import com.google.common.collect.Lists;
@Service
@Transactional
public class FooService extends AbstractService<Foo> implements IFooService {
@Autowired
private IFooDao dao;
public FooService() {
super();
}
// API
@Override
protected JpaRepository<Foo, Long> getDao() {
return dao;
}
// custom methods
@Override
public Page<Foo> findPaginated(Pageable pageable) {
return dao.findAll(pageable);
}
// overridden to be secured
@Override
@Transactional(readOnly = true)
public List<Foo> findAll() {
return Lists.newArrayList(getDao().findAll());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/common/AbstractService.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/service/common/AbstractService.java | package com.baeldung.hateoas.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.hateoas.persistence.IOperations;
import com.google.common.collect.Lists;
@Transactional
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
// read - one
@Override
@Transactional(readOnly = true)
public T findById(final long id) {
return getDao().findById(id).orElse(null);
}
// read - all
@Override
@Transactional(readOnly = true)
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
// write
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override
public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract JpaRepository<T, Long> getDao();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Foo.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Foo.java | package com.baeldung.hateoas.persistence.model;
import java.io.Serializable;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Version;
@XStreamAlias("Foo")
@Entity
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
private String name;
@Version
private long version;
public Foo() {
super();
}
public Foo(final String name) {
super();
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;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Customer.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Customer.java | package com.baeldung.hateoas.persistence.model;
import java.util.Map;
import org.springframework.hateoas.RepresentationModel;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class Customer extends RepresentationModel<Customer> {
private String customerId;
private String customerName;
private String companyName;
private Map<String, Order> orders;
public Customer() {
super();
}
public Customer(final String customerId, final String customerName, final String companyName) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.companyName = companyName;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(final String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(final String customerName) {
this.customerName = customerName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
public Map<String, Order> getOrders() {
return orders;
}
public void setOrders(final Map<String, Order> orders) {
this.orders = orders;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Order.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/persistence/model/Order.java | package com.baeldung.hateoas.persistence.model;
import org.springframework.hateoas.RepresentationModel;
public class Order extends RepresentationModel<Order> {
private String orderId;
private double price;
private int quantity;
public Order() {
super();
}
public Order(final String orderId, final double price, final int quantity) {
super();
this.orderId = orderId;
this.price = price;
this.quantity = quantity;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(final String orderId) {
this.orderId = orderId;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(final int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", price=" + price + ", quantity=" + quantity + "]";
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/ResourceCreatedEvent.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/ResourceCreatedEvent.java | package com.baeldung.hateoas.event;
import org.springframework.context.ApplicationEvent;
import jakarta.servlet.http.HttpServletResponse;
public class ResourceCreatedEvent extends ApplicationEvent {
private final HttpServletResponse response;
private final long idOfNewResource;
public ResourceCreatedEvent(final Object source, final HttpServletResponse response, final long idOfNewResource) {
super(source);
this.response = response;
this.idOfNewResource = idOfNewResource;
}
// API
public HttpServletResponse getResponse() {
return response;
}
public long getIdOfNewResource() {
return idOfNewResource;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/PaginatedResultsRetrievedEvent.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/PaginatedResultsRetrievedEvent.java | package com.baeldung.hateoas.event;
import java.io.Serializable;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.util.UriComponentsBuilder;
import jakarta.servlet.http.HttpServletResponse;
/**
* Event that is fired when a paginated search is performed.
* <p/>
* This event object contains all the information needed to create the URL for the paginated results
*
* @param <T>
* Type of the result that is being handled (commonly Entities).
*/
public final class PaginatedResultsRetrievedEvent<T extends Serializable> extends ApplicationEvent {
private final UriComponentsBuilder uriBuilder;
private final HttpServletResponse response;
private final int page;
private final int totalPages;
private final int pageSize;
public PaginatedResultsRetrievedEvent(final Class<T> clazz, final UriComponentsBuilder uriBuilderToSet, final HttpServletResponse responseToSet, final int pageToSet, final int totalPagesToSet, final int pageSizeToSet) {
super(clazz);
uriBuilder = uriBuilderToSet;
response = responseToSet;
page = pageToSet;
totalPages = totalPagesToSet;
pageSize = pageSizeToSet;
}
// API
public final UriComponentsBuilder getUriBuilder() {
return uriBuilder;
}
public final HttpServletResponse getResponse() {
return response;
}
public final int getPage() {
return page;
}
public final int getTotalPages() {
return totalPages;
}
public final int getPageSize() {
return pageSize;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
@SuppressWarnings("unchecked")
public final Class<T> getClazz() {
return (Class<T>) getSource();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/SingleResourceRetrievedEvent.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/event/SingleResourceRetrievedEvent.java | package com.baeldung.hateoas.event;
import org.springframework.context.ApplicationEvent;
import jakarta.servlet.http.HttpServletResponse;
public class SingleResourceRetrievedEvent extends ApplicationEvent {
private final HttpServletResponse response;
public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) {
super(source);
this.response = response;
}
// API
public HttpServletResponse getResponse() {
return response;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java | package com.baeldung.hateoas.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.baeldung.hateoas.event.SingleResourceRetrievedEvent;
import com.baeldung.hateoas.util.LinkUtil;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
import jakarta.servlet.http.HttpServletResponse;
@Component
class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener<SingleResourceRetrievedEvent> {
@Override
public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) {
Preconditions.checkNotNull(resourceRetrievedEvent);
final HttpServletResponse response = resourceRetrievedEvent.getResponse();
addLinkHeaderOnSingleResourceRetrieval(response);
}
void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) {
final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString();
final int positionOfLastSlash = requestURL.lastIndexOf("/");
final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash);
final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection");
response.addHeader(HttpHeaders.LINK, linkHeaderValue);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/listener/ResourceCreatedDiscoverabilityListener.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/listener/ResourceCreatedDiscoverabilityListener.java | package com.baeldung.hateoas.listener;
import java.net.URI;
import org.apache.http.HttpHeaders;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.baeldung.hateoas.event.ResourceCreatedEvent;
import com.google.common.base.Preconditions;
import jakarta.servlet.http.HttpServletResponse;
@Component
class ResourceCreatedDiscoverabilityListener implements ApplicationListener<ResourceCreatedEvent> {
@Override
public void onApplicationEvent(final ResourceCreatedEvent resourceCreatedEvent) {
Preconditions.checkNotNull(resourceCreatedEvent);
final HttpServletResponse response = resourceCreatedEvent.getResponse();
final long idOfNewResource = resourceCreatedEvent.getIdOfNewResource();
addLinkHeaderOnResourceCreation(response, idOfNewResource);
}
void addLinkHeaderOnResourceCreation(final HttpServletResponse response, final long idOfNewResource) {
// final String requestUrl = request.getRequestURL().toString();
// final URI uri = new UriTemplate("{requestUrl}/{idOfNewResource}").expand(requestUrl, idOfNewResource);
final URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{idOfNewResource}").buildAndExpand(idOfNewResource).toUri();
response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/controller/FooController.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/controller/FooController.java | package com.baeldung.hateoas.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.baeldung.hateoas.event.ResourceCreatedEvent;
import com.baeldung.hateoas.event.SingleResourceRetrievedEvent;
import com.baeldung.hateoas.persistence.model.Foo;
import com.baeldung.hateoas.persistence.service.IFooService;
import com.baeldung.hateoas.web.exception.MyResourceNotFoundException;
import com.baeldung.hateoas.util.RestPreconditions;
import com.google.common.base.Preconditions;
import jakarta.servlet.http.HttpServletResponse;
@RestController
@RequestMapping(value = "/foos")
public class FooController {
private static final Logger logger = LoggerFactory.getLogger(FooController.class);
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private IFooService service;
public FooController() {
super();
}
// read - one
@GetMapping(value = "/{id}")
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
try {
final Foo resourceById = RestPreconditions.checkFound(service.findById(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
catch (MyResourceNotFoundException exc) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Foo Not Found", exc);
}
}
// write
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/controller/RootController.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/controller/RootController.java | package com.baeldung.hateoas.web.controller;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriTemplate;
import com.baeldung.hateoas.util.LinkUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Controller
public class RootController {
// API
// discover
@GetMapping("/")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL()
.toString();
final URI fooUri = new UriTemplate("{rootUri}{resource}").expand(rootUri, "foos");
final String linkToFoos = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoos);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/exception/MyResourceNotFoundException.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/hateoas/web/exception/MyResourceNotFoundException.java | package com.baeldung.hateoas.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public final class MyResourceNotFoundException extends RuntimeException {
public MyResourceNotFoundException() {
super();
}
public MyResourceNotFoundException(final String message, final Throwable cause) {
super(message, cause);
}
public MyResourceNotFoundException(final String message) {
super(message);
}
public MyResourceNotFoundException(final Throwable cause) {
super(cause);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/Book.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/Book.java | package com.baeldung.smartdoc;
public class Book {
/**
* Book ID
*/
private Long id;
/**
* Author
*/
private String author;
/**
* Book Title
*/
private String title;
/**
* Book Price
*/
private Double price;
public Book() {
}
public Book(Long id, String author, String title, Double price) {
this.id = id;
this.author = author;
this.title = title;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookController.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookController.java | package com.baeldung.smartdoc;
import java.util.List;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
/**
* The type Book controller.
*
* @author Baeldung.
*/
@RestController
@RequestMapping("/api/v1")
public class BookController {
@Autowired
private BookRepository bookRepository;
/**
* Create book.
*
* @param book the book
* @return the book
*/
@PostMapping("/books")
public ResponseEntity<Book> createBook(@RequestBody Book book) {
bookRepository.add(book);
return ResponseEntity.ok(book);
}
/**
* Get all books.
*
* @return the list
*/
@GetMapping("/books")
public ResponseEntity<List<Book>> getAllBooks() {
return ResponseEntity.ok(bookRepository.getBooks());
}
/**
* Gets book by id.
*
* @param bookId the book id|1
* @return the book by id
*/
@GetMapping("/book/{id}")
public ResponseEntity<Book> getBookById(@PathVariable(value = "id") Long bookId) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
return ResponseEntity.ok(book);
}
/**
* Update book response entity.
*
* @param bookId the book id|1
* @param bookDetails the book details
* @return the response entity
*/
@PutMapping("/books/{id}")
public ResponseEntity<Book> updateBook(@PathVariable(value = "id") Long bookId, @Valid @RequestBody Book bookDetails) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
book.setAuthor(bookDetails.getAuthor());
book.setPrice(bookDetails.getPrice());
book.setTitle(bookDetails.getTitle());
bookRepository.add(book);
return ResponseEntity.ok(book);
}
/**
* Delete book.
*
* @param bookId the book id|1
* @return the true
*/
@DeleteMapping("/book/{id}")
public ResponseEntity<Boolean> deleteBook(@PathVariable(value = "id") Long bookId) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
return ResponseEntity.ok(bookRepository.delete(book));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookApplication.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookApplication.java | package com.baeldung.smartdoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookApplication {
public static void main(String[] args) {
SpringApplication.run(BookApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookRepository.java | spring-web-modules/spring-boot-rest-2/src/main/java/com/baeldung/smartdoc/BookRepository.java | package com.baeldung.smartdoc;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepository {
private static final Map<Long, Book> books = new ConcurrentHashMap<>();
static {
Book book = new Book(1L, "George Martin", "A Song of Ice and Fire", 10000.00);
books.put(1L, book);
}
public Optional<Book> findById(long id) {
return Optional.ofNullable(books.get(id));
}
public void add(Book book) {
books.put(book.getId(), book);
}
public List<Book> getBooks() {
return new ArrayList<>(books.values());
}
public boolean delete(Book book) {
return books.remove(book.getId(), book);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java | package com.baeldung;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.baeldung")
public class SpringTestConfig {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java | package com.baeldung;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.resttemplate.RestTemplateConfigurationApplication;
@SpringBootTest(classes= RestTemplateConfigurationApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java | package com.baeldung.resttemplate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.RestTemplate;
import com.baeldung.sampleapp.config.RestClientConfig;
import com.baeldung.transfer.LoginForm;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = RestClientConfig.class)
public class RestTemplateLiveTest {
@Autowired
RestTemplate restTemplate;
@Test
public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() {
LoginForm loginForm = new LoginForm("userName", "password");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<LoginForm> requestEntity = new HttpEntity<LoginForm>(loginForm, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class);
Assertions.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
Assertions.assertEquals(responseEntity.getHeaders()
.get("Foo")
.get(0), "bar");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java | package com.baeldung.resttemplate;
import java.util.Base64;
import static com.baeldung.client.Consts.APPLICATION_PORT;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Set;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.dto.Foo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RequestCallback;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.core5.util.Timeout;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestTemplate;
import com.google.common.base.Charsets;
// This test needs RestTemplateConfigurationApplication to be up and running
public class RestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
@BeforeEach
public void beforeTest() {
restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
// restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
}
// GET
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
final ResponseEntity<Foo> response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
final RestTemplate template = new RestTemplate();
final ResponseEntity<String> response = template.getForEntity(fooResourceUrl + "/1", String.class);
final ObjectMapper mapper = new ObjectMapper();
final JsonNode root = mapper.readTree(response.getBody());
final JsonNode name = root.path("name");
Assertions.assertNotNull(name.asText());
}
@Test
public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException {
final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
Assertions.assertNotNull(foo.getName());
Assertions.assertEquals(foo.getId(), 1L);
}
// HEAD, OPTIONS
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
Assertions.assertTrue(httpHeaders.getContentType()
.includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
Assertions.assertNotNull(foo);
Assertions.assertEquals(foo.getName(), "bar");
}
@Test
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final URI location = restTemplate.postForLocation(fooResourceUrl, request, Foo.class);
Assertions.assertNotNull(location);
}
@Test
public void givenFooService_whenPostResource_thenResourceIsCreated() {
final Foo foo = new Foo("bar");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final Foo fooResponse = response.getBody();
Assertions.assertNotNull(fooResponse);
Assertions.assertEquals(fooResponse.getName(), "bar");
}
@Test
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
Assertions.assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
// PUT
@Test
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
Assertions.assertEquals(foo.getName(), updatedInstance.getName());
}
@Test
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create entity
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
// Update entity
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(response.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + response.getBody()
.getId();
restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
// Check that entity was updated
response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = response.getBody();
Assertions.assertEquals(foo.getName(), updatedInstance.getName());
}
// PATCH
@Test
public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedResource = new Foo("newName");
updatedResource.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers);
final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
final ClientHttpRequestFactory requestFactoryAlternate = getClientHttpRequestFactoryAlternate();
final RestTemplate template = new RestTemplate(requestFactory);
template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
template.patchForObject(resourceUrl, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
Assertions.assertEquals(foo.getName(), updatedResource.getName());
}
// DELETE
@Test
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
final Foo foo = new Foo("remove me");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final String entityUrl = fooResourceUrl + "/" + response.getBody()
.getId();
restTemplate.delete(entityUrl);
try {
restTemplate.getForEntity(entityUrl, Foo.class);
fail();
} catch (final HttpClientErrorException ex) {
Assertions.assertEquals(ex.getStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Test
public void givenFooService_whenFormSubmit_thenResourceIsCreated() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "10");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final String fooResponse = response.getBody();
Assertions.assertNotNull(fooResponse);
Assertions.assertEquals(fooResponse, "10");
}
private HttpHeaders prepareBasicAuthHeaders() {
final HttpHeaders headers = new HttpHeaders();
final String encodedLogPass = getBase64EncodedLogPass();
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
return headers;
}
private String getBase64EncodedLogPass() {
final String logPass = "user1:user1Pass";
final byte[] authHeaderBytes = Base64.getEncoder().encode(logPass.getBytes(Charsets.US_ASCII));
return new String(authHeaderBytes, Charsets.US_ASCII);
}
private RequestCallback requestCallback(final Foo updatedInstance) {
return clientHttpRequest -> {
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
clientHttpRequest.getHeaders()
.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
clientHttpRequest.getHeaders()
.add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
};
}
// Simply setting restTemplate timeout using ClientHttpRequestFactory
ClientHttpRequestFactory getClientHttpRequestFactory() {
final int timeout = 5;
final HttpComponentsClientHttpRequestFactory
clientHttpRequestFactory = new
HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectionRequestTimeout(timeout * 1000);
clientHttpRequestFactory.setConnectTimeout(timeout * 2000);
//clientHttpRequestFactory.setReadTimeout(timeout * 3000);
return clientHttpRequestFactory;
}
// Alternate GET ClientHttpRequestFactory
ClientHttpRequestFactory getClientHttpRequestFactoryAlternate() {
long timeout = 5;
int readTimeout = 5;
// Connect timeout
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(timeout * 2000))
.build();
// Connection request timeout
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(timeout * 1000))
.build();
// Socket timeout
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(Timeout.ofMilliseconds(timeout * 1000)).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultSocketConfig(socketConfig);
connectionManager.setDefaultConnectionConfig(connectionConfig);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.build();
/**final HttpComponentsClientHttpRequestFactory
clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
clientHttpRequestFactory.setReadTimeout(readTimeout*3000);**/
//return clientHttpRequestFactory;
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/web/service/BarConsumerServiceUnitTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/web/service/BarConsumerServiceUnitTest.java | package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.exception.UnauthorizedException;
import com.baeldung.resttemplate.web.model.Bar;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class BarConsumerServiceUnitTest {
@Mock
private RestTemplateBuilder restTemplateBuilder;
@Mock
private RestTemplate restTemplate;
private BarConsumerService barConsumerService;
@BeforeEach
public void setup() {
when(restTemplateBuilder.errorHandler(any())).thenReturn(restTemplateBuilder);
when(restTemplateBuilder.build()).thenReturn(restTemplate);
barConsumerService = new BarConsumerService(restTemplateBuilder);
}
@Test
public void givenValidId_whenFetchingBar_thenReturnsBar() {
Bar expectedBar = new Bar();
expectedBar.setId("123");
expectedBar.setName("Test Bar");
when(restTemplate.getForObject(any(String.class), eq(Bar.class))).thenReturn(expectedBar);
Bar result = barConsumerService.fetchBarById("123");
assertEquals(expectedBar, result);
}
@Test
public void givenUnauthorizedResponse_whenFetchingBar_thenThrowsUnauthorizedException() {
String errorBody = "{\"error\": \"Invalid token\"}";
HttpClientErrorException exception = HttpClientErrorException.create(
HttpStatus.UNAUTHORIZED,
"Unauthorized",
null,
errorBody.getBytes(),
null
);
when(restTemplate.getForObject(any(String.class), eq(Bar.class))).thenThrow(exception);
UnauthorizedException thrown = assertThrows(
UnauthorizedException.class,
() -> barConsumerService.fetchBarById("123")
);
assertTrue(thrown.getMessage().contains(errorBody));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceMockRestServiceServerUnitTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceMockRestServiceServerUnitTest.java | package com.baeldung.mock;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import java.net.URI;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import com.baeldung.SpringTestConfig;
import com.baeldung.resttemplate.web.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SpringTestConfig.class)
public class EmployeeServiceMockRestServiceServerUnitTest {
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class);
@Autowired
private EmployeeService empService;
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
private ObjectMapper mapper = new ObjectMapper();
@BeforeEach
public void init() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void givenMockingIsDoneByMockRestServiceServer_whenGetForEntityIsCalled_thenReturnMockedObject() throws Exception {
Employee emp = new Employee("E001", "Eric Simmons");
mockServer.expect(ExpectedCount.once(),
requestTo(new URI("http://localhost:8080/employee/E001")))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(mapper.writeValueAsString(emp)));
Employee employee = empService.getEmployeeWithGetForEntity("E001");
mockServer.verify();
Assertions.assertEquals(emp, employee);
}
@Test
public void givenMockingIsDoneByMockRestServiceServer_whenExchangeIsCalled_thenReturnMockedObject() throws Exception {
Employee emp = new Employee("E001", "Eric Simmons");
mockServer.expect(ExpectedCount.once(),
requestTo(new URI("http://localhost:8080/employee/E001")))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(mapper.writeValueAsString(emp)));
Employee employee = empService.getEmployeeWithRestTemplateExchange("E001");
mockServer.verify();
Assertions.assertEquals(emp, employee);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java | package com.baeldung.mock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.AdditionalMatchers.eq;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.web.model.Employee;
@ExtendWith(MockitoExtension.class)
public class EmployeeServiceUnitTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private EmployeeService empService = new EmployeeService();
@Test
public void givenMockingIsDoneByMockito_whenGetForEntityIsCalled_thenReturnMockedObject() throws Exception {
Employee emp = new Employee("E001", "Eric Simmons");
Mockito.when(restTemplate.getForEntity("http://localhost:8080/employee/E001", Employee.class))
.thenReturn(new ResponseEntity(emp, HttpStatus.OK));
Employee employee = empService.getEmployeeWithGetForEntity("E001");
assertEquals(emp, employee);
}
@Test
public void givenMockingIsDoneByMockito_whenExchangeIsCalled_thenReturnMockedObject(){
Employee emp = new Employee("E001", "Eric Simmons");
Mockito.when(restTemplate.exchange("http://localhost:8080/employee/E001",
HttpMethod.GET,
null,
Employee.class)
).thenReturn(new ResponseEntity(emp, HttpStatus.OK));
Employee employee = empService.getEmployeeWithRestTemplateExchange("E001");
assertEquals(emp, employee);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java | package com.baeldung.client;
import com.baeldung.resttemplate.web.dto.Foo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import okhttp3.Request;
import okhttp3.RequestBody;
// This test needs RestTemplateConfigurationApplication to be up and running
public class TestRestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos";
private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd";
private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest";
@BeforeEach
public void beforeTest() {
restTemplate = new RestTemplate();
}
// GET
@Test
public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.build();
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd").
getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate.
HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
// HEAD
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL);
Assertions.assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenService_whenPostForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
// PUT
@Test
public void givenService_whenPutForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java | package com.baeldung.client;
public interface Consts {
int APPLICATION_PORT = 8082;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java | spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java | package com.baeldung.web.handler;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.web.exception.NotFoundException;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.model.Bar;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { NotFoundException.class, Bar.class })
@RestClientTest
public class RestTemplateResponseErrorHandlerIntegrationTest {
@Autowired private MockRestServiceServer server;
@Autowired private RestTemplateBuilder builder;
@Test
public void givenRemoteApiCall_when404Error_thenThrowNotFound() {
Assertions.assertNotNull(this.builder);
Assertions.assertNotNull(this.server);
RestTemplate restTemplate = this.builder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
this.server
.expect(ExpectedCount.once(), requestTo("/bars/4242"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
Assertions.assertThrows(NotFoundException.class, () -> {
Bar response = restTemplate.getForObject("/bars/4242", Bar.class);
});
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java | package com.baeldung.resttemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java | package com.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.baeldung.resttemplate.configuration")
public class SpringConfig {
@Bean
@Qualifier("customRestTemplateCustomizer")
public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
return new CustomRestTemplateCustomizer();
}
@Bean
@DependsOn(value = {"customRestTemplateCustomizer"})
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder(customRestTemplateCustomizer());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java | package com.baeldung.resttemplate.configuration;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import com.baeldung.resttemplate.web.dto.Foo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
@Controller
public class FooController {
private Map<Long, Foo> fooRepository = Maps.newHashMap(ImmutableMap.of(1L, new Foo(1L, randomAlphabetic(4))));
public FooController() {
super();
}
@RequestMapping(method = RequestMethod.GET, value = "/foos")
@ResponseBody
public Collection<Foo> findListOfFoo() {
return fooRepository.values();
}
// API - read
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
@ResponseBody
public Foo findById(@PathVariable final long id) throws HttpClientErrorException {
Foo foo = fooRepository.get(id);
if (foo == null) {
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
} else {
return foo;
}
}
// API - write
@RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
fooRepository.put(id, foo);
return foo;
}
@RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
fooRepository.put(id, foo);
return foo;
}
@RequestMapping(method = RequestMethod.POST, value = "/foos")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public ResponseEntity<Foo> postFoo(@RequestBody final Foo foo) {
fooRepository.put(foo.getId(), foo);
final URI location = ServletUriComponentsBuilder
.fromCurrentServletMapping()
.path("/foos/{id}")
.build()
.expand(foo.getId())
.toUri();
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(location);
final ResponseEntity<Foo> entity = new ResponseEntity<Foo>(foo, headers, HttpStatus.CREATED);
return entity;
}
@RequestMapping(method = RequestMethod.HEAD, value = "/foos")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo headFoo() {
return new Foo(1, randomAlphabetic(4));
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/new")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo createFoo(@RequestBody final Foo foo) {
fooRepository.put(foo.getId(), foo);
return foo;
}
@RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public long deleteFoo(@PathVariable final long id) {
fooRepository.remove(id);
return id;
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/form", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String submitFoo(@RequestParam("id") String id) {
return id;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java | package com.baeldung.resttemplate.configuration;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.web.client.RestTemplate;
/**
* customize rest template with an interceptor
*/
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java | package com.baeldung.resttemplate.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
/**
* interceptor to log incoming requests
*/
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequestDetails(request);
return execution.execute(request, body);
}
private void logRequestDetails(HttpRequest request) {
LOGGER.info("Request Headers: {}", request.getHeaders());
LOGGER.info("Request Method: {}", request.getMethod());
LOGGER.info("Request URI: {}", request.getURI());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java | package com.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Controller to test RestTemplate configuration
*/
@RestController
public class HelloController {
private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz";
private RestTemplate restTemplate;
@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
@RequestMapping("/foo")
public String foo() {
ResponseEntity<String> response = restTemplate.getForEntity(RESOURCE_URL, String.class);
return response.getBody();
}
@RequestMapping("/baz")
public String baz() {
return "Foo";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java | package com.baeldung.resttemplate.web.dto;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Foo")
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;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java | package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.exception.UnauthorizedException;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.model.Bar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
@Service
public class BarConsumerService {
private RestTemplate restTemplate;
@Autowired
public BarConsumerService(RestTemplateBuilder restTemplateBuilder) {
restTemplate = restTemplateBuilder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
}
public Bar fetchBarById(String barId) {
try {
return restTemplate.getForObject("/bars/" + barId, Bar.class);
} catch (HttpStatusCodeException e) {
if (HttpStatus.UNAUTHORIZED == e.getStatusCode()) {
String responseBody = e.getResponseBodyAsString();
throw new UnauthorizedException("Unauthorized access: " + responseBody);
}
throw e;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java | package com.baeldung.resttemplate.web.model;
import java.util.Objects;
public class Employee {
private String id;
private String name;
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
public Employee() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id);
}
@Override public int hashCode() {
return Objects.hash(id);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java | package com.baeldung.resttemplate.web.model;
public class Bar {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/UnauthorizedException.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/UnauthorizedException.java | package com.baeldung.resttemplate.web.exception;
public class UnauthorizedException extends RuntimeException {
public UnauthorizedException(String message) {
super(message);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java | package com.baeldung.resttemplate.web.exception;
public class NotFoundException extends RuntimeException {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java | package com.baeldung.resttemplate.web.handler;
import java.io.IOException;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResponseErrorHandler;
import com.baeldung.resttemplate.web.exception.NotFoundException;
@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
return httpResponse.getStatusCode()
.is5xxServerError() || httpResponse.getStatusCode()
.is4xxClientError();
}
@Override
public void handleError(ClientHttpResponse httpResponse) throws IOException {
if (httpResponse.getStatusCode()
.is5xxServerError()) {
//Handle SERVER_ERROR
throw new HttpClientErrorException(httpResponse.getStatusCode());
} else if (httpResponse.getStatusCode()
.is4xxClientError()) {
//Handle CLIENT_ERROR
if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new NotFoundException();
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/transfer/LoginForm.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/transfer/LoginForm.java | package com.baeldung.transfer;
public class LoginForm {
private String username;
private String password;
public LoginForm() {
}
public LoginForm(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/mock/EmployeeService.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/mock/EmployeeService.java | package com.baeldung.mock;
import com.baeldung.resttemplate.web.model.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class EmployeeService {
static final String EMP_URL_PREFIX = "http://localhost:8080/employee";
static final String URL_SEP = "/";
private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);
@Autowired
private RestTemplate restTemplate;
public Employee getEmployeeWithGetForEntity(String id) {
ResponseEntity<Employee> resp = restTemplate.getForEntity("http://localhost:8080/employee/" + id,
Employee.class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
public Employee getEmployeeWithRestTemplateExchange(String id) {
ResponseEntity<Employee> resp = restTemplate.exchange("http://localhost:8080/employee/" + id,
HttpMethod.GET,
null,
Employee.class
);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java | 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) {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/MainApplication.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/MainApplication.java | 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);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/WebConfig.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/WebConfig.java | 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());
}
*/
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java | 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);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java | 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.";
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java | package com.baeldung.sampleapp.web.controller;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import jakarta.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 = "/foo")
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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java | 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");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java | spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java | 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;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.