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-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeNoMvcIntegrationTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeNoMvcIntegrationTest.java | package com.baeldung.matrix;
import com.baeldung.matrix.config.MatrixWebConfig;
import com.baeldung.matrix.controller.EmployeeController;
import com.baeldung.matrix.model.Employee;
import org.junit.Assert;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class })
public class EmployeeNoMvcIntegrationTest {
@Autowired
private EmployeeController employeeController;
@Before
public void setup() {
employeeController.initEmployees();
}
//
@Test
public void whenInitEmployees_thenVerifyValuesInitiation() {
Employee employee1 = employeeController.employeeMap.get(1L);
Employee employee2 = employeeController.employeeMap.get(2L);
Employee employee3 = employeeController.employeeMap.get(3L);
Assert.assertTrue(employee1.getId() == 1L);
Assert.assertTrue(employee1.getName().equals("John"));
Assert.assertTrue(employee1.getContactNumber().equals("223334411"));
Assert.assertTrue(employee1.getWorkingArea().equals("rh"));
Assert.assertTrue(employee2.getId() == 2L);
Assert.assertTrue(employee2.getName().equals("Peter"));
Assert.assertTrue(employee2.getContactNumber().equals("22001543"));
Assert.assertTrue(employee2.getWorkingArea().equals("informatics"));
Assert.assertTrue(employee3.getId() == 3L);
Assert.assertTrue(employee3.getName().equals("Mike"));
Assert.assertTrue(employee3.getContactNumber().equals("223334411"));
Assert.assertTrue(employee3.getWorkingArea().equals("admin"));
}
}
| 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-2/src/test/java/com/baeldung/matrix/EmployeeMvcIntegrationTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/matrix/EmployeeMvcIntegrationTest.java | package com.baeldung.matrix;
import com.baeldung.matrix.config.MatrixWebConfig;
import com.baeldung.matrix.controller.EmployeeController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
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 static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class })
public class EmployeeMvcIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.openMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception {
mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print());
}
}
| 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-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java | package com.baeldung.htmlunit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitAndJUnitLiveTest {
private WebClient webClient;
@Before
public void init() throws Exception {
webClient = new WebClient();
}
@After
public void close() throws Exception {
webClient.close();
}
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk() throws Exception {
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}
| 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-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java | package com.baeldung.htmlunit;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitWebScrapingLiveTest {
private WebClient webClient;
@Before
public void init() throws Exception {
webClient = new WebClient();
}
@After
public void close() throws Exception {
webClient.close();
}
@Test
public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1() throws Exception {
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(false);
final String url = "http://www.baeldung.com/full_archive";
final HtmlPage page = webClient.getPage(url);
final String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a";
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0);
final HtmlPage postPage = latestPostLink.click();
final List<Object> h1 = postPage.getByXPath("//h1");
Assert.assertTrue(h1.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-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java | package com.baeldung.htmlunit;
import org.junit.Assert;
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.htmlunit.MockMvcWebClientBuilder;
import org.springframework.web.context.WebApplicationContext;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { TestConfig.class })
public class HtmlUnitAndSpringLiveTest {
@Autowired
private WebApplicationContext wac;
private WebClient webClient;
@Before
public void setup() {
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
}
@Test
public void givenAMessage_whenSent_thenItShows() throws Exception {
String text = "Hello world!";
HtmlPage page;
String url = "http://localhost/message/showForm";
page = webClient.getPage(url);
HtmlTextInput messageText = page.getHtmlElementById("message");
messageText.setValueAttribute(text);
HtmlForm form = page.getForms().get(0);
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
HtmlPage newPage = submit.click();
String receivedText = newPage.getHtmlElementById("received").getTextContent();
Assert.assertEquals(receivedText, text);
}
}
| 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-2/src/test/java/com/baeldung/htmlunit/TestConfig.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java | package com.baeldung.htmlunit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
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.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.WebApplicationTemplateResolver;
import org.thymeleaf.web.IWebApplication;
import org.thymeleaf.web.servlet.IServletWebApplication;
import org.thymeleaf.web.servlet.JakartaServletWebApplication;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.web.controller.message" })
public class TestConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext ctx;
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public SpringResourceTemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver ();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
} | 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-2/src/test/java/com/baeldung/multiparttesting/MultipartPostRequestControllerUnitTest.java | spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/multiparttesting/MultipartPostRequestControllerUnitTest.java | package com.baeldung.multiparttesting;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
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.matrix.config.MatrixWebConfig;
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, MultipartPostRequestController.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MultipartPostRequestControllerUnitTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void whenFileUploaded_thenVerifyStatus() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "hello.txt", MediaType.TEXT_PLAIN_VALUE, "Hello, World!".getBytes());
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(multipart("/upload").file(file)).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-2/src/main/java/com/baeldung/servlets/CounterServlet.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/servlets/CounterServlet.java | package com.baeldung.servlets;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/counter", name = "counterServlet")
public class CounterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
int count = (int)request.getServletContext().getAttribute("counter");
out.println("Request counter: " + count);
}
}
| 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-2/src/main/java/com/baeldung/servlets/UppercaseServlet.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/servlets/UppercaseServlet.java | package com.baeldung.servlets;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet")
public class UppercaseServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String inputString = request.getParameter("input").toUpperCase();
PrintWriter out = response.getWriter();
out.println(inputString);
}
}
| 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-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java | package com.baeldung.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPOIHelper {
public Map<Integer, List<MyCell>> readExcel(String fileLocation) throws IOException {
Map<Integer, List<MyCell>> data = new HashMap<>();
FileInputStream fis = new FileInputStream(new File(fileLocation));
if (fileLocation.endsWith(".xls")) {
data = readHSSFWorkbook(fis);
} else if (fileLocation.endsWith(".xlsx")) {
data = readXSSFWorkbook(fis);
}
int maxNrCols = data.values().stream()
.mapToInt(List::size)
.max()
.orElse(0);
data.values().stream()
.filter(ls -> ls.size() < maxNrCols)
.forEach(ls -> {
IntStream.range(ls.size(), maxNrCols)
.forEach(i -> ls.add(new MyCell("")));
});
return data;
}
private String readCellContent(Cell cell) {
String content;
switch (cell.getCellTypeEnum()) {
case STRING:
content = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
content = cell.getDateCellValue() + "";
} else {
content = cell.getNumericCellValue() + "";
}
break;
case BOOLEAN:
content = cell.getBooleanCellValue() + "";
break;
case FORMULA:
content = cell.getCellFormula() + "";
break;
default:
content = "";
}
return content;
}
private Map<Integer, List<MyCell>> readHSSFWorkbook(FileInputStream fis) throws IOException {
Map<Integer, List<MyCell>> data = new HashMap<>();
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
HSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
HSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
short[] rgbColor = bgColor.getTriplet();
myCell.setBgColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
HSSFFont font = cell.getCellStyle()
.getFont(workbook);
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
HSSFColor textColor = font.getHSSFColor(workbook);
if (textColor != null) {
short[] rgbColor = textColor.getTriplet();
myCell.setTextColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
private Map<Integer, List<MyCell>> readXSSFWorkbook(FileInputStream fis) throws IOException {
XSSFWorkbook workbook = null;
Map<Integer, List<MyCell>> data = new HashMap<>();
try {
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
XSSFCell cell = row.getCell(j);
if (cell != null) {
XSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
XSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgbColor = bgColor.getRGB();
myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
XSSFFont font = cellStyle.getFont();
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
XSSFColor textColor = font.getXSSFColor();
if (textColor != null) {
byte[] rgbColor = textColor.getRGB();
myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
} | 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-2/src/main/java/com/baeldung/excel/ExcelController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java | package com.baeldung.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import jakarta.annotation.Resource;
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 org.springframework.web.multipart.MultipartFile;
@Controller
public class ExcelController {
private String fileLocation;
@Resource(name = "excelPOIHelper")
private ExcelPOIHelper excelPOIHelper;
@RequestMapping(method = RequestMethod.GET, value = "/excelProcessing")
public String getExcelProcessingPage() {
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/uploadExcelFile")
public String uploadFile(Model model, MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename();
FileOutputStream f = new FileOutputStream(fileLocation);
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!");
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readPOI")
public String readPOI(Model model) throws IOException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) {
Map<Integer, List<MyCell>> data = excelPOIHelper.readExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid excel file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
} | 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-2/src/main/java/com/baeldung/excel/WebConfig.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java | package com.baeldung.excel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.baeldung.excel" })
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();
}
}
| 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-2/src/main/java/com/baeldung/excel/MyCell.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java | package com.baeldung.excel;
public class MyCell {
private String content;
private String textColor;
private String bgColor;
private String textSize;
private String textWeight;
public MyCell() {
}
public MyCell(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTextColor() {
return textColor;
}
public void setTextColor(String textColor) {
this.textColor = textColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextWeight() {
return textWeight;
}
public void setTextWeight(String textWeight) {
this.textWeight = textWeight;
}
} | 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-2/src/main/java/com/baeldung/cache/CacheControlController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheControlController.java | package com.baeldung.cache;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.request.WebRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;
@Controller
public class CacheControlController {
@GetMapping(value = "/hello/{name}")
public ResponseEntity<String> hello(@PathVariable String name) {
CacheControl cacheControl = CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate();
return ResponseEntity.ok()
.cacheControl(cacheControl)
.body("Hello " + name);
}
@GetMapping(value = "/home/{name}")
public String home(@PathVariable String name, final HttpServletResponse response) {
response.addHeader("Cache-Control", "max-age=60, must-revalidate, no-transform");
return "home";
}
@GetMapping(value = "/login/{name}")
public ResponseEntity<String> intercept(@PathVariable String name) {
return ResponseEntity.ok().body("Hello " + name);
}
@GetMapping(value = "/productInfo/{name}")
public ResponseEntity<String> validate(@PathVariable String name, WebRequest request) {
ZoneId zoneId = ZoneId.of("GMT");
long lastModifiedTimestamp = LocalDateTime.of(2020, 02, 4, 19, 57, 45)
.atZone(zoneId).toInstant().toEpochMilli();
if (request.checkNotModified(lastModifiedTimestamp)) {
return ResponseEntity.status(304).build();
}
return ResponseEntity.ok().body("Hello " + name);
}
}
| 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-2/src/main/java/com/baeldung/cache/CacheWebConfig.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/cache/CacheWebConfig.java | package com.baeldung.cache;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.WebContentInterceptor;
import java.util.concurrent.TimeUnit;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"com.baeldung.cache"})
public class CacheWebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/")
.setCacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebContentInterceptor interceptor = new WebContentInterceptor();
interceptor.addCacheMapping(CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate(), "/login/*");
registry.addInterceptor(interceptor);
}
} | 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-2/src/main/java/com/baeldung/matrix/controller/CompanyController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/CompanyController.java | package com.baeldung.matrix.controller;
import com.baeldung.matrix.model.Company;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
public class CompanyController {
Map<Long, Company> companyMap = new HashMap<>();
@RequestMapping(value = "/company", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("companyHome", "company", new Company());
}
@RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
return companyMap.get(Id);
}
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", company.getName());
model.addAttribute("id", company.getId());
companyMap.put(company.getId(), company);
return "companyView";
}
@RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
final Map<String, String> result = new HashMap<>();
result.put("name", name);
return new ResponseEntity<>(result, 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-mvc-java-2/src/main/java/com/baeldung/matrix/controller/EmployeeController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/matrix/controller/EmployeeController.java | package com.baeldung.matrix.controller;
import com.baeldung.matrix.model.Employee;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
@SessionAttributes("employees")
@Controller
public class EmployeeController {
public Map<Long, Employee> employeeMap = new HashMap<>();
@ModelAttribute("employees")
public void initEmployees() {
employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh"));
employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics"));
employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin"));
}
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("workingArea", employee.getWorkingArea());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
@RequestMapping(value = "/employees/{name}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) {
final List<Employee> employeesList = new ArrayList<>();
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
if (employee.getName().equalsIgnoreCase(name) && employee.getContactNumber().startsWith(beginContactNumber)) {
employeesList.add(employee);
}
}
return new ResponseEntity<>(employeesList, HttpStatus.OK);
}
@RequestMapping(value = "/employeesContacts/{contactNumber}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByContactNumber(@MatrixVariable(required = true) final String contactNumber) {
final List<Employee> employeesList = new ArrayList<>();
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
if (employee.getContactNumber().equalsIgnoreCase(contactNumber)) {
employeesList.add(employee);
}
}
return new ResponseEntity<>(employeesList, HttpStatus.OK);
}
@RequestMapping(value = "employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeData(@MatrixVariable final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "employeeArea/{workingArea}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByWorkingArea(@MatrixVariable final Map<String, List<String>> matrixVars) {
final List<Employee> employeesList = new ArrayList<>();
final Collection<String> workingArea = matrixVars.get("workingArea");
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
for (final String area : workingArea) {
if (employee.getWorkingArea().equalsIgnoreCase(area)) {
employeesList.add(employee);
break;
}
}
}
return new ResponseEntity<>(employeesList, 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-mvc-java-2/src/main/java/com/baeldung/matrix/model/Employee.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Employee.java | package com.baeldung.matrix.model;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private long id;
private String name;
private String contactNumber;
private String workingArea;
public Employee() {
super();
}
public Employee(final long id, final String name, final String contactNumber, final String workingArea) {
this.id = id;
this.name = name;
this.contactNumber = contactNumber;
this.workingArea = workingArea;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(final String contactNumber) {
this.contactNumber = contactNumber;
}
public String getWorkingArea() {
return workingArea;
}
public void setWorkingArea(final String workingArea) {
this.workingArea = workingArea;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]";
}
}
| 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-2/src/main/java/com/baeldung/matrix/model/Company.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/matrix/model/Company.java | package com.baeldung.matrix.model;
public class Company {
private long id;
private String name;
public Company() {
super();
}
public Company(final long id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
@Override
public String toString() {
return "Company [id=" + id + ", name=" + name + "]";
}
}
| 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-2/src/main/java/com/baeldung/matrix/config/MatrixWebConfig.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/matrix/config/MatrixWebConfig.java | package com.baeldung.matrix.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration
public class MatrixWebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
| 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-2/src/main/java/com/baeldung/pathvariable.dottruncated/CustomWebMvcConfigurationSupport.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/CustomWebMvcConfigurationSupport.java | package com.baeldung.pathvariable.dottruncated;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
@Override
protected PathMatchConfigurer getPathMatchConfigurer() {
PathMatchConfigurer pathMatchConfigurer = super.getPathMatchConfigurer();
return pathMatchConfigurer;
}
}
| 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-2/src/main/java/com/baeldung/pathvariable.dottruncated/SiteController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/SiteController.java | package com.baeldung.pathvariable.dottruncated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/site")
public class SiteController {
@GetMapping("/{firstValue}/{secondValue}")
public String requestWithError(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
@GetMapping("/{firstValue}/{secondValue:.+}")
public String requestWithRegex(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
@GetMapping("/{firstValue}/{secondValue}/")
public String requestWithSlash(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
}
| 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-2/src/main/java/com/baeldung/filters/EmptyParamFilter.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/filters/EmptyParamFilter.java | package com.baeldung.filters;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/uppercase")
public class EmptyParamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
String inputString = servletRequest.getParameter("input");
if (inputString != null && inputString.matches("[A-Za-z0-9]+")) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
servletResponse.getWriter().println("Missing input parameter");
}
}
@Override
public void destroy() {
}
}
| 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-2/src/main/java/com/baeldung/multiparttesting/MultipartPostRequestController.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/multiparttesting/MultipartPostRequestController.java | package com.baeldung.multiparttesting;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class MultipartPostRequestController {
@PostMapping(path = "/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
return file.isEmpty() ? new ResponseEntity<>(HttpStatus.NOT_FOUND) : new ResponseEntity<>(
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-mvc-java-2/src/main/java/com/baeldung/listeners/AppListener.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/listeners/AppListener.java | package com.baeldung.listeners;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
@WebListener
public class AppListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
context.setAttribute("counter", 0);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
| 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-2/src/main/java/com/baeldung/listeners/RequestListener.java | spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/listeners/RequestListener.java | package com.baeldung.listeners;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent event) {
}
@Override
public void requestDestroyed(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest)event.getServletRequest();
if (!request.getServletPath().equals("/counter")) {
ServletContext context = event.getServletContext();
context.setAttribute("counter", (int)context.getAttribute("counter") + 1);
}
}
}
| 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/src/test/java/com/baeldung/Consts.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/Consts.java | package com.baeldung;
public interface Consts {
int APPLICATION_PORT = 8080;
}
| 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/src/test/java/com/baeldung/test/IMarshaller.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/test/IMarshaller.java | package com.baeldung.test;
import java.util.List;
public interface IMarshaller {
<T> String encode(final T entity);
<T> T decode(final String entityAsString, final Class<T> clazz);
<T> List<T> decodeList(final String entitiesAsString, final Class<T> clazz);
String getMime();
}
| 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/src/test/java/com/baeldung/test/TestMarshallerFactory.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/test/TestMarshallerFactory.java | package com.baeldung.test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Profile("test")
public class TestMarshallerFactory implements FactoryBean<IMarshaller> {
@Autowired
private Environment env;
public TestMarshallerFactory() {
super();
}
// API
@Override
public IMarshaller getObject() {
final String testMime = env.getProperty("test.mime");
if (testMime != null) {
switch (testMime) {
case "json":
return new JacksonMarshaller();
case "xml":
return new XStreamMarshaller();
default:
throw new IllegalStateException();
}
}
return new JacksonMarshaller();
}
@Override
public Class<IMarshaller> getObjectType() {
return IMarshaller.class;
}
@Override
public boolean isSingleton() {
return true;
}
} | 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/src/test/java/com/baeldung/test/JacksonMarshaller.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/test/JacksonMarshaller.java | package com.baeldung.test;
import java.io.IOException;
import java.util.List;
import com.baeldung.persistence.model.Foo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
public final class JacksonMarshaller implements IMarshaller {
private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class);
private final ObjectMapper objectMapper;
public JacksonMarshaller() {
super();
objectMapper = new ObjectMapper();
}
// API
@Override
public final <T> String encode(final T resource) {
Preconditions.checkNotNull(resource);
String entityAsJSON = null;
try {
entityAsJSON = objectMapper.writeValueAsString(resource);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entityAsJSON;
}
@Override
public final <T> T decode(final String resourceAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourceAsString);
T entity = null;
try {
entity = objectMapper.readValue(resourceAsString, clazz);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entity;
}
@SuppressWarnings("unchecked")
@Override
public final <T> List<T> decodeList(final String resourcesAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourcesAsString);
List<T> entities = null;
try {
if (clazz.equals(Foo.class)) {
entities = objectMapper.readValue(resourcesAsString, new TypeReference<List<T>>() {
// ...
});
} else {
entities = objectMapper.readValue(resourcesAsString, List.class);
}
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entities;
}
@Override
public final String getMime() {
return MediaType.APPLICATION_JSON.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/src/test/java/com/baeldung/test/XStreamMarshaller.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/test/XStreamMarshaller.java | package com.baeldung.test;
import java.util.List;
import com.baeldung.persistence.model.Foo;
import org.springframework.http.MediaType;
import com.google.common.base.Preconditions;
import com.thoughtworks.xstream.XStream;
public final class XStreamMarshaller implements IMarshaller {
private XStream xstream;
public XStreamMarshaller() {
super();
xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.processAnnotations(Foo.class);
}
// API
@Override
public final <T> String encode(final T resource) {
Preconditions.checkNotNull(resource);
return xstream.toXML(resource);
}
@SuppressWarnings("unchecked")
@Override
public final <T> T decode(final String resourceAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourceAsString);
return (T) xstream.fromXML(resourceAsString);
}
@SuppressWarnings("unchecked")
@Override
public <T> List<T> decodeList(final String resourcesAsString, final Class<T> clazz) {
return this.decode(resourcesAsString, List.class);
}
@Override
public final String getMime() {
return MediaType.APPLICATION_XML.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/src/test/java/com/baeldung/common/web/AbstractDiscoverabilityLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractDiscoverabilityLiveTest.java | package com.baeldung.common.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.Serializable;
import com.baeldung.persistence.model.Foo;
import com.baeldung.web.util.HTTPLinkHeaderUtil;
import org.hamcrest.core.AnyOf;
import org.junit.Test;
import org.springframework.http.MediaType;
import com.google.common.net.HttpHeaders;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public abstract class AbstractDiscoverabilityLiveTest<T extends Serializable> extends AbstractLiveTest<T> {
public AbstractDiscoverabilityLiveTest(final Class<T> clazzToSet) {
super(clazzToSet);
}
// tests
// discoverability
@Test
public void whenInvalidPOSTIsSentToValidURIOfResource_thenAllowHeaderListsTheAllowedActions() {
// Given
final String uriOfExistingResource = createAsUri();
// When
final Response res = RestAssured.post(uriOfExistingResource);
// Then
final String allowHeader = res.getHeader(HttpHeaders.ALLOW);
assertThat(allowHeader, AnyOf.anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE")));
}
@Test
public void whenResourceIsCreated_thenUriOfTheNewlyCreatedResourceIsDiscoverable() {
// When
final Foo newResource = new Foo(randomAlphabetic(6));
final Response createResp = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(newResource)
.post(getURL());
final String uriOfNewResource = createResp.getHeader(HttpHeaders.LOCATION);
// Then
final Response response = RestAssured.given()
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.get(uriOfNewResource);
final Foo resourceFromServer = response.body().as(Foo.class);
assertThat(newResource, equalTo(resourceFromServer));
}
@Test
public void whenResourceIsRetrieved_thenUriToGetAllResourcesIsDiscoverable() {
// Given
final String uriOfExistingResource = createAsUri();
// When
final Response getResponse = RestAssured.get(uriOfExistingResource);
// Then
final String uriToAllResources = HTTPLinkHeaderUtil.extractURIByRel(getResponse.getHeader("Link"), "collection");
final Response getAllResponse = RestAssured.get(uriToAllResources);
assertThat(getAllResponse.getStatusCode(), is(200));
}
// template method
}
| 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/src/test/java/com/baeldung/common/web/AbstractBasicLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractBasicLiveTest.java | package com.baeldung.common.web;
import static com.baeldung.web.util.HTTPLinkHeaderUtil.extractURIByRel;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import com.baeldung.persistence.model.Foo;
import com.google.common.net.HttpHeaders;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.springframework.http.MediaType;
public abstract class AbstractBasicLiveTest<T extends Serializable> extends AbstractLiveTest<T> {
public AbstractBasicLiveTest(final Class<T> clazzToSet) {
super(clazzToSet);
}
// find - all - paginated
@Test
public void whenResourcesAreRetrievedPaged_then200IsReceived() {
create();
final Response response = RestAssured.get(getURL() + "?page=0&size=10");
assertThat(response.getStatusCode(), is(200));
}
@Test
public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() {
final String url = getURL() + "?page=" + randomNumeric(5) + "&size=10";
final Response response = RestAssured.get(url);
assertThat(response.getStatusCode(), is(404));
}
@Test
public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() {
create();
final Response response = RestAssured.given()
.accept(MediaType.APPLICATION_JSON_VALUE).get(getURL() + "?page=0&size=10");
assertFalse(response.body().as(List.class).isEmpty());
}
@Test
public void whenFirstPageOfResourcesAreRetrieved_thenSecondPageIsNext() {
create();
create();
create();
final Response response = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next");
assertEquals(getURL() + "?page=1&size=2", uriToNextPage);
}
@Test
public void whenFirstPageOfResourcesAreRetrieved_thenNoPreviousPage() {
final Response response = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev");
assertNull(uriToPrevPage);
}
@Test
public void whenSecondPageOfResourcesAreRetrieved_thenFirstPageIsPrevious() {
create();
create();
final Response response = RestAssured.get(getURL() + "?page=1&size=2");
final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev");
assertEquals(getURL() + "?page=0&size=2", uriToPrevPage);
}
@Test
public void whenLastPageOfResourcesIsRetrieved_thenNoNextPageIsDiscoverable() {
create();
create();
create();
final Response first = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToLastPage = extractURIByRel(first.getHeader(HttpHeaders.LINK), "last");
final Response response = RestAssured.get(uriToLastPage);
final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next");
assertNull(uriToNextPage);
}
// etags
@Test
public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() {
// Given
final String uriOfResource = createAsUri();
// When
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
// Then
assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG));
}
@Test
public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() {
// Given
final String uriOfResource = createAsUri();
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG);
// When
final Response secondFindOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-None-Match", etagValue)
.get(uriOfResource);
// Then
assertTrue(secondFindOneResponse.getStatusCode() == 304);
}
@Test
public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() {
// Given
final String uriOfResource = createAsUri();
final Response firstFindOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
final String etagValue = firstFindOneResponse.getHeader(HttpHeaders.ETAG);
final long createdId = firstFindOneResponse.jsonPath().getLong("id");
Foo updatedFoo = new Foo("updated value");
updatedFoo.setId(createdId);
Response updatedResponse = RestAssured.given().contentType(ContentType.JSON).body(updatedFoo)
.put(uriOfResource);
assertThat(updatedResponse.getStatusCode() == 200);
// When
final Response secondFindOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-None-Match", etagValue)
.get(uriOfResource);
// Then
assertTrue(secondFindOneResponse.getStatusCode() == 200);
}
@Test
@Ignore("Not Yet Implemented By Spring - https://jira.springsource.org/browse/SPR-10164")
public void givenResourceExists_whenRetrievedWithIfMatchIncorrectEtag_then412IsReceived() {
// Given
final String uriOfResource = createAsUri();
// When
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-Match", randomAlphabetic(8))
.get(uriOfResource);
// Then
assertTrue(findOneResponse.getStatusCode() == 412);
}
}
| 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/src/test/java/com/baeldung/common/web/AbstractLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java | package com.baeldung.common.web;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static com.baeldung.Consts.APPLICATION_PORT;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.test.IMarshaller;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
public abstract class AbstractLiveTest<T extends Serializable> {
protected final Class<T> clazz;
@Autowired
protected IMarshaller marshaller;
public AbstractLiveTest(final Class<T> clazzToSet) {
super();
Preconditions.checkNotNull(clazzToSet);
clazz = clazzToSet;
}
// template method
public abstract void create();
public abstract String createAsUri();
protected final void create(final T resource) {
createAsUri(resource);
}
protected final String createAsUri(final T resource) {
final Response response = createAsResponse(resource);
Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode());
final String locationOfCreatedResource = response.getHeader(HttpHeaders.LOCATION);
Preconditions.checkNotNull(locationOfCreatedResource);
return locationOfCreatedResource;
}
final Response createAsResponse(final T resource) {
Preconditions.checkNotNull(resource);
final String resourceAsString = marshaller.encode(resource);
return RestAssured.given()
.contentType(marshaller.getMime())
.body(resourceAsString)
.post(getURL());
}
//
protected String getURL() {
return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/foos";
}
}
| 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/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java | package com.baeldung.springhateoas;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.hateoas.MediaTypes;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
import com.baeldung.services.CustomerService;
import com.baeldung.services.OrderService;
import com.baeldung.web.controller.CustomerController;
@RunWith(SpringRunner.class)
@WebMvcTest(CustomerController.class)
public class CustomerControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private CustomerService customerService;
@MockBean
private OrderService orderService;
private static final String DEFAULT_CUSTOMER_ID = "customer1";
private static final String DEFAULT_ORDER_ID = "order1";
@Test
public void givenExistingCustomer_whenCustomerRequested_thenResourceRetrieved() throws Exception {
given(this.customerService.getCustomerDetail(DEFAULT_CUSTOMER_ID))
.willReturn(new Customer(DEFAULT_CUSTOMER_ID, "customerJohn", "companyOne"));
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$._links").doesNotExist())
.andExpect(jsonPath("$.customerId", is(DEFAULT_CUSTOMER_ID)));
}
@Test
public void givenExistingOrder_whenOrderRequested_thenResourceRetrieved() throws Exception {
given(this.orderService.getOrderByIdForCustomer(DEFAULT_CUSTOMER_ID, DEFAULT_ORDER_ID))
.willReturn(new Order(DEFAULT_ORDER_ID, 1., 1));
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/" + DEFAULT_ORDER_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$._links").doesNotExist())
.andExpect(jsonPath("$.orderId", is(DEFAULT_ORDER_ID)));
}
@Test
public void givenExistingCustomerWithOrders_whenOrdersRequested_thenHalResourceRetrieved() throws Exception {
Order order1 = new Order(DEFAULT_ORDER_ID, 1., 1);
List<Order> orders = Collections.singletonList(order1);
given(this.orderService.getAllOrdersForCustomer(DEFAULT_CUSTOMER_ID)).willReturn(orders);
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/orders").accept(MediaTypes.HAL_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.orders[0]._links.self.href",
is("http://localhost/customers/customer1/order1")))
.andExpect(jsonPath("$._links.self.href", is("http://localhost/customers/customer1/orders")));
}
@Test
public void givenExistingCustomer_whenAllCustomersRequested_thenHalResourceRetrieved() throws Exception {
// customers
Customer retrievedCustomer = new Customer(DEFAULT_CUSTOMER_ID, "customerJohn", "companyOne");
List<Customer> customers = Collections.singletonList(retrievedCustomer);
given(this.customerService.allCustomers()).willReturn(customers);
// orders
Order order1 = new Order(DEFAULT_ORDER_ID, 1., 1);
List<Order> orders = Collections.singletonList(order1);
given(this.orderService.getAllOrdersForCustomer(DEFAULT_CUSTOMER_ID)).willReturn(orders);
this.mvc.perform(get("/customers").accept(MediaTypes.HAL_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(
jsonPath("$._embedded.customers[0]._links.self.href", is("http://localhost/customers/customer1")))
.andExpect(jsonPath("$._embedded.customers[0]._links.allOrders.href",
is("http://localhost/customers/customer1/orders")))
.andExpect(jsonPath("$._links.self.href", is("http://localhost/customers")));
}
}
| 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/src/test/java/com/baeldung/spring/ConfigIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/spring/ConfigIntegrationTest.java | package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan("com.baeldung.test")
public class ConfigIntegrationTest implements WebMvcConfigurer {
public ConfigIntegrationTest() {
super();
}
// API
} | 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/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java | package com.baeldung.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.persistence.dao.IFooDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.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;
/**
* We'll start the whole context, but not the server. We'll mock the REST calls instead.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class FooControllerAppIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private IFooDao fooDao;
@Before
public void setup() {
this.fooDao.deleteAll();
}
@Test
public void whenFindPaginatedRequest_thenEmptyResponse() throws Exception {
this.mockMvc.perform(get("/foos")
.param("page", "0")
.param("size", "2")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json("[]"));
}
}
| 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/src/test/java/com/baeldung/web/GlobalExceptionHandlerIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/GlobalExceptionHandlerIntegrationTest.java | package com.baeldung.web;
import com.baeldung.persistence.service.IFooService;
import com.baeldung.web.controller.FooController;
import com.baeldung.web.exception.CustomException3;
import com.baeldung.web.exception.CustomException4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
*
* We'll start only the web layer.
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class GlobalExceptionHandlerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private IFooService service;
@MockitoBean
private ApplicationEventPublisher publisher;
@Test
public void delete_forException3_fromService() throws Exception {
when(service.findAll())
.thenThrow(new CustomException3());
this.mockMvc
.perform(get("/foos"))
.andExpect(status().isBadRequest());
}
@Test
public void delete_forException4Json_fromService() throws Exception {
when(service.findAll())
.thenThrow(new CustomException4("TEST"));
this.mockMvc
.perform(get("/foos").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
@Test
public void delete_forException4Text_fromService() throws Exception {
when(service.findAll())
.thenThrow(new CustomException4("TEST"));
this.mockMvc
.perform(
get("/foos")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
}
| 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/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java | package com.baeldung.web;
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 com.baeldung.web.controller.students.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
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.request.MockMvcRequestBuilders.put;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StudentControllerIntegrationTest {
private static final String STUDENTS_PATH = "/students/";
@Autowired
private MockMvc mockMvc;
@Test
public void whenReadAll_thenStatusIsOk() throws Exception {
this.mockMvc.perform(get(STUDENTS_PATH))
.andExpect(status().isOk());
}
@Test
public void whenReadOne_thenStatusIsOk() throws Exception {
this.mockMvc.perform(get(STUDENTS_PATH + 1))
.andExpect(status().isOk());
}
@Test
public void whenCreate_thenStatusIsCreated() throws Exception {
Student student = new Student(10, "Albert", "Einstein");
this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student))
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isCreated());
}
@Test
public void whenUpdate_thenStatusIsOk() throws Exception {
Student student = new Student(1, "Nikola", "Tesla");
this.mockMvc.perform(put(STUDENTS_PATH + 1)
.content(asJsonString(student))
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void whenDelete_thenStatusIsNoContent() throws Exception {
this.mockMvc.perform(delete(STUDENTS_PATH + 3))
.andExpect(status().isNoContent());
}
private String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 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/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java | package com.baeldung.web;
import com.baeldung.web.FooDiscoverabilityLiveTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
FooDiscoverabilityLiveTest.class,
FooLiveTest.class,
FooPageableLiveTest.class
}) //
public class LiveTestSuiteLiveTest {
}
| 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/src/test/java/com/baeldung/web/FooMessageConvertersLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooMessageConvertersLiveTest.java | package com.baeldung.web;
import static com.baeldung.Consts.APPLICATION_PORT;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import com.baeldung.common.web.AbstractLiveTest;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.ConfigIntegrationTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooMessageConvertersLiveTest extends AbstractLiveTest<Foo> {
private static final String BASE_URI = "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/";
public FooMessageConvertersLiveTest() {
super(Foo.class);
}
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
@Before
public void setup(){
create();
}
/**
* Without specifying Accept Header, uses the default response from the
* server (in this case json)
*/
@Test
public void whenRetrievingAFoo_thenCorrect() {
final String URI = BASE_URI + "foos/{id}";
final RestTemplate restTemplate = new RestTemplate();
final Foo resource = restTemplate.getForObject(URI, Foo.class, "1");
assertThat(resource, notNullValue());
}
@Test
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
final String URI = BASE_URI + "foos/{id}";
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getXmlMessageConverters());
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<Foo>
response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
final Foo resource = response.getBody();
assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getXmlMessageConverters() {
final XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAnnotatedClasses(Foo.class);
final MarshallingHttpMessageConverter marshallingConverter = new MarshallingHttpMessageConverter(marshaller);
final List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(marshallingConverter);
return converters;
}
@Test
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
final String URI = BASE_URI + "foos/{id}";
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getJsonMessageConverters());
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
final HttpEntity<String> entity = new HttpEntity<String>(headers);
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
final Foo resource = response.getBody();
assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getJsonMessageConverters() {
final List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new MappingJackson2HttpMessageConverter());
return converters;
}
@Test
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
final String URI = BASE_URI + "foos";
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getJsonAndXmlMessageConverters());
final Foo resource = new Foo("jason");
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType((MediaType.APPLICATION_XML));
final HttpEntity<Foo> entity = new HttpEntity<>(resource, headers);
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.POST, entity, Foo.class);
final Foo fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertEquals(resource.getName(), fooResponse.getName());
}
private List<HttpMessageConverter<?>> getJsonAndXmlMessageConverters() {
final List<HttpMessageConverter<?>> converters = getJsonMessageConverters();
converters.addAll(getXmlMessageConverters());
return converters;
}
}
| 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/src/test/java/com/baeldung/web/FooPageableLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java | package com.baeldung.web;
import static com.baeldung.Consts.APPLICATION_PORT;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.common.web.AbstractBasicLiveTest;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.ConfigIntegrationTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooPageableLiveTest extends AbstractBasicLiveTest<Foo> {
public FooPageableLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
super.create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
@Override
@Test
public void whenResourcesAreRetrievedPaged_then200IsReceived() {
this.create();
final Response response = RestAssured.get(getPageableURL() + "?page=0&size=10");
assertThat(response.getStatusCode(), is(200));
}
@Override
@Test
public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() {
final String url = getPageableURL() + "?page=" + randomNumeric(5) + "&size=10";
final Response response = RestAssured.get(url);
assertThat(response.getStatusCode(), is(404));
}
@Override
@Test
public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() {
create();
final Response response = RestAssured.given()
.accept(MediaType.APPLICATION_JSON_VALUE)
.get(getPageableURL() + "?page=0&size=10");
assertFalse(response.body().as(List.class).isEmpty());
}
protected String getPageableURL() {
return getURL() + "/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/src/test/java/com/baeldung/web/FooDiscoverabilityLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooDiscoverabilityLiveTest.java | package com.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import com.baeldung.common.web.AbstractDiscoverabilityLiveTest;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.ConfigIntegrationTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooDiscoverabilityLiveTest extends AbstractDiscoverabilityLiveTest<Foo> {
public FooDiscoverabilityLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
}
| 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/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java | package com.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import com.baeldung.persistence.model.Foo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.HttpHeaders;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
public class FooControllerCustomEtagIntegrationTest {
@Autowired
private MockMvc mvc;
private String FOOS_ENDPOINT = "/foos";
private String CUSTOM_ETAG_ENDPOINT_SUFFIX = "/custom-etag";
private static String serializeFoo(Foo foo) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(foo);
}
private static String createFooJson() throws Exception {
return serializeFoo(new Foo(randomAlphabetic(6)));
}
private static Foo deserializeFoo(String fooJson) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(fooJson, Foo.class);
}
@Test
public void givenResourceExists_whenRetrievingResourceUsingCustomEtagEndpoint_thenEtagIsAlsoReturned()
throws Exception {
// Given
String createdResourceUri = this.mvc.perform(post(FOOS_ENDPOINT).contentType(MediaType.APPLICATION_JSON)
.content(createFooJson()))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader(HttpHeaders.LOCATION);
// When
ResultActions result = this.mvc
.perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON));
// Then
result.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ETAG, "\"0\""));
}
@Test
public void givenResourceWasRetrieved_whenRetrievingAgainWithEtagUsingCustomEtagEndpoint_thenNotModifiedReturned() throws Exception {
// Given
String createdResourceUri = this.mvc.perform(post(FOOS_ENDPOINT).contentType(MediaType.APPLICATION_JSON)
.content(createFooJson()))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader(HttpHeaders.LOCATION);
ResultActions findOneResponse = this.mvc
.perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON));
String etag = findOneResponse.andReturn().getResponse().getHeader(HttpHeaders.ETAG);
// When
ResultActions result = this.mvc
.perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.IF_NONE_MATCH, etag));
// Then
result.andExpect(status().isNotModified());
}
@Test
public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtagUsingCustomEtagEndpoint_thenResourceIsReturned() throws Exception {
// Given
String createdResourceUri = this.mvc.perform(post(FOOS_ENDPOINT).contentType(MediaType.APPLICATION_JSON)
.content(createFooJson()))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader(HttpHeaders.LOCATION);
ResultActions findOneResponse = this.mvc
.perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX)
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON));
String etag = findOneResponse.andReturn().getResponse().getHeader(HttpHeaders.ETAG);
Foo createdFoo = deserializeFoo(findOneResponse.andReturn().getResponse().getContentAsString());
createdFoo.setName("updated name");
this.mvc
.perform(put(createdResourceUri).contentType(MediaType.APPLICATION_JSON).content(serializeFoo(createdFoo)));
// When
ResultActions result = this.mvc
.perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.IF_NONE_MATCH, etag));
// Then
result.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ETAG, "\"1\""));
}
}
| 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/src/test/java/com/baeldung/web/FooLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooLiveTest.java | package com.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.common.web.AbstractBasicLiveTest;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.ConfigIntegrationTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooLiveTest extends AbstractBasicLiveTest<Foo> {
public FooLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
}
| 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/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java | package com.baeldung.web;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Collections;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.service.IFooService;
import com.baeldung.web.controller.FooController;
import com.baeldung.web.exception.CustomException1;
import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent;
/**
*
* We'll start only the web layer.
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerWebLayerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private IFooService service;
@MockBean
private ApplicationEventPublisher publisher;
@Test()
public void givenPresentFoo_whenFindPaginatedRequest_thenPageWithFooRetrieved() throws Exception {
Page<Foo> page = new PageImpl<>(Collections.singletonList(new Foo("fooName")));
when(service.findPaginated(0, 2)).thenReturn(page);
doNothing().when(publisher)
.publishEvent(any(PaginatedResultsRetrievedEvent.class));
this.mockMvc.perform(get("/foos")
.param("page", "0")
.param("size", "2")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", Matchers.hasSize(1)));
}
@Test
public void delete_forException_fromService() throws Exception {
Mockito.when(service.findAll()).thenThrow(new CustomException1());
this.mockMvc.perform(get("/foos")).andDo(h -> {
final Exception expectedException = h.getResolvedException();
Assert.assertTrue(expectedException instanceof CustomException1);
});
}
}
| 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/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java | package com.baeldung.web.util;
public final class HTTPLinkHeaderUtil {
private HTTPLinkHeaderUtil() {
throw new AssertionError();
}
//
public static String extractURIByRel(final String linkHeader, final String rel) {
if (linkHeader == null) {
return null;
}
String uriWithSpecifiedRel = null;
final String[] links = linkHeader.split(", ");
String linkRelation;
for (final String link : links) {
final int positionOfSeparator = link.indexOf(';');
linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim();
if (extractTypeOfRelation(linkRelation).equals(rel)) {
uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1);
break;
}
}
return uriWithSpecifiedRel;
}
private static Object extractTypeOfRelation(final String linkRelation) {
final int positionOfEquals = linkRelation.indexOf('=');
return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim();
}
}
| 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/src/test/java/com/baeldung/web/error/ErrorHandlingLiveTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/web/error/ErrorHandlingLiveTest.java | package com.baeldung.web.error;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.not;
import static com.baeldung.Consts.APPLICATION_PORT;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class ErrorHandlingLiveTest {
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest";
private static final String EXCEPTION_ENDPOINT = BASE_URL + "/exception";
private static final String ERROR_RESPONSE_KEY_PATH = "error";
private static final String XML_RESPONSE_KEY_PATH = "xmlkey";
private static final String LOCALE_RESPONSE_KEY_PATH = "locale";
private static final String CAUSE_RESPONSE_KEY_PATH = "cause";
private static final String RESPONSE_XML_ROOT = "Map";
private static final String XML_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + XML_RESPONSE_KEY_PATH;
private static final String LOCALE_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + LOCALE_RESPONSE_KEY_PATH;
private static final String CAUSE_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + CAUSE_RESPONSE_KEY_PATH;
private static final String CAUSE_RESPONSE_VALUE = "Error in the faulty controller!";
private static final String XML_RESPONSE_VALUE = "the XML response is different!";
@Test
public void whenRequestingFaultyEndpointAsJson_thenReceiveDefaultResponseWithConfiguredAttrs() {
given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.get(EXCEPTION_ENDPOINT)
.then()
.body("$", hasKey(LOCALE_RESPONSE_KEY_PATH))
.body(CAUSE_RESPONSE_KEY_PATH, is(CAUSE_RESPONSE_VALUE))
.body("$", not(hasKey(ERROR_RESPONSE_KEY_PATH)))
.body("$", not(hasKey(XML_RESPONSE_KEY_PATH)));
}
@Test
public void whenRequestingFaultyEndpointAsXml_thenReceiveXmlResponseWithConfiguredAttrs() {
given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)
.get(EXCEPTION_ENDPOINT)
.then()
.body(LOCALE_RESPONSE_KEY_XML_PATH, isA(String.class))
.body(CAUSE_RESPONSE_KEY_XML_PATH, is(CAUSE_RESPONSE_VALUE))
.body(RESPONSE_XML_ROOT, not(hasKey(ERROR_RESPONSE_KEY_PATH)))
.body(XML_RESPONSE_KEY_XML_PATH, is(XML_RESPONSE_VALUE));
}
@Test
public void whenRequestingFaultyEndpointAsHtml_thenReceiveWhitelabelPageResponse() throws Exception {
try (WebClient webClient = new WebClient()) {
webClient.getOptions()
.setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = webClient.getPage(EXCEPTION_ENDPOINT);
assertThat(page.getBody().asNormalizedText()).contains("Whitelabel Error Page");
}
}
}
| 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/src/test/java/com/baeldung/springpagination/PostDtoUnitTest.java | spring-web-modules/spring-boot-rest/src/test/java/com/baeldung/springpagination/PostDtoUnitTest.java | package com.baeldung.springpagination;
import static org.junit.Assert.assertEquals;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.junit.Test;
import org.modelmapper.ModelMapper;
import com.baeldung.springpagination.dto.PostDto;
import com.baeldung.springpagination.model.Post;
public class PostDtoUnitTest {
private ModelMapper modelMapper = new ModelMapper();
@Test
public void whenConvertPostEntityToPostDto_thenCorrect() {
Post post = new Post();
post.setId(1L);
post.setTitle(randomAlphabetic(6));
post.setUrl("www.test.com");
PostDto postDto = modelMapper.map(post, PostDto.class);
assertEquals(post.getId(), postDto.getId());
assertEquals(post.getTitle(), postDto.getTitle());
assertEquals(post.getUrl(), postDto.getUrl());
}
@Test
public void whenConvertPostDtoToPostEntity_thenCorrect() {
PostDto postDto = new PostDto();
postDto.setId(1L);
postDto.setTitle(randomAlphabetic(6));
postDto.setUrl("www.test.com");
Post post = modelMapper.map(postDto, Post.class);
assertEquals(postDto.getId(), post.getId());
assertEquals(postDto.getTitle(), post.getTitle());
assertEquals(postDto.getUrl(), post.getUrl());
}
} | 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/src/main/java/com/baeldung/SpringBootRestApplication.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/SpringBootRestApplication.java | package com.baeldung;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
| 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/src/main/java/com/baeldung/services/OrderService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/services/OrderService.java | package com.baeldung.services;
import java.util.List;
import com.baeldung.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/src/main/java/com/baeldung/services/CustomerServiceImpl.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/services/CustomerServiceImpl.java | package com.baeldung.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.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/src/main/java/com/baeldung/services/OrderServiceImpl.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/services/OrderServiceImpl.java | package com.baeldung.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.persistence.model.Customer;
import com.baeldung.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/src/main/java/com/baeldung/services/CustomerService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/services/CustomerService.java | package com.baeldung.services;
import java.util.List;
import com.baeldung.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/src/main/java/com/baeldung/persistence/IOperations.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java | package com.baeldung.persistence;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.domain.Page;
public interface IOperations<T extends Serializable> {
// read - one
T findById(final long id);
// read - all
List<T> findAll();
Page<T> findPaginated(int page, int size);
// 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/src/main/java/com/baeldung/persistence/dao/IFooDao.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/dao/IFooDao.java | package com.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.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/src/main/java/com/baeldung/persistence/service/IFooService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/service/IFooService.java | package com.baeldung.persistence.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.baeldung.persistence.IOperations;
import com.baeldung.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/src/main/java/com/baeldung/persistence/service/impl/FooService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java | package com.baeldung.persistence.service.impl;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.service.IFooService;
import com.baeldung.persistence.service.common.AbstractService;
import com.google.common.collect.Lists;
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;
@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/src/main/java/com/baeldung/persistence/service/common/AbstractService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java | package com.baeldung.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.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());
}
@Override
public Page<T> findPaginated(final int page, final int size) {
return getDao().findAll(PageRequest.of(page, size));
}
// 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/src/main/java/com/baeldung/persistence/model/Foo.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Foo.java | package com.baeldung.persistence.model;
import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Version;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@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/src/main/java/com/baeldung/persistence/model/Customer.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Customer.java | package com.baeldung.persistence.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.springframework.hateoas.RepresentationModel;
import java.util.Map;
@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/src/main/java/com/baeldung/persistence/model/Order.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/model/Order.java | package com.baeldung.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/src/main/java/com/baeldung/persistence/config/CustomH2Dialect.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/persistence/config/CustomH2Dialect.java | package com.baeldung.persistence.config;
import org.hibernate.dialect.H2Dialect;
/**
* Since H2 1.4.200. the behavior of the drop table commands has changed.
* Tables are not dropped in a correct order.
* Until this is properly fixed directly in Hibernate project,
* let's use this custom H2Dialect class to solve this issue.
*
* @see <a href="https://hibernate.atlassian.net/browse/HHH-13711">https://hibernate.atlassian.net/browse/HHH-13711</a>
* @see <a href="https://github.com/hibernate/hibernate-orm/pull/3093">https://github.com/hibernate/hibernate-orm/pull/3093</a>
*/
public class CustomH2Dialect extends H2Dialect {
@Override
public boolean dropConstraints() {
return true;
}
@Override
public boolean supportsIfExistsAfterAlterTable() {
return true;
}
}
| 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/src/main/java/com/baeldung/spring/PersistenceConfig.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/spring/PersistenceConfig.java | package com.baeldung.spring;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
@ComponentScan(basePackages = { "com.baeldung.persistence", "com.baeldung.springpagination" })
@EnableJpaRepositories(basePackages = {"com.baeldung.persistence.dao", "com.baeldung.springpagination.repository"})
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model", "com.baeldung.springpagination.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// vendorAdapter.set
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
} | 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/src/main/java/com/baeldung/spring/ConverterExtensionsConfig.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/spring/ConverterExtensionsConfig.java | package com.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
/**
* Another possibility is to create a bean which will be automatically added to the Spring Boot Autoconfigurations.
*
* ATTENTION: Multiple converter registration of the same type most likely causes problem (serialize twice, etc.)
* Therefore, be sure to remove manually added XML message converter first then uncomment
* this @{@link org.springframework.context.annotation.Configuration} to use
*/
//@Configuration
public class ConverterExtensionsConfig {
@Bean
public HttpMessageConverter<Object> createXmlHttpMessageConverter() {
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
}
| 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/src/main/java/com/baeldung/spring/WebConfig.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java | package com.baeldung.spring;
import java.util.List;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(createXmlHttpMessageConverter());
}
/**
* There is another possibility to add a message converter, see {@link ConverterExtensionsConfig}
*/
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
// Etags
// If we're not using Spring Boot we can make use of
// AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters
@Bean
public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() {
FilterRegistrationBean<ShallowEtagHeaderFilter> filterRegistrationBean =
new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
filterRegistrationBean.addUrlPatterns("/foos/*");
filterRegistrationBean.setName("etagFilter");
return filterRegistrationBean;
}
// We can also just declare the filter directly
// @Bean
// public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
// return new ShallowEtagHeaderFilter();
// }
}
| 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/src/main/java/com/baeldung/web/controller/CustomerController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/CustomerController.java | package com.baeldung.web.controller;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
import com.baeldung.services.CustomerService;
import com.baeldung.services.OrderService;
@RestController
@RequestMapping(value = "/customers")
@EnableHypermediaSupport(type = HypermediaType.HAL)
public class CustomerController {
@Autowired
private CustomerService customerService;
@Autowired
private OrderService orderService;
@GetMapping("/{customerId}")
public Customer getCustomerById(@PathVariable final String customerId) {
return customerService.getCustomerDetail(customerId);
}
@GetMapping("/{customerId}/{orderId}")
public Order getOrderById(@PathVariable final String customerId, @PathVariable final String orderId) {
return orderService.getOrderByIdForCustomer(customerId, orderId);
}
@GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" })
public CollectionModel<Order> getOrdersForCustomer(@PathVariable final String customerId) {
final List<Order> orders = orderService.getAllOrdersForCustomer(customerId);
for (final Order order : orders) {
final Link selfLink = linkTo(
methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel();
order.add(selfLink);
}
Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel();
CollectionModel<Order> result = CollectionModel.of(orders, link);
return result;
}
@GetMapping(produces = { "application/hal+json" })
public CollectionModel<Customer> getAllCustomers() {
final List<Customer> allCustomers = customerService.allCustomers();
for (final Customer customer : allCustomers) {
String customerId = customer.getCustomerId();
Link selfLink = linkTo(CustomerController.class).slash(customerId)
.withSelfRel();
customer.add(selfLink);
if (orderService.getAllOrdersForCustomer(customerId)
.size() > 0) {
final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId))
.withRel("allOrders");
customer.add(ordersLink);
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
CollectionModel<Customer> result = CollectionModel.of(allCustomers, link);
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-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java | package com.baeldung.web.controller;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.UriComponentsBuilder;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.service.IFooService;
import com.baeldung.web.exception.CustomException1;
import com.baeldung.web.exception.CustomException2;
import com.baeldung.web.exception.MyResourceNotFoundException;
import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent;
import com.baeldung.web.hateoas.event.ResourceCreatedEvent;
import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import com.baeldung.web.util.RestPreconditions;
import com.google.common.base.Preconditions;
@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();
}
// API
// Note: the global filter overrides the ETag value we set here. We can still analyze its behaviour in the Integration Test.
@GetMapping(value = "/{id}/custom-etag")
public ResponseEntity<Foo> findByIdWithCustomEtag(@PathVariable("id") final Long id,
final HttpServletResponse response) {
final Foo foo = RestPreconditions.checkFound(service.findById(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return ResponseEntity.ok()
.eTag(Long.toString(foo.getVersion()))
.body(foo);
}
// 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);
}
}
// read - all
@GetMapping
public List<Foo> findAll() {
return service.findAll();
}
@GetMapping(params = { "page", "size" })
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size,
final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(page, size);
if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page,
resultPage.getTotalPages(), size));
return resultPage.getContent();
}
@GetMapping("/pageable")
public List<Foo> findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder,
final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(pageable);
if (pageable.getPageNumber() > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response,
pageable.getPageNumber(), resultPage.getTotalPages(), pageable.getPageSize()));
return resultPage.getContent();
}
// 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;
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findById(resource.getId()));
service.update(resource);
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException(final Exception ex) {
final String error = "Application specific error handling";
logger.error(error, ex);
}
}
| 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/src/main/java/com/baeldung/web/controller/FaultyRestController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/FaultyRestController.java | package com.baeldung.web.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FaultyRestController {
@GetMapping("/exception")
public ResponseEntity<Void> requestWithException() {
throw new RuntimeException("Error in the faulty controller!");
}
}
| 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/src/main/java/com/baeldung/web/controller/RootController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java | package com.baeldung.web.controller;
import java.net.URI;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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.web.util.LinkUtil;
@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/src/main/java/com/baeldung/web/controller/students/Student.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java | package com.baeldung.web.controller.students;
public class Student {
private long id;
private String firstName;
private String lastName;
public Student() {}
public Student(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Student(long id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
| 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/src/main/java/com/baeldung/web/controller/students/StudentService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java | package com.baeldung.web.controller.students;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
// DB repository mock
private Map<Long, Student> repository = Arrays.asList(
new Student[]{
new Student(1, "Alan","Turing"),
new Student(2, "Sebastian","Bach"),
new Student(3, "Pablo","Picasso"),
}).stream()
.collect(Collectors.toConcurrentMap(Student::getId, Function.identity()));
// DB id sequence mock
private AtomicLong sequence = new AtomicLong(3);
public List<Student> readAll() {
return repository.values().stream().collect(Collectors.toList());
}
public Student read(Long id) {
return repository.get(id);
}
public Student create(Student student) {
long key = sequence.incrementAndGet();
student.setId(key);
repository.put(key, student);
return student;
}
public Student update(Long id, Student student) {
student.setId(id);
Student oldStudent = repository.replace(id, student);
return oldStudent == null ? null : student;
}
public void delete(Long id) {
repository.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-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java | package com.baeldung.web.controller.students;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.support.ServletUriComponentsBuilder;
import com.baeldung.web.controller.students.StudentService;
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/")
public List<Student> read() {
return service.readAll();
}
@GetMapping("/{id}")
public ResponseEntity<Student> read(@PathVariable("id") Long id) {
Student foundStudent = service.read(id);
if (foundStudent == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(foundStudent);
}
}
@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
Student createdStudent = service.create(student);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdStudent.getId())
.toUri();
return ResponseEntity.created(uri)
.body(createdStudent);
}
@PutMapping("/{id}")
public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable Long id) {
Student updatedStudent = service.update(id, student);
if (updatedStudent == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(updatedStudent);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Object> deleteStudent(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
}
| 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/src/main/java/com/baeldung/web/util/RestPreconditions.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/util/RestPreconditions.java | package com.baeldung.web.util;
import org.springframework.http.HttpStatus;
import com.baeldung.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/src/main/java/com/baeldung/web/util/LinkUtil.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/util/LinkUtil.java | package com.baeldung.web.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/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java | package com.baeldung.web.error;
import com.baeldung.web.exception.MyResourceNotFoundException;
import jakarta.persistence.EntityNotFoundException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public RestResponseEntityExceptionHandler() {
super();
}
// API
// 400
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleBadRequest(final ConstraintViolationException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler({ DataIntegrityViolationException.class })
public ResponseEntity<Object> handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
final String bodyOfResponse = "This should be application specific";
// ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// 404
@ExceptionHandler(value = { EntityNotFoundException.class, MyResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
// 409
@ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class })
protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
}
// 412
// 500
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class })
/*500*/public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
} | 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/src/main/java/com/baeldung/web/error/CustomExceptionObject.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/error/CustomExceptionObject.java | package com.baeldung.web.error;
public class CustomExceptionObject {
private String message;
public String getMessage() {
return message;
}
public CustomExceptionObject setMessage(String message) {
this.message = message;
return this;
}
}
| 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/src/main/java/com/baeldung/web/error/RestResponseStatusExceptionResolver.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/error/RestResponseStatusExceptionResolver.java | package com.baeldung.web.error;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Component
public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(RestResponseStatusExceptionResolver.class);
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
try {
if (ex instanceof IllegalArgumentException) {
return handleIllegalArgument(
(IllegalArgumentException) ex, request, response, handler);
}
} catch (Exception handlerException) {
logger.warn("Handling of [{}] resulted in Exception", ex.getClass().getName(), handlerException);
}
return null;
}
private ModelAndView handleIllegalArgument(IllegalArgumentException ex,
final HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
final String accept = request.getHeader(HttpHeaders.ACCEPT);
response.sendError(HttpServletResponse.SC_CONFLICT);
response.setHeader("ContentType", accept);
final ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("error", prepareErrorResponse(accept));
return modelAndView;
}
/** Prepares error object based on the provided accept type.
* @param accept The Accept header present in the request.
* @return The response to return
* @throws JsonProcessingException
*/
private String prepareErrorResponse(String accept) throws JsonProcessingException {
final Map<String, String> error = new HashMap<>();
error.put("Error", "Application specific error message");
final String response;
if(MediaType.APPLICATION_JSON_VALUE.equals(accept)) {
response = new ObjectMapper().writeValueAsString(error);
} else {
response = new XmlMapper().writeValueAsString(error);
}
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/src/main/java/com/baeldung/web/error/MyGlobalExceptionHandler.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/error/MyGlobalExceptionHandler.java | package com.baeldung.web.error;
import com.baeldung.web.exception.CustomException1;
import com.baeldung.web.exception.CustomException2;
import com.baeldung.web.exception.CustomException3;
import com.baeldung.web.exception.CustomException4;
import com.baeldung.web.exception.CustomException5;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.nio.file.AccessDeniedException;
@RestControllerAdvice
public class MyGlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(CustomException1.class)
public void handleException1() {
//
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler
public ProblemDetail handleException2(CustomException2 ex) {
return ProblemDetail
.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
ex.getMessage()
);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler( produces = MediaType.APPLICATION_JSON_VALUE )
public CustomExceptionObject handleException3Json(CustomException3 ex) {
return new CustomExceptionObject()
.setMessage("custom exception 3: " + ex.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler( produces = MediaType.TEXT_PLAIN_VALUE )
public String handleException3Text(CustomException3 ex) {
return "custom exception 3: " + ex.getMessage();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({
CustomException4.class,
CustomException5.class
})
public ResponseEntity<CustomExceptionObject> handleException45(Exception ex) {
return ResponseEntity
.badRequest()
.body(
new CustomExceptionObject()
.setMessage( "custom exception 4/5: " + ex.getMessage())
);
}
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler( AccessDeniedException.class )
public void handleAccessDeniedException() {
// ...
}
}
| 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/src/main/java/com/baeldung/web/exception/CustomException1.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException1.java | package com.baeldung.web.exception;
public class CustomException1 extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| 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/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java | package com.baeldung.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException 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-boot-rest/src/main/java/com/baeldung/web/exception/CustomException5.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException5.java | package com.baeldung.web.exception;
import java.io.Serial;
public class CustomException5 extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
public CustomException5(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-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java | package com.baeldung.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException 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-boot-rest/src/main/java/com/baeldung/web/exception/CustomException2.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException2.java | package com.baeldung.web.exception;
public class CustomException2 extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| 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/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java | package com.baeldung.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/src/main/java/com/baeldung/web/exception/CustomException4.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException4.java | package com.baeldung.web.exception;
import java.io.Serial;
public class CustomException4 extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
public CustomException4(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-boot-rest/src/main/java/com/baeldung/web/exception/CustomException3.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/exception/CustomException3.java | package com.baeldung.web.exception;
import java.io.Serial;
public class CustomException3 extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
}
| 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/src/main/java/com/baeldung/web/hateoas/event/ResourceCreatedEvent.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/ResourceCreatedEvent.java | package com.baeldung.web.hateoas.event;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
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/src/main/java/com/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java | package com.baeldung.web.hateoas.event;
import java.io.Serializable;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.util.UriComponentsBuilder;
/**
* 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/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java | package com.baeldung.web.hateoas.event;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
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/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java | package com.baeldung.web.hateoas.listener;
import jakarta.servlet.http.HttpServletResponse;
import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import com.baeldung.web.util.LinkUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@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/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java | package com.baeldung.web.hateoas.listener;
import java.util.StringJoiner;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent;
import com.baeldung.web.util.LinkUtil;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@SuppressWarnings({ "rawtypes" })
@Component
class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationListener<PaginatedResultsRetrievedEvent> {
private static final String PAGE = "page";
public PaginatedResultsRetrievedDiscoverabilityListener() {
super();
}
// API
@Override
public final void onApplicationEvent(final PaginatedResultsRetrievedEvent ev) {
Preconditions.checkNotNull(ev);
addLinkHeaderOnPagedResourceRetrieval(ev.getUriBuilder(), ev.getResponse(), ev.getClazz(), ev.getPage(),
ev.getTotalPages(), ev.getPageSize());
}
// - note: at this point, the URI is transformed into plural (added `s`) in a hardcoded way - this will change in the future
final void addLinkHeaderOnPagedResourceRetrieval(final UriComponentsBuilder uriBuilder,
final HttpServletResponse response, final Class clazz, final int page, final int totalPages,
final int pageSize) {
plural(uriBuilder, clazz);
final StringJoiner linkHeader = new StringJoiner(", ");
if (hasNextPage(page, totalPages)) {
final String uriForNextPage = constructNextPageUri(uriBuilder, page, pageSize);
linkHeader.add(LinkUtil.createLinkHeader(uriForNextPage, LinkUtil.REL_NEXT));
}
if (hasPreviousPage(page)) {
final String uriForPrevPage = constructPrevPageUri(uriBuilder, page, pageSize);
linkHeader.add(LinkUtil.createLinkHeader(uriForPrevPage, LinkUtil.REL_PREV));
}
if (hasFirstPage(page)) {
final String uriForFirstPage = constructFirstPageUri(uriBuilder, pageSize);
linkHeader.add(LinkUtil.createLinkHeader(uriForFirstPage, LinkUtil.REL_FIRST));
}
if (hasLastPage(page, totalPages)) {
final String uriForLastPage = constructLastPageUri(uriBuilder, totalPages, pageSize);
linkHeader.add(LinkUtil.createLinkHeader(uriForLastPage, LinkUtil.REL_LAST));
}
if (linkHeader.length() > 0) {
response.addHeader(HttpHeaders.LINK, linkHeader.toString());
}
}
final String constructNextPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page + 1)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructPrevPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page - 1)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructFirstPageUri(final UriComponentsBuilder uriBuilder, final int size) {
return uriBuilder.replaceQueryParam(PAGE, 0)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructLastPageUri(final UriComponentsBuilder uriBuilder, final int totalPages, final int size) {
return uriBuilder.replaceQueryParam(PAGE, totalPages)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final boolean hasNextPage(final int page, final int totalPages) {
return page < (totalPages - 1);
}
final boolean hasPreviousPage(final int page) {
return page > 0;
}
final boolean hasFirstPage(final int page) {
return hasPreviousPage(page);
}
final boolean hasLastPage(final int page, final int totalPages) {
return (totalPages > 1) && hasNextPage(page, totalPages);
}
// template
protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) {
final String resourceName = clazz.getSimpleName()
.toLowerCase() + "s";
uriBuilder.path("/" + resourceName);
}
}
| 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/src/main/java/com/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java | package com.baeldung.web.hateoas.listener;
import com.baeldung.web.hateoas.event.ResourceCreatedEvent;
import com.google.common.base.Preconditions;
import java.net.URI;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpHeaders;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@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/src/main/java/com/baeldung/web/config/MyCustomErrorAttributes.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/config/MyCustomErrorAttributes.java | package com.baeldung.web.config;
import java.util.Map;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
@Component
public class MyCustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
errorAttributes.put("locale", webRequest.getLocale()
.toString());
errorAttributes.remove("error");
errorAttributes.put("cause", errorAttributes.get("message"));
errorAttributes.remove("message");
errorAttributes.put("status", String.valueOf(errorAttributes.get("status")));
return errorAttributes;
}
}
| 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/src/main/java/com/baeldung/web/config/MyErrorController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/web/config/MyErrorController.java | package com.baeldung.web.config;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
public class MyErrorController extends BasicErrorController {
public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes, serverProperties.getError());
}
@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.APPLICATION_XML));
body.put("xmlkey", "the XML response is different!");
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
}
}
| 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/src/main/java/com/baeldung/springpagination/controller/PostRestController.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java | package com.baeldung.springpagination.controller;
import com.baeldung.springpagination.dto.PostDto;
import com.baeldung.springpagination.model.Post;
import com.baeldung.springpagination.service.IPostService;
import com.baeldung.springpagination.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/posts")
public class PostRestController {
@Autowired
private IPostService postService;
@Autowired
private IUserService userService;
@Autowired
private ModelMapper modelMapper;
@GetMapping
@ResponseBody
public List<PostDto> getPosts(
@PathVariable("page") int page,
@PathVariable("size") int size,
@PathVariable("sortDir") String sortDir,
@PathVariable("sort") String sort) {
List<Post> posts = postService.getPostsList(page, size, sortDir, sort);
return posts.stream()
.map(this::convertToDto)
.collect(Collectors.toList());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public PostDto createPost(@RequestBody PostDto postDto) throws ParseException {
Post post = convertToEntity(postDto);
Post postCreated = postService.createPost(post);
return convertToDto(postCreated);
}
@GetMapping(value = "/{id}")
@ResponseBody
public PostDto getPost(@PathVariable("id") Long id) {
return convertToDto(postService.getPostById(id));
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) throws ParseException {
if(!Objects.equals(id, postDto.getId())){
throw new IllegalArgumentException("IDs don't match");
}
Post post = convertToEntity(postDto);
postService.updatePost(post);
}
private PostDto convertToDto(Post post) {
PostDto postDto = modelMapper.map(post, PostDto.class);
postDto.setSubmissionDate(post.getSubmissionDate(),
userService.getCurrentUser().getPreference().getTimezone());
return postDto;
}
private Post convertToEntity(PostDto postDto) throws ParseException {
Post post = modelMapper.map(postDto, Post.class);
post.setSubmissionDate(postDto.getSubmissionDateConverted(
userService.getCurrentUser().getPreference().getTimezone()));
if (postDto.getId() != null) {
Post oldPost = postService.getPostById(postDto.getId());
post.setRedditID(oldPost.getRedditID());
post.setSent(oldPost.isSent());
}
return post;
}
}
| 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/src/main/java/com/baeldung/springpagination/dto/PostDto.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/PostDto.java | package com.baeldung.springpagination.dto;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class PostDto {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String title;
private String url;
private String date;
private UserDto user;
public Date getSubmissionDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
return dateFormat.parse(this.date);
}
public void setSubmissionDate(Date date, String timezone) {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
this.date = dateFormat.format(date);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
}
| 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/src/main/java/com/baeldung/springpagination/dto/UserDto.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/springpagination/dto/UserDto.java | package com.baeldung.springpagination.dto;
public class UserDto {
private String name;
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-boot-rest/src/main/java/com/baeldung/springpagination/service/UserService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/UserService.java | package com.baeldung.springpagination.service;
import org.springframework.stereotype.Service;
import com.baeldung.springpagination.model.Preference;
import com.baeldung.springpagination.model.User;
@Service
public class UserService implements IUserService {
@Override
public User getCurrentUser() {
Preference preference = new Preference();
preference.setId(1L);
preference.setTimezone("Asia/Calcutta");
User user = new User();
user.setId(1L);
user.setName("Micheal");
user.setPreference(preference);
return user;
}
} | 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/src/main/java/com/baeldung/springpagination/service/IPostService.java | spring-web-modules/spring-boot-rest/src/main/java/com/baeldung/springpagination/service/IPostService.java | package com.baeldung.springpagination.service;
import java.util.List;
import com.baeldung.springpagination.model.Post;
public interface IPostService {
List<Post> getPostsList(int page, int size, String sortDir, String sort);
void updatePost(Post post);
Post createPost(Post post);
Post getPostById(Long id);
}
| 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.