repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java
package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressPartialUpdate { private Integer id; private String address; public HeavyResourceAddressPartialUpdate() { } public HeavyResourceAddressPartialUpdate(Integer id, String address) { this.id = id; this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Item.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Item.java
package com.baeldung.sampleapp.web.dto; import com.fasterxml.jackson.annotation.JsonView; public class Item { @JsonView(Views.Public.class) public int id; @JsonView(Views.Public.class) public String itemName; @JsonView(Views.Internal.class) public String ownerName; public Item() { super(); } public Item(final int id, final String itemName, final String ownerName) { this.id = id; this.itemName = itemName; this.ownerName = ownerName; } public int getId() { return id; } public String getItemName() { return itemName; } public String getOwnerName() { return ownerName; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java
package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressOnly { private Integer id; private String address; public HeavyResourceAddressOnly() { } public HeavyResourceAddressOnly(Integer id, String address) { this.id = id; this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Company.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Company.java
package com.baeldung.sampleapp.web.dto; public class Company { private long id; private String name; public Company() { super(); } public Company(final long id, final String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public long getId() { return id; } public void setId(final long id) { this.id = id; } @Override public String toString() { return "Company [id=" + id + ", name=" + name + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Views.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Views.java
package com.baeldung.sampleapp.web.dto; public class Views { public static class Public { } public static class Internal extends Public { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java
package com.baeldung.sampleapp.web.dto; public class ItemManager { public static Item getById(final int id) { final Item item = new Item(2, "book", "John"); return item; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java
package com.baeldung.sampleapp.web.dto; public class HeavyResource { private Integer id; private String name; private String surname; private Integer age; private String address; public HeavyResource() { } public HeavyResource(Integer id, String name, String surname, Integer age, String address) { this.id = id; this.name = name; this.surname = surname; this.age = age; this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java
spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java
package com.baeldung.sampleapp.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java
spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java
package com.baeldung.unsupportedmediatype; 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.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) public class ApplicationUnitTest { @Autowired private MockMvc mockMvc; @Test public void JsonTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.APPLICATION_JSON_VALUE) .content( "{\n" + " \"name\": \"Andy\",\n" + " \"age\": 1,\n" + " \"address\": \"Hello world\"\n" + "}")) .andExpect(status().isOk()); } @Test public void JsonFailTestCase() throws Exception {// Because no content-type added mockMvc.perform(MockMvcRequestBuilders.post("/user/") .content( "{\n" + " \"name\": \"Andy\",\n" + " \"age\": 1,\n" + " \"address\": \"Hello world\"\n" + "}")) .andExpect(status().isUnsupportedMediaType()); } @Test public void XmlTestCase() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.APPLICATION_XML_VALUE) .content("<user><name>Andy</name><age>1</age><address>Hello world</address></user>")) .andExpect(status().isOk()); } @Test public void StringFailTestCase() throws Exception { // Because content-type is not supported mockMvc.perform(MockMvcRequestBuilders.post("/user/") .contentType(MediaType.TEXT_PLAIN_VALUE) .content("<user><name>Andy</name><age>1</age><address>Hello world</address></user>")) .andExpect(status().isUnsupportedMediaType()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/longpolling/BakeryControllerIntegrationTest.java
spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/longpolling/BakeryControllerIntegrationTest.java
package com.baeldung.longpolling; 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.mock.web.MockAsyncContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.io.IOException; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; @AutoConfigureMockMvc @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BakeryControllerIntegrationTest { @Autowired private MockMvc mockMvc; @Test public void givenDeferredResultTimesOut_ThenErrorResponseIsRecieved() throws Exception { MvcResult asyncListener = mockMvc .perform(MockMvcRequestBuilders.get("/api/bake/cookie?bakeTime=6000")) .andExpect(request().asyncStarted()) .andReturn(); enableTimeout(asyncListener); String response = mockMvc .perform(asyncDispatch(asyncListener)) .andReturn() .getResponse() .getContentAsString(); assertThat(response) .isEqualTo("the bakery is not responding in allowed time"); } @Test public void givenDeferredResultSuccessful_ThenSuccessResponseIsRecieved() throws Exception { MvcResult asyncListener = mockMvc .perform(MockMvcRequestBuilders.get("/api/bake/cookie?bakeTime=1000")) .andExpect(request().asyncStarted()) .andReturn(); String response = mockMvc .perform(asyncDispatch(asyncListener)) .andReturn() .getResponse() .getContentAsString(); assertThat(response) .isEqualTo("Bake for cookie complete and order dispatched. Enjoy!"); } private static void enableTimeout(MvcResult asyncListener) throws IOException { ((MockAsyncContext) asyncListener .getRequest() .getAsyncContext()) .getListeners() .get(0) .onTimeout(null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/status/ExampleControllerIntegrationTest.java
spring-web-modules/spring-rest-http-2/src/test/java/com/baeldung/status/ExampleControllerIntegrationTest.java
package com.baeldung.status; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.client.AutoConfigureWebClient; 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; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class ExampleControllerIntegrationTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception { mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable()); } @Test public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception { mockMvc.perform(get("/exception")).andExpect(status().isForbidden()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRest2Application { public static void main(String[] args) { SpringApplication.run(SpringBootRest2Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/User.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/User.java
package com.baeldung.unsupportedmediatype; import jakarta.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlRootElement public class User implements Serializable { private Integer id; private String name; private Integer age; private String address; public User(){ } public User(Integer id, String name, Integer age, String address) { this.id = id; this.name = name; this.age = age; this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java
package com.baeldung.unsupportedmediatype; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UnsupportedMediaTypeApplication { public static void main(String[] args) { SpringApplication.run(UnsupportedMediaTypeApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java
package com.baeldung.unsupportedmediatype; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.Collections; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @GetMapping(value = "/") List<User> getAllUsers(){ return Collections.singletonList(new User(1, "Andy", 28, "14th Street")); } @GetMapping(value = "/{user-id}") User getUser(@PathVariable("user-id") Integer userId){ return new User(userId, "Andy", 28, "14th Street"); } @PostMapping(value = "/", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) void AddUser(@RequestBody User user){ // Adding the User in the repository } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/SwaggerUIDisableApplication.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/SwaggerUIDisableApplication.java
package com.baeldung.swaggerui.disable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SwaggerUIDisableApplication { public static void main(String[] args) { SpringApplication.run(SwaggerUIDisableApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java
package com.baeldung.swaggerui.disable.controllers; import io.swagger.v3.oas.annotations.Operation; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class VersionController { private final Environment environment; public VersionController(Environment environment) { this.environment = environment; } @Operation(summary = "Get the currently deployed API version and active Spring profiles") @GetMapping("/api/version") public Version getVersion() { return new Version("1.0", environment.getActiveProfiles()); } private static class Version { private final String version; private String[] activeProfiles; private Version(String version, String[] activeProfiles) { this.version = version; this.activeProfiles = activeProfiles; } public String getVersion() { return version; } public String[] getActiveProfiles() { return activeProfiles; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java
package com.baeldung.swaggerui.disable.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; @Profile("!prod && swagger") //@Profile("!prod") // @Profile("swagger") // @ConditionalOnExpression(value = "${useSwagger:false}") @Configuration public class SwaggerConfig { @Bean public OpenAPI openAPI() { return new OpenAPI().info(new Info().title("SpringDoc Disable SwaggerUI example") .description("SpringDoc Disable SwaggerUI application") .version("v0.0.1")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/longpolling/controller/BakeryController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/longpolling/controller/BakeryController.java
package com.baeldung.longpolling.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static java.lang.String.format; /** * Long polling controller example. */ @RestController @RequestMapping("/api") public class BakeryController { private final static Logger LOG = LoggerFactory.getLogger(BakeryController.class); private final static Long LONG_POLLING_TIMEOUT = 5000L; private ExecutorService bakers; public BakeryController() { bakers = Executors.newFixedThreadPool(5); } @GetMapping("/bake/{bakedGood}") public DeferredResult<String> publisher(@PathVariable String bakedGood, @RequestParam Integer bakeTime) { DeferredResult<String> output = new DeferredResult<>(LONG_POLLING_TIMEOUT); bakers.execute(() -> { try { Thread.sleep(bakeTime); output.setResult(format("Bake for %s complete and order dispatched. Enjoy!", bakedGood)); } catch (Exception e) { output.setErrorResult("Something went wrong with your order!"); } }); output.onTimeout(() -> output.setErrorResult("the bakery is not responding in allowed time")); return output; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/longpolling/client/LongPollingBakeryClient.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/longpolling/client/LongPollingBakeryClient.java
package com.baeldung.longpolling.client; import io.netty.handler.timeout.ReadTimeoutException; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Component; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.function.client.WebClient; import java.time.Duration; @Component public class LongPollingBakeryClient { public String callBakeWithRestTemplate(RestTemplateBuilder restTemplateBuilder) { RestTemplate restTemplate = restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(10)) .setReadTimeout(Duration.ofSeconds(10)) .build(); try { return restTemplate.getForObject("/api/bake/cookie?bakeTime=1000", String.class); } catch (ResourceAccessException e) { throw e; } } public String callBakeWithWebClient() { WebClient webClient = WebClient.create(); try { return webClient.get() .uri("/api/bake/cookie?bakeTime=1000") .retrieve() .bodyToFlux(String.class) .timeout(Duration.ofSeconds(10)) .blockFirst(); } catch (ReadTimeoutException e) { throw e; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/deffered/controllers/DeferredResultController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/deffered/controllers/DeferredResultController.java
package com.baeldung.deffered.controllers; import java.util.concurrent.ForkJoinPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; @RestController public class DeferredResultController { private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class); @GetMapping("/async-deferredresult") public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) { LOG.info("Received async-deferredresult request"); DeferredResult<ResponseEntity<?>> output = new DeferredResult<>(); ForkJoinPool.commonPool().submit(() -> { LOG.info("Processing in separate thread"); try { Thread.sleep(6000); } catch (InterruptedException e) { } output.setResult(ResponseEntity.ok("ok")); }); LOG.info("servlet thread freed"); return output; } public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) { LOG.info("Received async request with a configured timeout"); DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l); deferredResult.onTimeout(new Runnable() { @Override public void run() { deferredResult.setErrorResult( ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred.")); } }); ForkJoinPool.commonPool().submit(() -> { LOG.info("Processing in separate thread"); try { Thread.sleep(600l); deferredResult.setResult(ResponseEntity.ok("ok")); } catch (InterruptedException e) { LOG.info("Request processing interrupted"); deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("INTERNAL_SERVER_ERROR occurred.")); } }); LOG.info("servlet thread freed"); return deferredResult; } public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) { DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(); ForkJoinPool.commonPool().submit(() -> { try { // Exception occurred in processing throw new Exception(); } catch (Exception e) { LOG.info("Request processing failed"); deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("INTERNAL_SERVER_ERROR occurred.")); } }); return deferredResult; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/ExampleController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/ExampleController.java
package com.baeldung.status; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ExampleController { @RequestMapping(value = "/controller", method = RequestMethod.GET) @ResponseBody public ResponseEntity sendViaResponseEntity() { return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE); } @RequestMapping(value = "/exception", method = RequestMethod.GET) @ResponseBody public ResponseEntity sendViaException() { throw new ForbiddenException(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/MvcConfig.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/MvcConfig.java
package com.baeldung.status; import java.text.SimpleDateFormat; import java.util.List; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml */ @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.status" }) public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); } // @Override public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) { final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true) .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/ForbiddenException.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/status/ForbiddenException.java
package com.baeldung.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message") public class ForbiddenException extends RuntimeException { private static final long serialVersionUID = 6826605655586311552L; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressRepository.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressRepository.java
package com.baeldung.putvspost; import org.springframework.data.jpa.repository.JpaRepository; public interface AddressRepository extends JpaRepository<Address, Long> { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressController.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/AddressController.java
package com.baeldung.putvspost; import java.util.List; import java.util.Optional; 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.RestController; @RestController public class AddressController { private final AddressRepository repository; AddressController(AddressRepository repository) { this.repository = repository; } @GetMapping("/addresses") List<Address> getAllAddresses() { return repository.findAll(); } @GetMapping("/addresses/{id}") Optional<Address> getAddressesById(@PathVariable Long id) { return repository.findById(id); } @PostMapping("/addresses") Address createNewAddress(@RequestBody Address newAddress) { return repository.save(newAddress); } @PutMapping("/addresses/{id}") Address replaceEmployee(@RequestBody Address newAddress, @PathVariable Long id) { return repository.findById(id) .map(address -> { address.setCity(newAddress.getCity()); address.setPostalCode(newAddress.getPostalCode()); return repository.save(address); }) .orElseGet(() -> { return repository.save(newAddress); }); } @DeleteMapping("/addresses/{id}") void deleteEmployee(@PathVariable Long id) { repository.deleteById(id); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/Address.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/Address.java
package com.baeldung.putvspost; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @Entity public class Address { private @Id @GeneratedValue Long id; private String name; private String city; private String postalCode; Address() { } public Address(String name, String city, String postalCode) { this.name = name; this.city = city; this.postalCode = postalCode; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "Address [id=" + id + ", name=" + name + ", city=" + city + ", postalCode=" + postalCode + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java
spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/putvspost/PutVsPostApplication.java
package com.baeldung.putvspost; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PutVsPostApplication { public static void main(String[] args) { SpringApplication.run(PutVsPostApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerServiceImplUnitTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerServiceImplUnitTest.java
package com.baeldung.service.impl; import com.baeldung.model.Customer; import com.baeldung.service.CustomerIdGenerator; import com.baeldung.service.CustomerService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.HashMap; import java.util.Map; import static com.baeldung.model.Customer.fromCustomer; import static java.util.Arrays.asList; import static java.util.Optional.empty; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class CustomerServiceImplUnitTest { @Mock private CustomerIdGenerator mockCustomerIdGenerator; private CustomerService customerService; @Before public void setup() { customerService = new CustomerServiceImpl(mockCustomerIdGenerator); } @Test public void whenCustomerIsCreated_thenNewCustomerDetailsAreCorrect() { Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); given(mockCustomerIdGenerator.generateNextId()).willReturn(1); Customer newCustomer = customerService.createCustomer(customer); assertThat(newCustomer.getId()).isEqualTo("1"); assertThat(newCustomer.getTelephone()).isEqualTo("001-555-1234"); assertThat(newCustomer.getFavorites()).containsExactly("Milk", "Eggs"); assertThat(newCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); } @Test public void givenNonExistentCustomer_whenCustomerIsLookedUp_thenCustomerCanNotBeFound() { assertThat(customerService.findCustomer("CUST12345")).isEqualTo(empty()); } @Test public void whenCustomerIsCreated_thenCustomerCanBeFound() { Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); given(mockCustomerIdGenerator.generateNextId()).willReturn(7890); customerService.createCustomer(customer); Customer lookedUpCustomer = customerService.findCustomer("7890").get(); assertThat(lookedUpCustomer.getId()).isEqualTo("7890"); assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-1234"); assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs"); assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); } @Test public void whenCustomerUpdated_thenDetailsUpdatedCorrectly() { given(mockCustomerIdGenerator.generateNextId()).willReturn(7890); Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); Customer newCustomer = customerService.createCustomer(customer); Customer customerWithUpdates = fromCustomer(newCustomer); customerWithUpdates.setTelephone("001-555-6789"); customerService.updateCustomer(customerWithUpdates); Customer lookedUpCustomer = customerService.findCustomer("7890").get(); assertThat(lookedUpCustomer.getId()).isEqualTo("7890"); assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-6789"); assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs"); assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerIdGeneratorImplUnitTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/service/impl/CustomerIdGeneratorImplUnitTest.java
package com.baeldung.service.impl; import com.baeldung.service.CustomerIdGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CustomerIdGeneratorImplUnitTest { @Test public void givenIdGeneratedPreviously_whenGenerated_thenIdIsIncremented(){ CustomerIdGenerator customerIdGenerator = new CustomerIdGeneratorImpl(); int firstId = customerIdGenerator.generateNextId(); assertThat(customerIdGenerator.generateNextId()).isEqualTo(++firstId); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requesttimeout/RequestTimeoutIntegrationTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requesttimeout/RequestTimeoutIntegrationTest.java
package com.baeldung.requesttimeout; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClientResponseException; @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) @RunWith(SpringRunner.class) public class RequestTimeoutIntegrationTest { private WebClient webClient; @Before public void setUp() { webClient = WebClient.builder() .baseUrl("http://localhost:8080") .build(); } @Test(expected = WebClientResponseException.InternalServerError.class) public void givenTransactionTimeout_whenTimeExpires_thenReceiveException() { getAuthor("transactional"); } @Test(expected = WebClientResponseException.InternalServerError.class) public void givenResilience4jTimeLimiter_whenTimeExpires_thenReceiveException() { getAuthor("resilience4j"); } @Test(expected = WebClientResponseException.ServiceUnavailable.class) public void givenMvcRequestTimeout_whenTimeExpires_thenReceiveException() { getAuthor("mvc-request-timeout"); } @Test(expected = WebClientResponseException.InternalServerError.class) public void givenWebClientTimeout_whenTimeExpires_thenReceiveException() { getAuthor("webclient"); } @Test(expected = WebClientResponseException.InternalServerError.class) public void givenRestClientTimeout_whenTimeExpires_thenReceiveException() { getAuthor("restclient"); } private void getAuthor(String authorPath) { webClient.get() .uri(uriBuilder -> uriBuilder .path("/author/" + authorPath) .queryParam("title", "title") .build()) .retrieve() .bodyToMono(String.class) .block(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/uribuilder/SpringUriBuilderUnitTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/uribuilder/SpringUriBuilderUnitTest.java
package com.baeldung.uribuilder; import static org.junit.Assert.assertEquals; import java.util.Collections; import org.junit.Test; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; public class SpringUriBuilderUnitTest { @Test public void constructUri() { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http").host("www.baeldung.com").path("/junit-5") .build(); assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); } @Test public void constructUriEncoded() { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http").host("www.baeldung.com").path("/junit 5") .build().encode(); assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString()); } @Test public void constructUriFromTemplate() { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http").host("www.baeldung.com").path("/{article-name}") .buildAndExpand("junit-5"); assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); } @Test public void constructUriWithQueryParameter() { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http").host("www.google.com").path("/").query("q={keyword}") .buildAndExpand("baeldung"); assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString()); } @Test public void expandWithRegexVar() { String template = "/myurl/{name:[a-z]{1,5}}/show"; UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); assertEquals("/myurl/test/show", uriComponents.getPath()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/responseheaders/ResponseHeaderLiveTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/responseheaders/ResponseHeaderLiveTest.java
package com.baeldung.responseheaders; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ResponseHeaderLiveTest { private static final String BASE_URL = "http://localhost:8080"; private static final String SINGLE_BASE_URL = BASE_URL + "/single-response-header"; private static final String FILTER_BASE_URL = BASE_URL + "/filter-response-header"; private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header"; private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header"; @Autowired private TestRestTemplate template; @Test public void whenHttpServletResponseRequest_thenObtainResponseWithCorrectHeader() { final String requestUrl = "/http-servlet-response"; ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-HttpServletResponse")); } @Test public void whenResponseEntityConstructorRequest_thenObtainResponseWithCorrectHeader() { final String requestUrl = "/response-entity-constructor"; ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityContructor")); } @Test public void whenResponseEntityConstructorAndMultipleHeadersRequest_thenObtainResponseWithCorrectHeaders() { final String requestUrl = "/response-entity-contructor-multiple-headers"; ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityConstructorAndHeaders")); assertThat(responseHeaders).containsEntry("Accept", Arrays.asList(MediaType.APPLICATION_JSON.toString())); } @Test public void whenResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeader() { final String requestUrl = "/response-entity-builder"; ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilder")); } @Test public void whenResponseEntityBuilderAndHttpHeadersRequest_thenObtainResponseWithCorrectHeader() { final String requestUrl = "/response-entity-builder-with-http-headers"; ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilderWithHttpHeaders")); } @Test public void whenFilterWithNoExtraHeaderRequest_thenObtainResponseWithCorrectHeader() { final String requestUrl = "/no-extra-header"; ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter")); } @Test public void whenFilterWithExtraHeaderRequest_thenObtainResponseWithCorrectHeaders() { final String requestUrl = "/extra-header"; ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders).isNotEmpty(); assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter")); assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ExtraHeader")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerUnitTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerUnitTest.java
package com.baeldung.web.controller.customer; import com.baeldung.model.Customer; import com.baeldung.service.CustomerService; 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.boot.test.mock.mockito.MockBean; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.HashMap; import java.util.Map; import static java.util.Arrays.asList; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; import static org.springframework.http.MediaType.APPLICATION_JSON; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class CustomerRestControllerUnitTest { private static final String APPLICATION_JSON_PATCH_JSON = "application/json-patch+json"; @Autowired private MockMvc mvc; @MockBean private CustomerService mockCustomerService; @Autowired ApplicationContext context; @Test public void whenCustomerCreated_then201ReturnedWithNewCustomerLocation() throws Exception { Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences); Customer persistedCustomer = Customer.fromCustomer(customer); persistedCustomer.setId("1"); given(mockCustomerService.createCustomer(customer)).willReturn(persistedCustomer); String createCustomerRequestBody = "{" + "\"telephone\": \"001-555-1234\",\n" + "\"favorites\": [\"Milk\", \"Eggs\"],\n" + "\"communicationPreferences\": {\"post\":true, \"email\":true}\n" + "}"; mvc.perform(post("/customers") .contentType(APPLICATION_JSON) .content(createCustomerRequestBody)) .andExpect(status().isCreated()) .andExpect(redirectedUrlPattern("http://*/customers/1")); } @Test public void givenNonExistentCustomer_whenPatched_then404Returned() throws Exception { given(mockCustomerService.findCustomer("1")).willReturn(empty()); String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]"; mvc.perform(patch("/customers/1") .contentType(APPLICATION_JSON_PATCH_JSON) .content(patchInstructions)) .andExpect(status().isNotFound()); } @Test public void givenExistingCustomer_whenPatched_thenReturnPatchedCustomer() throws Exception { Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer customer = new Customer("1", "001-555-1234", asList("Milk", "Eggs"), communicationPreferences); given(mockCustomerService.findCustomer("1")).willReturn(of(customer)); String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]"; mvc.perform(patch("/customers/1") .contentType(APPLICATION_JSON_PATCH_JSON) .content(patchInstructions)) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is("1"))) .andExpect(jsonPath("$.telephone", is("001-555-5678"))) .andExpect(jsonPath("$.favorites", is(asList("Milk", "Eggs")))) .andExpect(jsonPath("$.communicationPreferences", is(communicationPreferences))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerIntegrationTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/web/controller/customer/CustomerRestControllerIntegrationTest.java
package com.baeldung.web.controller.customer; import com.baeldung.model.Customer; import com.baeldung.service.CustomerService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CustomerRestControllerIntegrationTest { @Autowired private CustomerService customerService; @Autowired private TestRestTemplate testRestTemplate; @Before public void setup() { testRestTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory()); } @Test public void givenExistingCustomer_whenPatched_thenOnlyPatchedFieldsUpdated() { Map<String, Boolean> communicationPreferences = new HashMap<>(); communicationPreferences.put("post", true); communicationPreferences.put("email", true); Customer newCustomer = new Customer("001-555-1234", Arrays.asList("Milk", "Eggs"), communicationPreferences); Customer customer = customerService.createCustomer(newCustomer); String patchBody = "[ { \"op\": \"replace\", \"path\": \"/telephone\", \"value\": \"001-555-5678\" },\n" + "{\"op\": \"add\", \"path\": \"/favorites/0\", \"value\": \"Bread\" }]"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf("application/json-patch+json")); ResponseEntity<Customer> patchResponse = testRestTemplate.exchange("/customers/{id}", HttpMethod.PATCH, new HttpEntity<>(patchBody, headers), Customer.class, customer.getId()); Customer customerPatched = patchResponse.getBody(); assertThat(patchResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(customerPatched.getId()).isEqualTo(customer.getId()); assertThat(customerPatched.getTelephone()).isEqualTo("001-555-5678"); assertThat(customerPatched.getCommunicationPreferences().get("post")).isTrue(); assertThat(customerPatched.getCommunicationPreferences().get("email")).isTrue(); assertThat(customerPatched.getFavorites()).containsExactly("Bread", "Milk", "Eggs"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requestmapping/FooMappingExamplesControllerUnitTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requestmapping/FooMappingExamplesControllerUnitTest.java
package com.baeldung.requestmapping; 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.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(FooMappingExamplesController.class) public class FooMappingExamplesControllerUnitTest { @Autowired private MockMvc mvc; @Test public void givenAcceptsJson_whenGetDuplicate_thenJsonResponseReturned() throws Exception { mvc.perform(get("/ex/foos/duplicate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("{\"message\":\"Duplicate\"}")); } @Test public void givenAcceptsXml_whenGetDuplicate_thenXmlResponseReturned() throws Exception { mvc.perform(get("/ex/foos/duplicate") .accept(MediaType.APPLICATION_XML)) .andExpect(status().isOk()) .andExpect(content().string("<message>Duplicate</message>")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requestmapping/BazzNewMappingsExampleIntegrationTest.java
spring-web-modules/spring-rest-http/src/test/java/com/baeldung/requestmapping/BazzNewMappingsExampleIntegrationTest.java
package com.baeldung.requestmapping; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; 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; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.client.AutoConfigureWebClient; 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.config.MvcConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class BazzNewMappingsExampleIntegrationTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void whenGettingAllBazz_thenSuccess() throws Exception{ mockMvc.perform(get("/bazz")) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(4))) .andExpect(jsonPath("$[1].id", is("2"))) .andExpect(jsonPath("$[1].name", is("Bazz2"))); } @Test public void whenGettingABazz_thenSuccess() throws Exception{ mockMvc.perform(get("/bazz/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is("1"))) .andExpect(jsonPath("$.name", is("Bazz1"))); } @Test public void whenAddingABazz_thenSuccess() throws Exception{ mockMvc.perform(post("/bazz").param("name", "Bazz5")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is("5"))) .andExpect(jsonPath("$.name", is("Bazz5"))); } @Test public void whenUpdatingABazz_thenSuccess() throws Exception{ mockMvc.perform(put("/bazz/5").param("name", "Bazz6")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is("5"))) .andExpect(jsonPath("$.name", is("Bazz6"))); } @Test public void whenDeletingABazz_thenSuccess() throws Exception{ mockMvc.perform(delete("/bazz/5")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is("5"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/CustomerSpringBootRestApplication.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/CustomerSpringBootRestApplication.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CustomerSpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(CustomerSpringBootRestApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/CustomerIdGenerator.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/CustomerIdGenerator.java
package com.baeldung.service; public interface CustomerIdGenerator { int generateNextId(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/CustomerService.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/CustomerService.java
package com.baeldung.service; import com.baeldung.model.Customer; import java.util.Optional; public interface CustomerService { Customer createCustomer(Customer customer); Optional<Customer> findCustomer(String id); void updateCustomer(Customer customer); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerServiceImpl.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerServiceImpl.java
package com.baeldung.service.impl; import com.baeldung.model.Customer; import com.baeldung.service.CustomerIdGenerator; import com.baeldung.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CustomerServiceImpl implements CustomerService { private CustomerIdGenerator customerIdGenerator; private List<Customer> customers = new ArrayList<>(); @Autowired public CustomerServiceImpl(CustomerIdGenerator customerIdGenerator) { this.customerIdGenerator = customerIdGenerator; } @Override public Customer createCustomer(Customer customer) { customer.setId(Integer.toString(customerIdGenerator.generateNextId())); customers.add(customer); return customer; } @Override public Optional<Customer> findCustomer(String id) { return customers.stream() .filter(customer -> customer.getId().equals(id)) .findFirst(); } @Override public void updateCustomer(Customer customer) { customers.set(customers.indexOf(customer), customer); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerIdGeneratorImpl.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/service/impl/CustomerIdGeneratorImpl.java
package com.baeldung.service.impl; import com.baeldung.service.CustomerIdGenerator; import org.springframework.stereotype.Component; import java.util.concurrent.atomic.AtomicInteger; @Component public class CustomerIdGeneratorImpl implements CustomerIdGenerator { private static final AtomicInteger SEQUENCE = new AtomicInteger(); @Override public int generateNextId() { return SEQUENCE.incrementAndGet(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/model/Customer.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/model/Customer.java
package com.baeldung.model; import java.util.List; import java.util.Map; import java.util.Objects; public class Customer { private String id; private String telephone; private List<String> favorites; private Map<String, Boolean> communicationPreferences; public Customer() { } public Customer(String id, String telephone, List<String> favorites, Map<String, Boolean> communicationPreferences) { this(telephone, favorites, communicationPreferences); this.id = id; } public Customer(String telephone, List<String> favorites, Map<String, Boolean> communicationPreferences) { this.telephone = telephone; this.favorites = favorites; this.communicationPreferences = communicationPreferences; } public static Customer fromCustomer(Customer customer) { return new Customer(customer.getId(), customer.getTelephone(), customer.getFavorites(), customer.getCommunicationPreferences()); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Map<String, Boolean> getCommunicationPreferences() { return communicationPreferences; } public void setCommunicationPreferences(Map<String, Boolean> communicationPreferences) { this.communicationPreferences = communicationPreferences; } public List<String> getFavorites() { return favorites; } public void setFavorites(List<String> favorites) { this.favorites = favorites; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Customer)) { return false; } Customer customer = (Customer) o; return Objects.equals(id, customer.id); } @Override public int hashCode() { return Objects.hash(id); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/RequestTimeoutRestController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/RequestTimeoutRestController.java
package com.baeldung.requesttimeout; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestClient; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.requesttimeout.domain.Book; import com.baeldung.requesttimeout.domain.BookRepository; import io.github.resilience4j.timelimiter.TimeLimiter; import io.github.resilience4j.timelimiter.TimeLimiterConfig; @RestController public class RequestTimeoutRestController { private final BookRepository bookRepository; private final WebClient webClient; private final RestClient restClient; public RequestTimeoutRestController(BookRepository bookRepository, WebClient webClient, RestClient restClient) { this.bookRepository = bookRepository; this.webClient = webClient; this.restClient = restClient; } @GetMapping("/author/transactional") @Transactional(timeout = 1) public String getWithTransactionTimeout(@RequestParam String title) { return getAuthor(title); } private final TimeLimiter ourTimeLimiter = TimeLimiter.of(TimeLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(500)) .build()); @GetMapping("/author/resilience4j") public Callable<String> getWithResilience4jTimeLimiter(@RequestParam String title) { return TimeLimiter.decorateFutureSupplier(ourTimeLimiter, () -> CompletableFuture.supplyAsync(() -> getAuthor(title))); } @GetMapping("/author/mvc-request-timeout") public Callable<String> getWithMvcRequestTimeout(@RequestParam String title) { return () -> getAuthor(title); } @GetMapping("/author/webclient") public String getWithWebClient(@RequestParam String title) { return webClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build()) .retrieve() .bodyToMono(String.class) .block(); } @GetMapping("/author/restclient") public String getWithRestClient(@RequestParam String title) { return restClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build()) .retrieve() .body(String.class); } private String getAuthor(String title) { bookRepository.wasteTime(); return bookRepository.findById(title) .map(Book::getAuthor) .orElse("No book found for this title."); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/configuration/WebClientConfiguration.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/configuration/WebClientConfiguration.java
package com.baeldung.requesttimeout.configuration; import java.time.Duration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; @Configuration public class WebClientConfiguration { @Bean public WebClient webClient() { return WebClient.builder() .baseUrl("http://localhost:8080") .clientConnector(new ReactorClientHttpConnector(HttpClient.create().responseTimeout(Duration.ofMillis(250)))) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/configuration/RestClientConfiguration.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/configuration/RestClientConfiguration.java
package com.baeldung.requesttimeout.configuration; import java.time.Duration; import org.springframework.boot.web.client.ClientHttpRequestFactories; import org.springframework.boot.web.client.ClientHttpRequestFactorySettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.web.client.RestClient; @Configuration public class RestClientConfiguration { @Bean public RestClient restClient() { return RestClient.builder() .baseUrl("http://localhost:8080") .requestFactory(customRequestFactory()) .build(); } ClientHttpRequestFactory customRequestFactory() { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS .withConnectTimeout(Duration.ofMillis(200)) .withReadTimeout(Duration.ofMillis(200)); return ClientHttpRequestFactories.get(settings); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/domain/Book.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/domain/Book.java
package com.baeldung.requesttimeout.domain; import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class Book { @Id private String title; private String author; public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/domain/BookRepository.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requesttimeout/domain/BookRepository.java
package com.baeldung.requesttimeout.domain; import static java.util.concurrent.TimeUnit.SECONDS; import org.springframework.data.jpa.repository.JpaRepository; import com.google.common.base.Stopwatch; public interface BookRepository extends JpaRepository<Book, String> { default void wasteTime() { Stopwatch watch = Stopwatch.createStarted(); // delay for 2 seconds while (watch.elapsed(SECONDS) < 2) { int i = Integer.MIN_VALUE; while (i < Integer.MAX_VALUE) { i++; } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/config/MvcConfig.java
package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.text.SimpleDateFormat; import java.util.List; /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml */ @Configuration @EnableWebMvc @ComponentScan({"com.baeldung.requestmapping" }) public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); } // @Override public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) { final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true) .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { configurer.setDefaultTimeout(750); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java
package com.baeldung.responseheaders; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @ServletComponentScan @SpringBootApplication public class ResponseHeadersApplication { public static void main(String[] args) { SpringApplication.run(ResponseHeadersApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java
package com.baeldung.responseheaders.filter; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 jakarta.servlet.http.HttpServletResponse; @WebFilter("/filter-response-header/*") public class AddResponseHeaderFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(AddResponseHeaderFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { // add special initialization requirements here LOGGER.trace("Initializing filter..."); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Baeldung-Example-Filter-Header", "Value-Filter"); chain.doFilter(request, response); } @Override public void destroy() { // clean up any resource being held by the filter here LOGGER.trace("Destroying filter..."); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java
package com.baeldung.responseheaders.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletResponse; @RestController @RequestMapping("/filter-response-header") public class FilterResponseHeaderController { @GetMapping("/no-extra-header") public String filterHeaderResponseWithNoExtraHeader() { return "Response body with Filter header and no extra header"; } @GetMapping("/extra-header") public String filterHeaderResponseWithExtraHeader(HttpServletResponse response) { response.addHeader("Baeldung-Example-Header", "Value-ExtraHeader"); return "Response body with Filter header and one extra header"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java
package com.baeldung.responseheaders.controllers; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/single-response-header") public class ResponseHeaderController { @GetMapping("/http-servlet-response") public String usingHttpServletResponse(HttpServletResponse response) { response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse"); return "Response with header using HttpServletResponse"; } @GetMapping("/response-entity-constructor") public ResponseEntity<String> usingResponseEntityConstructor() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor"); String responseBody = "Response with header using ResponseEntity (constructor)"; HttpStatus responseStatus = HttpStatus.OK; return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus); } @GetMapping("/response-entity-contructor-multiple-headers") public ResponseEntity<String> usingResponseEntityConstructorAndMultipleHeaders() { List<MediaType> acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON)); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders"); responseHeaders.setAccept(acceptableMediaTypes); String responseBody = "Response with header using ResponseEntity (constructor)"; HttpStatus responseStatus = HttpStatus.OK; return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus); } @GetMapping("/response-entity-builder") public ResponseEntity<String> usingResponseEntityBuilder() { String responseHeaderKey = "Baeldung-Example-Header"; String responseHeaderValue = "Value-ResponseEntityBuilder"; String responseBody = "Response with header using ResponseEntity (builder)"; return ResponseEntity.ok() .header(responseHeaderKey, responseHeaderValue) .body(responseBody); } @GetMapping("/response-entity-builder-with-http-headers") public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders"); String responseBody = "Response with header using ResponseEntity (builder)"; return ResponseEntity.ok() .headers(responseHeaders) .body(responseBody); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java
package com.baeldung.endpoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/controller/HelloController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/controller/HelloController.java
package com.baeldung.endpoint.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public ResponseEntity<String> hello() { return ResponseEntity.ok("hello baeldung"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/swagger/SpringDocConfig.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/swagger/SpringDocConfig.java
package com.baeldung.endpoint.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; @Configuration public class SpringDocConfig { @Bean public OpenAPI openAPI() { return new OpenAPI().info(new Info().title("SpringDoc example") .description("SpringDoc application") .version("v0.0.1")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java
package com.baeldung.endpoint.listener; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @Configuration public class EndpointsListener implements ApplicationListener<ContextRefreshedEvent> { private final Logger LOGGER = LoggerFactory.getLogger("EndpointsListener.class"); @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext .getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods(); map.forEach((key, value) -> LOGGER.info("{} {}", key, value)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java
package com.baeldung.endpoint.listener; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @Configuration public class AnnotationDrivenEndpointsListener { private final Logger LOGGER = LoggerFactory.getLogger("AnnotationDrivenEndpointsListener.class"); @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext .getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods(); map.forEach((key, value) -> LOGGER.info("{} {}", key, value)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/controller/customer/CustomerRestController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/controller/customer/CustomerRestController.java
package com.baeldung.web.controller.customer; import com.baeldung.model.Customer; import com.baeldung.service.CustomerService; import com.baeldung.web.exception.CustomerNotFoundException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @RestController @RequestMapping(value = "/customers") public class CustomerRestController { private CustomerService customerService; private ObjectMapper objectMapper = new ObjectMapper(); @Autowired public CustomerRestController(CustomerService customerService) { this.customerService = customerService; } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer) { Customer customerCreated = customerService.createCustomer(customer); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(customerCreated.getId()) .toUri(); return ResponseEntity.created(location) .build(); } @PatchMapping(path = "/{id}", consumes = "application/json-patch+json") public ResponseEntity<Customer> updateCustomer(@PathVariable String id, @RequestBody JsonPatch patch) { try { Customer customer = customerService.findCustomer(id) .orElseThrow(CustomerNotFoundException::new); Customer customerPatched = applyPatchToCustomer(patch, customer); customerService.updateCustomer(customerPatched); return ResponseEntity.ok(customerPatched); } catch (CustomerNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .build(); } catch (JsonPatchException | JsonProcessingException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .build(); } } private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer) throws JsonPatchException, JsonProcessingException { JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class)); return objectMapper.treeToValue(patched, Customer.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/dto/Foo.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/dto/Foo.java
package com.baeldung.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("Foo") public class Foo { private long id; private String name; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } public Foo(final long id, final String name) { super(); this.id = id; this.name = name; } // API public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/dto/Bazz.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/dto/Bazz.java
package com.baeldung.web.dto; public class Bazz { public String id; public String name; public Bazz(String id){ this.id = id; } public Bazz(String id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Bazz [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-rest-http/src/main/java/com/baeldung/web/exception/CustomerNotFoundException.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/web/exception/CustomerNotFoundException.java
package com.baeldung.web.exception; public class CustomerNotFoundException 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-rest-http/src/main/java/com/baeldung/requestmapping/BarMappingExamplesController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requestmapping/BarMappingExamplesController.java
package com.baeldung.requestmapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/ex") public class BarMappingExamplesController { public BarMappingExamplesController() { super(); } // API // with @RequestParam @RequestMapping(value = "/bars") @ResponseBody public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) { return "Get a specific Bar with id=" + id; } @RequestMapping(value = "/bars", params = "id") @ResponseBody public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) { return "Get a specific Bar with id=" + id; } @RequestMapping(value = "/bars", params = { "id", "second" }) @ResponseBody public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) { return "Get a specific Bar with id=" + id; } // with @PathVariable @RequestMapping(value = "/bars/{numericId:[\\d]+}") @ResponseBody public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) { return "Get a specific Bar with id=" + numericId; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requestmapping/BazzNewMappingsExampleController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requestmapping/BazzNewMappingsExampleController.java
package com.baeldung.requestmapping; import java.util.Arrays; import java.util.List; import org.springframework.http.HttpStatus; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.baeldung.web.dto.Bazz; import com.fasterxml.jackson.core.JsonProcessingException; @RestController @RequestMapping("/bazz") public class BazzNewMappingsExampleController { @GetMapping public ResponseEntity<?> getBazzs() throws JsonProcessingException{ List<Bazz> data = Arrays.asList( new Bazz("1", "Bazz1"), new Bazz("2", "Bazz2"), new Bazz("3", "Bazz3"), new Bazz("4", "Bazz4")); return new ResponseEntity<>(data, HttpStatus.OK); } @GetMapping("/{id}") public ResponseEntity<?> getBazz(@PathVariable String id){ return new ResponseEntity<>(new Bazz(id, "Bazz"+id), HttpStatus.OK); } @PostMapping public ResponseEntity<?> newBazz(@RequestParam("name") String name){ return new ResponseEntity<>(new Bazz("5", name), HttpStatus.OK); } @PutMapping("/{id}") public ResponseEntity<?> updateBazz(@PathVariable String id, @RequestParam("name") String name){ return new ResponseEntity<>(new Bazz(id, name), HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteBazz(@PathVariable String id){ return new ResponseEntity<>(new Bazz(id), 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-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java
spring-web-modules/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java
package com.baeldung.requestmapping; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/ex") public class FooMappingExamplesController { public FooMappingExamplesController() { super(); } // API // mapping examples @RequestMapping(value = "/foos") @ResponseBody public String getFoosBySimplePath() { return "Simple Get some Foos"; } // with @PathVariable @RequestMapping(value = "/foos/{id}") @ResponseBody public String getFoosBySimplePathWithPathVariable(@PathVariable final long id) { return "Get a specific Foo with id=" + id; } @RequestMapping(value = "/foos/{fooid}/bar/{barid}") @ResponseBody public String getFoosBySimplePathWithPathVariables(@PathVariable final long fooid, @PathVariable final long barid) { return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid; } // other HTTP verbs @RequestMapping(value = "/foos", method = RequestMethod.POST) @ResponseBody public String postFoos() { return "Post some Foos"; } // with headers @RequestMapping(value = "/foos", headers = "key=val") @ResponseBody public String getFoosWithHeader() { return "Get some Foos with Header"; } @RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" }) @ResponseBody public String getFoosWithHeaders() { return "Get some Foos with Header"; } // @RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json") // @ResponseBody // public String getFoosAsJsonFromBrowser() { // return "Get some Foos with Header Old"; // } @RequestMapping(value = "/foos", produces = { "application/json", "application/xml" }) @ResponseBody public String getFoosAsJsonFromREST() { return "Get some Foos with Header New"; } // advanced - multiple mappings @RequestMapping(value = { "/advanced/bars", "/advanced/foos" }) @ResponseBody public String getFoosOrBarsByPath() { return "Advanced - Get some Foos or Bars"; } @RequestMapping(value = "*") @ResponseBody public String getFallback() { return "Fallback for GET Requests"; } @RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String allFallback() { return "Fallback for All Requests"; } @RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST }) @ResponseBody public String putAndPostFoos() { return "Advanced - PUT and POST within single method"; } // --- Ambiguous Mapping @GetMapping(value = "foos/duplicate" ) public ResponseEntity<String> duplicate() { return new ResponseEntity<>("Duplicate", HttpStatus.OK); } // uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping // @GetMapping(value = "foos/duplicate" ) // public String duplicateEx() { // return "Duplicate"; // } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE) public ResponseEntity<String> duplicateXml() { return new ResponseEntity<>("<message>Duplicate</message>", HttpStatus.OK); } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> duplicateJson() { return new ResponseEntity<>("{\"message\":\"Duplicate\"}", 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-rest-http-3/src/test/java/com/baeldung/streaming/ReactiveStreamingControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/streaming/ReactiveStreamingControllerUnitTest.java
package com.baeldung.streaming; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.MediaType; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import java.nio.file.Files; import java.nio.file.Path; import static org.assertj.core.api.Assertions.assertThat; // To test the reactive endpoints, uncomment spring.main.web-application-type=reactive in the application properties, // which switches the application from default MVC mode to reactive mode. @SpringBootTest @AutoConfigureWebTestClient class ReactiveStreamingControllerUnitTest { /* @Autowired private WebTestClient webTestClient; private static final Path UPLOAD_DIR = Path.of("reactive-uploads"); @BeforeEach void setUp() throws Exception { Files.createDirectories(UPLOAD_DIR); Files.writeString(UPLOAD_DIR.resolve("file1.txt"), "Hello from file1"); Files.writeString(UPLOAD_DIR.resolve("file2.txt"), "Hello from file2"); } @Test void givenFilePart_whenUpload_thenSuccessMessage() { byte[] content = "Reactive upload content".getBytes(); ByteArrayResource resource = new ByteArrayResource(content) { @Override public String getFilename() { return "upload.txt"; } }; MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("filePart", resource); webTestClient.post() .uri("/reactive/files/upload") .contentType(MediaType.MULTIPART_FORM_DATA) .bodyValue(body) .exchange() .expectStatus().isOk() .expectBody(String.class) .value(bodyStr -> assertThat(bodyStr).contains("Upload successful: upload.txt")); assertThat(Files.exists(UPLOAD_DIR.resolve("upload.txt"))).isTrue(); } @Test void givenExistingFiles_whenDownload_thenMultipartResponseContainsFiles() { webTestClient.get() .uri("/reactive/files/download") .exchange() .expectStatus().isOk() .expectHeader().contentTypeCompatibleWith("multipart/mixed") .expectBody(String.class) .value(body -> { assertThat(body).contains("Hello from file1"); assertThat(body).contains("Hello from file2"); assertThat(body).contains("Content-Disposition: attachment; filename=\"file1.txt\""); assertThat(body).contains("Content-Disposition: attachment; filename=\"file2.txt\""); }); } */ }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/streaming/MvcStreamingControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/streaming/MvcStreamingControllerUnitTest.java
package com.baeldung.streaming; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @SpringBootTest @AutoConfigureMockMvc class MvcStreamingControllerUnitTest { @Autowired private MockMvc mockMvc; @AfterEach void cleanupTestFiles() throws IOException { Path uploadDir = Path.of("mvc-uploads"); if (Files.exists(uploadDir)) { // Delete the entire directory and its contents Files.walk(uploadDir) .sorted(Comparator.reverseOrder()) // delete files first, then directory .forEach(path -> { try { Files.deleteIfExists(path); } catch (IOException e) { // Log the error but don't fail the test System.err.println("Failed to delete file: " + path + ", Error: " + e.getMessage()); } }); } } @Test void givenMultipartFile_whenUploadEndpointCalled_thenFileIsSavedAndSuccessResponseReturned() throws Exception { // Given String testContent = "Hello, World!"; MockMultipartFile file = new MockMultipartFile( "filePart", "test-file.txt", "text/plain", testContent.getBytes() ); // When mockMvc.perform(multipart("/mvc/files/upload").file(file)) // Then .andExpect(status().isOk()) .andExpect(content().string("Upload successful: test-file.txt")); // Then - Verify file was actually created Path uploadedFilePath = Path.of("mvc-uploads/test-file.txt"); assertTrue(Files.exists(uploadedFilePath), "Uploaded file should exist on the filesystem"); assertTrue(Files.readString(uploadedFilePath).equals(testContent), "Uploaded file content should match the original"); } @Test void givenSourceFilesExistInUploadDirectory_whenDownloadEndpointCalled_thenMultipartResponseWithCorrectContentTypeReturned() throws Exception { // Given - Create the source files that the controller expects to find Files.createDirectories(Path.of("mvc-uploads")); Files.writeString(Path.of("mvc-uploads/file1.txt"), "content of file1"); Files.writeString(Path.of("mvc-uploads/file2.txt"), "content of file2"); // When & Then mockMvc.perform(get("/mvc/files/download")) .andExpect(status().isOk()) .andExpect(header().string("Content-Type", "multipart/mixed; boundary=filesBoundary")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/xml/UserEchoControllerIntegrationTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/xml/UserEchoControllerIntegrationTest.java
package com.baeldung.xml; import static org.assertj.core.api.Assertions.assertThat; import com.baeldung.xml.controller.User; import com.baeldung.xml.controller.UserEchoController; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @WebMvcTest(UserEchoController.class) class UserEchoControllerIntegrationTest { private static final String URI = "/users"; private static final User USER = new User(1L, "John", "Doe"); private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); private static final XmlMapper XML_MAPPER = new XmlMapper(); @Autowired private UserEchoController controller; @Autowired private MockMvc mockMvc; @Test void whenContextStartBeansArePresent() { assertThat(controller).isNotNull(); assertThat(mockMvc).isNotNull(); } @Test void givenEndpointWhenPostJsonUserReceiveCorrectResponse() throws Exception { final String payload = JSON_MAPPER.writeValueAsString(USER); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(URI) .contentType(MediaType.APPLICATION_JSON) .content(payload); final MvcResult mvcResult = this.mockMvc.perform(builder) .andExpect(MockMvcResultMatchers.status() .isCreated()).andReturn(); final User actual = JSON_MAPPER.readValue(mvcResult.getResponse().getContentAsString(), User.class); assertThat(actual).isEqualTo(USER); } @Test void givenEndpointWhenPostXmlUserReceiveCorrectResponse() throws Exception { final String payload = XML_MAPPER.writeValueAsString(USER); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(URI) .contentType(MediaType.APPLICATION_XML) .accept(MediaType.APPLICATION_XML) .content(payload); final MvcResult mvcResult = this.mockMvc.perform(builder) .andExpect(MockMvcResultMatchers.status() .isCreated()).andReturn(); final User actual = XML_MAPPER.readValue(mvcResult.getResponse().getContentAsString(), User.class); assertThat(actual).isEqualTo(USER); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/bulkandbatchapi/BatchControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/bulkandbatchapi/BatchControllerUnitTest.java
package com.baeldung.bulkandbatchapi; import com.baeldung.bulkandbatchapi.controller.BatchController; import com.baeldung.bulkandbatchapi.request.Address; import com.baeldung.bulkandbatchapi.request.Customer; import com.baeldung.bulkandbatchapi.service.AddressService; import com.baeldung.bulkandbatchapi.service.CustomerService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @WebMvcTest(BatchController.class) class BatchControllerUnitTest { @MockBean private CustomerService customerService; @MockBean private AddressService addressService; @Autowired private MockMvc mockMvc; @Test void givenCustomersAndAddressAreValid_WhenCalledBatchApi_ThenShouldCreateAndReturnCustomers() throws Exception { Customer customer = this.getCustomer(); customer.setAddress("street1 city1"); Address address = this.getAddress(); when(addressService.createAddress(address)).thenReturn(address); when(customerService.updateCustomer(customer)).thenReturn(Optional.of(customer)); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); httpHeaders.add("Accept", "application/json"); mockMvc.perform(post("/api/batch").headers(httpHeaders).content("[" + " {" + " \"method\": \"POST\"," + " \"relativeUrl\": \"/address\"," + " \"data\": {" + " \"id\": 1," + " \"street\": \"test1\"," + " \"city\": \"test\"" + " }" + " }," + " {" + " \"method\": \"PATCH\"," + " \"relativeUrl\": \"/customer\"," + " \"data\": {" + " \"id\": \"1\"," + " \"name\": \"test1\"," + " \"email\": \"test1@email.com\"," + " \"address\": \"test1 test\"" + " }" + " }" + "]")).andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().string("Batch update is processed")); } @Test void givenBatchRequestIsEmpty_WhenCalledBatchApi_ThenShouldReturnBadRequestError() throws Exception { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); httpHeaders.add("Accept", "application/json"); mockMvc.perform(post("/api/batch").headers(httpHeaders).content("[]")) .andExpect(status().is(HttpStatus.BAD_REQUEST.value())) .andExpect(content().string("")); } private Customer getCustomer() { Customer customer = new Customer(); customer.setId(1); customer.setName("test1"); customer.setEmail("test1@email.com"); return customer; } private Address getAddress() { Address address = new Address(); address.setId(0); address.setStreet("street1"); address.setCity("city1"); return address; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/bulkandbatchapi/BulkControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/bulkandbatchapi/BulkControllerUnitTest.java
package com.baeldung.bulkandbatchapi; import com.baeldung.bulkandbatchapi.controller.BulkController; import com.baeldung.bulkandbatchapi.request.Customer; import com.baeldung.bulkandbatchapi.service.CustomerService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @WebMvcTest(BulkController.class) class BulkControllerUnitTest { @MockBean private CustomerService customerService; @Autowired private MockMvc mockMvc; @Test void givenCustomersIsValid_WhenCalledBulkCreateCustomers_ThenShouldCreateAndReturnCustomers() throws Exception { Customer customer1 = this.getCustomer("test1", "test1@email.com", "address1"); Customer customer2 = this.getCustomer("test2", "test2@email.com", "address2"); List<Customer> customers = Arrays.asList(customer1, customer2); when(customerService.createCustomers(customers)).thenReturn(customers); when(customerService.createCustomers(customers)).thenReturn(customers); mockMvc.perform(post("/api/customers").headers(getHttpHeaders("bulk")).content("[" + " {" + " \"name\": \"test1\"," + " \"email\": \"test1@email.com\"," + " \"address\": \"address1\"" + " }," + " {" + " \"name\": \"test2\"," + " \"email\": \"test2@email.com\"," + " \"address\": \"address2\"" + " }" + "]")) .andExpect(status().is(HttpStatus.CREATED.value())) .andExpect(content().string("[]")); } @Test void givenCustomersNotExists_WhenCalledBulkCreateCustomers_WithInvalidData_ThenShouldReturnBadRequestError() throws Exception { mockMvc.perform(post("/api/customers").headers(getHttpHeaders("bulk")).content("[]")) .andExpect(status().is(HttpStatus.BAD_REQUEST.value())) .andExpect(content().string("")); } @Test void givenActionTypeHeaderIsMissing_WhenCalledBulkCreateCustomers_ThenShouldReturnBadRequestError() throws Exception { mockMvc.perform(post("/api/customers")) .andExpect(status().is(HttpStatus.BAD_REQUEST.value())) .andExpect(content().string("")); } @Test void givenCustomersAreValid_WhenCalledBulkProcessCustomers_ThenShouldProcessCustomers_ReturnValidData() throws Exception { Customer customer1 = this.getCustomer("test4", "test4@email.com", "address1"); Customer customer2 = this.getCustomer("test1-update", "test2@email.com", "address1-update"); customer2.setId(1); when(customerService.createCustomer(customer1)).thenReturn(Optional.of(customer1)); when(customerService.updateCustomer(customer1)).thenReturn(Optional.of(customer2)); mockMvc.perform(post("/api/customers/bulk").headers(getHttpHeaders("singular")).content("[" + " {" + " \"bulkActionType\": \"CREATE\"," + " \"customers\": [" + " {" + " \"name\": \"test4\"," + " \"email\": \"test4@email.com\"," + " \"address\": \"address1\"" + " }" + " ]" + " }," + " {" + " \"bulkActionType\": \"UPDATE\"," + " \"customers\": [" + " {" + " \"id\": 1," + " \"name\": \"test1-update\"," + " \"email\": \"test1@email.com\"," + " \"address\": \"address1-update\"" + " }" + " ]" + "}" + "]")) .andExpect(status().is(HttpStatus.MULTI_STATUS.value())); } @Test void givenCustomerAreValid_WhenCalledSingleCustomer_ThenShouldProcessCustomers_ReturnValidData() throws Exception { Customer customer1 = this.getCustomer("test4", "test4@email.com", "address1"); when(customerService.createCustomer(customer1)).thenReturn(Optional.of(customer1)); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); httpHeaders.add("Accept", "application/json"); mockMvc.perform(post("/api/customers/bulk").headers(httpHeaders).content("[" + " {" + " \"bulkActionType\": \"CREATE\"," + " \"customers\": [" + " {" + " \"name\": \"test4\"," + " \"email\": \"test4@email.com\"," + " \"address\": \"address4\"" + " }" + " ]" + " }" + "]")) .andExpect(status().is(HttpStatus.MULTI_STATUS.value())); } private Customer getCustomer(String name, String email, String address) { Customer customer = new Customer(); customer.setName(name); customer.setEmail(email); customer.setAddress(address); return customer; } private HttpHeaders getHttpHeaders(String actionType) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); httpHeaders.add("Accept", "application/json"); httpHeaders.add("X-ActionType", actionType); return httpHeaders; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/httpstatuscode/StatusControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/httpstatuscode/StatusControllerUnitTest.java
package com.baeldung.httpstatuscode; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest(StatusController.class) class StatusControllerUnitTest { @Autowired private MockMvc mockMvc; @Test void whenGetRequestSentToResource_thenReturnStatusOk() throws Exception { mockMvc.perform(get("/resource")) .andExpect(status().is2xxSuccessful()); } @Test void whenGetRequestSentToException_thenReturnStatusNotFound() throws Exception { mockMvc.perform(get("/exception")) .andExpect(status().isNotFound()); } @Test void whenGetRequestSentToCustomException_thenReturnStatusGone() throws Exception { mockMvc.perform(get("/custom-exception")) .andExpect(status().is4xxClientError()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/zip/ZipArchiveControllerUnitTest.java
spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/zip/ZipArchiveControllerUnitTest.java
package com.baeldung.zip; import net.lingala.zip4j.model.LocalFileHeader; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @WebMvcTest(ZipArchiveController.class) public class ZipArchiveControllerUnitTest { @Autowired MockMvc mockMvc; @Test void givenZipArchiveController_whenGetZipArchiveBytes_thenExpectedArchiveShouldContainExpectedFiles() throws Exception { MvcResult result = mockMvc.perform(get("/zip-archive")) .andReturn(); MockHttpServletResponse response = result.getResponse(); byte[] content = response.getContentAsByteArray(); List<String> fileNames = fetchFileNamesFromArchive(content); assertThat(fileNames) .containsExactly("first-file.txt", "second-file.txt"); } @Test void givenZipArchiveController_whenGetZipArchiveStream_thenExpectedArchiveShouldContainExpectedFiles() throws Exception { MvcResult result = mockMvc.perform(get("/zip-archive-stream")) .andReturn(); MockHttpServletResponse response = result.getResponse(); Thread.sleep(1000); byte[] content = response.getContentAsByteArray(); List<String> fileNames = fetchFileNamesFromArchive(content); assertThat(fileNames) .containsExactly("first-file.txt", "second-file.txt"); } @Test void givenZipArchiveController_whenGetZipArchiveSecuredStream_thenExpectedArchiveShouldContainExpectedFilesSecuredByPassword() throws Exception { MvcResult result = mockMvc.perform(get("/zip-archive-stream-secured")) .andReturn(); MockHttpServletResponse response = result.getResponse(); Thread.sleep(1000); byte[] content = response.getContentAsByteArray(); List<String> fileNames = fetchFileNamesFromArchive(content); assertThat(fileNames) .containsExactly("first-file.txt", "second-file.txt"); } List<String> fetchFileNamesFromArchive(byte[] content) throws IOException { InputStream byteStream = new ByteArrayInputStream(content); net.lingala.zip4j.io.inputstream.ZipInputStream zipStream = new net.lingala.zip4j.io.inputstream.ZipInputStream(byteStream, "password".toCharArray()); List<String> fileNames = new ArrayList<>(); LocalFileHeader entry = zipStream.getNextEntry(); while (entry != null) { fileNames.add(entry.getFileName()); entry = zipStream.getNextEntry(); } zipStream.close(); return fileNames; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/SpringBootRest3Application.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/SpringBootRest3Application.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRest3Application { public static void main(String[] args) { SpringApplication.run(SpringBootRest3Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/streaming/MvcStreamingController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/streaming/MvcStreamingController.java
package com.baeldung.streaming; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @RestController @RequestMapping("/mvc/files") public class MvcStreamingController { private static final Path UPLOAD_DIR = Path.of("mvc-uploads"); @PostMapping("/upload") public ResponseEntity<String> uploadFileStreaming(@RequestPart("filePart") MultipartFile filePart) throws IOException { Path targetPath = UPLOAD_DIR.resolve(filePart.getOriginalFilename()); Files.createDirectories(targetPath.getParent()); try (InputStream inputStream = filePart.getInputStream(); OutputStream outputStream = Files.newOutputStream(targetPath)) { inputStream.transferTo(outputStream); } return ResponseEntity.ok("Upload successful: " + filePart.getOriginalFilename()); } @GetMapping("/download") public StreamingResponseBody downloadFiles(HttpServletResponse response) throws IOException { String boundary = "filesBoundary"; response.setContentType("multipart/mixed; boundary=" + boundary); List<Path> files = List.of(UPLOAD_DIR.resolve("file1.txt"), UPLOAD_DIR.resolve("file2.txt")); return outputStream -> { try (BufferedOutputStream bos = new BufferedOutputStream(outputStream); OutputStreamWriter writer = new OutputStreamWriter(bos)) { for (Path file : files) { writer.write("--" + boundary + "\r\n"); writer.write("Content-Type: application/octet-stream\r\n"); writer.write("Content-Disposition: attachment; filename=\"" + file.getFileName() + "\"\r\n\r\n"); writer.flush(); Files.copy(file, bos); bos.write("\r\n".getBytes()); bos.flush(); } writer.write("--" + boundary + "--\r\n"); writer.flush(); } }; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/streaming/ReactiveStreamingController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/streaming/ReactiveStreamingController.java
package com.baeldung.streaming; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.codec.multipart.FilePart; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @Controller @RequestMapping("/reactive/files") public class ReactiveStreamingController { private static final Path UPLOAD_DIR = Path.of("reactive-uploads"); @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody public Mono<String> uploadFileStreaming(@RequestPart("filePart") FilePart filePart) { return Mono.fromCallable(() -> { Path targetPath = UPLOAD_DIR.resolve(filePart.filename()); Files.createDirectories(targetPath.getParent()); return targetPath; }).flatMap(targetPath -> filePart.transferTo(targetPath) .thenReturn("Upload successful: " + filePart.filename()) ); } @GetMapping(value = "/download", produces = "multipart/mixed") public ResponseEntity<Flux<DataBuffer>> downloadFiles() { String boundary = "filesBoundary"; List<Path> files = List.of( UPLOAD_DIR.resolve("file1.txt"), UPLOAD_DIR.resolve("file2.txt") ); // Use concatMap to ensure files are streamed one after another, sequentially. Flux<DataBuffer> fileFlux = Flux.fromIterable(files) .concatMap(file -> { String partHeader = "--" + boundary + "\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Disposition: attachment; filename=\"" + file.getFileName() + "\"\r\n\r\n"; Flux<DataBuffer> fileContentFlux = DataBufferUtils.read(file, new DefaultDataBufferFactory(), 4096); DataBuffer footerBuffer = new DefaultDataBufferFactory().wrap("\r\n".getBytes()); // Build the flux for this specific part: header + content + footer return Flux.concat( Flux.just(new DefaultDataBufferFactory().wrap(partHeader.getBytes())), fileContentFlux, Flux.just(footerBuffer) ); }) // After all parts, concat the final boundary .concatWith(Flux.just( new DefaultDataBufferFactory().wrap(("--" + boundary + "--\r\n").getBytes()) )); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, "multipart/mixed; boundary=" + boundary) .body(fileFlux); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/AppConfig.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/AppConfig.java
package com.baeldung.xml; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AppConfig { public static void main(String[] args) { SpringApplication.run(AppConfig.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/UserEchoController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/UserEchoController.java
package com.baeldung.xml.controller; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserEchoController { @ResponseStatus(HttpStatus.CREATED) @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public User echoJsonUser(@RequestBody User user) { return user; } @ResponseStatus(HttpStatus.CREATED) @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) public User echoXmlUser(@RequestBody User user) { 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-rest-http-3/src/main/java/com/baeldung/xml/controller/User.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/User.java
package com.baeldung.xml.controller; import java.util.Objects; public class User { private Long id; private String firstName; private String secondName; public User() { } public User(final Long id, final String firstName, final String secondName) { this.id = id; this.firstName = firstName; this.secondName = secondName; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getSecondName() { return secondName; } public void setSecondName(final String secondName) { this.secondName = secondName; } public void setId(final Long id) { this.id = id; } public Long getId() { return id; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final User user = (User) o; if (!Objects.equals(id, user.id)) { return false; } if (!Objects.equals(firstName, user.firstName)) { return false; } return Objects.equals(secondName, user.secondName); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (secondName != null ? secondName.hashCode() : 0); return result; } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", secondName='" + secondName + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/controller/BulkController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/controller/BulkController.java
package com.baeldung.bulkandbatchapi.controller; import com.baeldung.bulkandbatchapi.request.BulkActionType; import com.baeldung.bulkandbatchapi.request.Customer; import com.baeldung.bulkandbatchapi.request.CustomerBulkRequest; import com.baeldung.bulkandbatchapi.response.BulkStatus; import com.baeldung.bulkandbatchapi.response.CustomerBulkResponse; import com.baeldung.bulkandbatchapi.service.CustomerService; import jakarta.validation.Valid; import jakarta.validation.constraints.Size; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.*; import java.util.function.Function; import static java.util.stream.Collectors.toList; @RestController @RequestMapping("/api") @Validated public class BulkController { private final CustomerService customerService; private final EnumMap<BulkActionType, Function<Customer, Optional<Customer>>> bulkActionFuncMap = new EnumMap<>(BulkActionType.class); public BulkController(CustomerService customerService) { this.customerService = customerService; bulkActionFuncMap.put(BulkActionType.CREATE, customerService::createCustomer); bulkActionFuncMap.put(BulkActionType.UPDATE, customerService::updateCustomer); bulkActionFuncMap.put(BulkActionType.DELETE, customerService::deleteCustomer); } @PostMapping(path = "/customers") public ResponseEntity<List<Customer>> createCustomers(@RequestHeader(value = "X-ActionType") String actionType, @RequestBody @Valid @Size(min = 1, max = 20) List<Customer> customers) { List<Customer> customerList = actionType.equals("bulk") ? customerService.createCustomers(customers) : Collections.singletonList(customerService.createCustomer(customers.get(0)).orElse(null)); return new ResponseEntity<>(customerList, HttpStatus.CREATED); } @PostMapping(path = "/customers/bulk") public ResponseEntity<List<CustomerBulkResponse>> bulkProcessCustomers(@RequestBody @Valid @Size(min = 1, max = 20) List<CustomerBulkRequest> customerBulkRequests) { List<CustomerBulkResponse> customerBulkResponseList = new ArrayList<>(); customerBulkRequests.forEach(customerBulkRequest -> { List<Customer> customers = customerBulkRequest.getCustomers().stream() .map(bulkActionFuncMap.get(customerBulkRequest.getBulkActionType())) .filter(Optional::isPresent) .map(Optional::get) .collect(toList()); BulkStatus bulkStatus = getBulkStatus(customerBulkRequest.getCustomers(), customers); customerBulkResponseList.add(new CustomerBulkResponse(customers, customerBulkRequest.getBulkActionType(), bulkStatus)); }); return new ResponseEntity<>(customerBulkResponseList, HttpStatus.MULTI_STATUS); } private BulkStatus getBulkStatus(List<Customer> customersInRequest, List<Customer> customersProcessed) { if (!customersProcessed.isEmpty()) { return customersProcessed.size() == customersInRequest.size() ? BulkStatus.PROCESSED : BulkStatus.PARTIALLY_PROCESSED; } return BulkStatus.NOT_PROCESSED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/controller/BatchController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/controller/BatchController.java
package com.baeldung.bulkandbatchapi.controller; import com.baeldung.bulkandbatchapi.request.Address; import com.baeldung.bulkandbatchapi.service.AddressService; import com.baeldung.bulkandbatchapi.request.Customer; import com.baeldung.bulkandbatchapi.service.CustomerService; import com.baeldung.bulkandbatchapi.request.BatchRequest; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.validation.Valid; import jakarta.validation.constraints.Size; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api") @Validated public class BatchController { private final CustomerService customerService; private final AddressService addressService; private final ObjectMapper objectMapper; public BatchController(CustomerService customerService, AddressService addressService, ObjectMapper objectMapper) { this.customerService = customerService; this.addressService = addressService; this.objectMapper = objectMapper; } @PostMapping(path = "/batch") public ResponseEntity<String> batchUpdateCustomerWithAddress(@RequestBody @Valid @Size(min = 1, max = 20) List<BatchRequest> batchRequests) { batchRequests.forEach(batchRequest -> { if (batchRequest.getMethod().equals(HttpMethod.POST) && batchRequest.getRelativeUrl().equals("/address")) { addressService.createAddress(objectMapper.convertValue(batchRequest.getData(), Address.class)); } else if (batchRequest.getMethod().equals(HttpMethod.PATCH) && batchRequest.getRelativeUrl().equals("/customer")) { customerService.updateCustomer(objectMapper.convertValue(batchRequest.getData(), Customer.class)); } }); return new ResponseEntity<>("Batch update is processed", 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-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/service/AddressService.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/service/AddressService.java
package com.baeldung.bulkandbatchapi.service; import com.baeldung.bulkandbatchapi.request.Address; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.*; @Service public class AddressService { private static final Logger LOGGER = LoggerFactory.getLogger(AddressService.class); private final Map<String, Address> addressRepoMap = new HashMap<>(); public Address createAddress(Address address) { LOGGER.info("Creating Address : {}", address); Address createdAddress = null; String addressUniqueKey = address.getStreet().concat(address.getCity()); if (!addressRepoMap.containsKey(addressUniqueKey)) { createdAddress = new Address(addressRepoMap.size() + 1, address.getStreet(), address.getCity()); addressRepoMap.put(addressUniqueKey, createdAddress); LOGGER.info("Created Address : {}", createdAddress); } return createdAddress; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/service/CustomerService.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/service/CustomerService.java
package com.baeldung.bulkandbatchapi.service; import com.baeldung.bulkandbatchapi.request.Customer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.*; import static java.util.stream.Collectors.toList; @Service public class CustomerService { private static final Logger LOGGER = LoggerFactory.getLogger(CustomerService.class); private final Map<String, Customer> customerRepoMap = new HashMap<>(); public List<Customer> createCustomers(List<Customer> customers) { return customers.stream() .map(this::createCustomer) .filter(Optional::isPresent) .map(Optional::get) .collect(toList()); } public Optional<Customer> createCustomer(Customer customer) { LOGGER.info("Creating Customer : {}", customer); if (!customerRepoMap.containsKey(customer.getEmail()) && customer.getId() == 0) { Customer customerToCreate = new Customer(customerRepoMap.size() + 1, customer.getName(), customer.getEmail()); customerToCreate.setAddress(customer.getAddress()); customerRepoMap.put(customerToCreate.getEmail(), customerToCreate); LOGGER.info("Created Customer : {}", customerToCreate); return Optional.of(customerToCreate); } return Optional.empty(); } public Optional<Customer> updateCustomer(Customer customer) { LOGGER.info("Updating Customer : {}", customer); Customer customerToUpdate = customerRepoMap.get(customer.getEmail()); if (customerToUpdate != null && customerToUpdate.getId() == customer.getId()) { customerToUpdate.setName(customer.getName()); customerToUpdate.setAddress(customer.getAddress()); LOGGER.info("Updated Customer : {}", customerToUpdate); } return Optional.ofNullable(customerToUpdate); } public Optional<Customer> deleteCustomer(Customer customer) { LOGGER.info("Deleting Customer : {}", customer); Customer customerToDelete = customerRepoMap.get(customer.getEmail()); if (customerToDelete != null && customerToDelete.getId() == customer.getId()) { customerRepoMap.remove(customer.getEmail()); LOGGER.info("Deleted Customer : {}", customerToDelete); } return Optional.ofNullable(customerToDelete); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/exception/CustomErrorHandler.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/exception/CustomErrorHandler.java
package com.baeldung.bulkandbatchapi.exception; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.ConstraintViolationException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.io.IOException; @ControllerAdvice public class CustomErrorHandler { @ExceptionHandler(ConstraintViolationException.class) public void handleConstraintViolationException(ConstraintViolationException exception, HttpServletResponse httpServletResponse) throws IOException { httpServletResponse.sendError(HttpStatus.BAD_REQUEST.value(), exception.getMessage()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/exception/BatchException.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/exception/BatchException.java
package com.baeldung.bulkandbatchapi.exception; public class BatchException extends RuntimeException { public BatchException(String exceptionMsg) { super(exceptionMsg); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/response/BulkStatus.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/response/BulkStatus.java
package com.baeldung.bulkandbatchapi.response; public enum BulkStatus { PROCESSED, PARTIALLY_PROCESSED, NOT_PROCESSED }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/response/CustomerBulkResponse.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/response/CustomerBulkResponse.java
package com.baeldung.bulkandbatchapi.response; import com.baeldung.bulkandbatchapi.request.Customer; import com.baeldung.bulkandbatchapi.request.BulkActionType; import java.util.List; public class CustomerBulkResponse { private BulkActionType bulkActionType; private List<Customer> customers; private BulkStatus status; public CustomerBulkResponse() { } public CustomerBulkResponse(List<Customer> customers, BulkActionType bulkActionType, BulkStatus status) { this.customers = customers; this.bulkActionType = bulkActionType; this.status = status; } public BulkActionType getBulkType() { return bulkActionType; } public void setBulkType(BulkActionType bulkActionType) { this.bulkActionType = bulkActionType; } public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } public BulkStatus getStatus() { return status; } public void setStatus(BulkStatus status) { this.status = status; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/CustomerBulkRequest.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/CustomerBulkRequest.java
package com.baeldung.bulkandbatchapi.request; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import java.util.List; public class CustomerBulkRequest { @NotNull private BulkActionType bulkActionType; @NotNull @Size(min = 1, max = 20) private List<Customer> customers; public BulkActionType getBulkActionType() { return bulkActionType; } public List<Customer> getCustomers() { return customers; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/BulkActionType.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/BulkActionType.java
package com.baeldung.bulkandbatchapi.request; public enum BulkActionType { CREATE, UPDATE, DELETE }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/Address.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/Address.java
package com.baeldung.bulkandbatchapi.request; import jakarta.validation.constraints.NotBlank; import java.io.Serializable; public class Address implements Serializable { private int id; @NotBlank private String street; @NotBlank private String city; public Address() { } public Address(int id, String street, String city) { this.id = id; this.street = street; this.city = city; } public void setId(int id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address{" + "id=" + id + ", street='" + street + '\'' + ", city='" + city + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/Customer.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/Customer.java
package com.baeldung.bulkandbatchapi.request; import jakarta.validation.constraints.NotBlank; import java.io.Serializable; public class Customer implements Serializable { private int id; @NotBlank private String name; @NotBlank private String email; @NotBlank private String address; public Customer() { } public Customer(int id, String name, String email) { this.id = id; this.name = name; this.email = email; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Customer{" + "id=" + id + ", name='" + name + '\'' + ", email='" + email + '\'' + ", address=" + address + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/BatchRequest.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/bulkandbatchapi/request/BatchRequest.java
package com.baeldung.bulkandbatchapi.request; import com.fasterxml.jackson.databind.JsonNode; import jakarta.validation.constraints.NotNull; import org.springframework.http.HttpMethod; public class BatchRequest { @NotNull private HttpMethod method; @NotNull private String relativeUrl; @NotNull private JsonNode data; public JsonNode getData() { return data; } public @NotNull String getRelativeUrl() { return relativeUrl; } public void setRelativeUrl(@NotNull String relativeUrl) { this.relativeUrl = relativeUrl; } public void setData(@NotNull JsonNode data) { this.data = data; } public @NotNull HttpMethod getMethod() { return method; } public void setMethod(@NotNull HttpMethod method) { this.method = method; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/StatusController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/StatusController.java
package com.baeldung.httpstatuscode; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import com.baeldung.httpstatuscode.exception.CustomException; @Controller public class StatusController { @GetMapping("/resource") public ResponseEntity<String> successStatusCode() { HttpStatusCode statusCode = HttpStatusCode.valueOf(200); if (statusCode.is2xxSuccessful()) { return new ResponseEntity<>("Success", statusCode); } return new ResponseEntity<>("Moved Permanently", HttpStatusCode.valueOf(301)); } @GetMapping("/exception") public ResponseEntity<String> resourceNotFound() { HttpStatus statusCode = HttpStatus.NOT_FOUND; if (statusCode.is4xxClientError()) { return new ResponseEntity<>("Resource not found", HttpStatusCode.valueOf(404)); } return new ResponseEntity<>("Resource found", HttpStatusCode.valueOf(200)); } @GetMapping("/custom-exception") public ResponseEntity<String> goneStatusCode() { throw new CustomException("Resource Gone", HttpStatusCode.valueOf(410)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/exception/CustomException.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/exception/CustomException.java
package com.baeldung.httpstatuscode.exception; import org.springframework.http.HttpStatusCode; public class CustomException extends RuntimeException { private final HttpStatusCode statusCode; public CustomException(String message, HttpStatusCode statusCode) { super(message); this.statusCode = statusCode; } public HttpStatusCode getStatusCode() { return statusCode; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/exception/GlobalExceptionHandler.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/httpstatuscode/exception/GlobalExceptionHandler.java
package com.baeldung.httpstatuscode.exception; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleGoneException(CustomException e) { return new ResponseEntity<>(e.getMessage(), e.getStatusCode()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/Course.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/Course.java
package com.baeldung.xwwwformurlencoded; class Course { private String name; private int hours; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentController.java
package com.baeldung.xwwwformurlencoded; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/students") public class StudentController { @PostMapping(path = "/simple", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE }) public ResponseEntity<StudentSimple> createStudentSimple(StudentSimple student) { return ResponseEntity.ok(student); } @PostMapping(path = "/complex", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE }) public ResponseEntity<StudentComplex> createStudentComplex(StudentComplex student) { return ResponseEntity.ok(student); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentSimple.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentSimple.java
package com.baeldung.xwwwformurlencoded; class StudentSimple { private String firstName; private String lastName; private String[] courses; 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; } public String[] getCourses() { return courses; } public void setCourses(String[] courses) { this.courses = courses; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentComplex.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xwwwformurlencoded/StudentComplex.java
package com.baeldung.xwwwformurlencoded; class StudentComplex { private String firstName; private String lastName; private Course[] courses; 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; } public Course[] getCourses() { return courses; } public void setCourses(Course[] courses) { this.courses = courses; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/zip/ZipArchiveController.java
spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/zip/ZipArchiveController.java
package com.baeldung.zip; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.EncryptionMethod; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @RestController public class ZipArchiveController { @GetMapping(value = "/zip-archive", produces = "application/zip") public ResponseEntity<byte[]> getZipBytes() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream); ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream); zipOutputStream.setLevel(0); addFilesToArchive(zipOutputStream); IOUtils.closeQuietly(bufferedOutputStream); IOUtils.closeQuietly(byteArrayOutputStream); return ResponseEntity .ok() .header("Content-Disposition", "attachment; filename=\"files.zip\"") .body(byteArrayOutputStream.toByteArray()); } @GetMapping(value = "/zip-archive-stream", produces = "application/zip") public ResponseEntity<StreamingResponseBody> getZipStream() { return ResponseEntity .ok() .header("Content-Disposition", "attachment; filename=\"files.zip\"") .body(out -> { ZipOutputStream zipOutputStream = new ZipOutputStream(out); zipOutputStream.setLevel(9); addFilesToArchive(zipOutputStream); }); } @GetMapping(value = "/zip-archive-stream-secured", produces = "application/zip") public ResponseEntity<StreamingResponseBody> getZipSecuredStream() { return ResponseEntity .ok() .header("Content-Disposition", "attachment; filename=\"files.zip\"") .body(out -> { net.lingala.zip4j.io.outputstream.ZipOutputStream zipOutputStream = new net.lingala.zip4j.io.outputstream.ZipOutputStream(out, "password".toCharArray()); addFilesToArchive(zipOutputStream); }); } void addFilesToArchive(net.lingala.zip4j.io.outputstream.ZipOutputStream zipOutputStream) throws IOException { List<String> filesNames = new ArrayList<>(); filesNames.add("first-file.txt"); filesNames.add("second-file.txt"); ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.DEFLATE); zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); zipParameters.setEncryptFiles(true); for (String fileName : filesNames) { File file = new File(ZipArchiveController.class.getClassLoader() .getResource(fileName).getFile()); zipParameters.setFileNameInZip(file.getName()); zipOutputStream.putNextEntry(zipParameters); FileInputStream fileInputStream = new FileInputStream(file); IOUtils.copy(fileInputStream, zipOutputStream); fileInputStream.close(); zipOutputStream.closeEntry(); } zipOutputStream.flush(); IOUtils.closeQuietly(zipOutputStream); } void addFilesToArchive(ZipOutputStream zipOutputStream) throws IOException { List<String> filesNames = new ArrayList<>(); filesNames.add("first-file.txt"); filesNames.add("second-file.txt"); for (String fileName : filesNames) { File file = new File(ZipArchiveController.class.getClassLoader() .getResource(fileName).getFile()); zipOutputStream.putNextEntry(new ZipEntry(file.getName())); FileInputStream fileInputStream = new FileInputStream(file); IOUtils.copy(fileInputStream, zipOutputStream); fileInputStream.close(); zipOutputStream.closeEntry(); } zipOutputStream.finish(); zipOutputStream.flush(); IOUtils.closeQuietly(zipOutputStream); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-5-mvc/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java
spring-web-modules/spring-5-mvc/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java
package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) public class Spring5ApplicationIntegrationTest { @Test public void contextLoads() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false