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-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/GenderAnalysisService.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/GenderAnalysisService.java
package com.baeldung.accesing_session_attributes.business; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.baeldung.accesing_session_attributes.business.entities.NameGenderEntity; @Service public interface GenderAnalysisService { ResponseEntity<NameGenderEntity> getGenderAnalysisForName(String nameToAnalyze); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/AgeAnalysisService.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/AgeAnalysisService.java
package com.baeldung.accesing_session_attributes.business; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.baeldung.accesing_session_attributes.business.entities.NameAgeEntity; @Service public interface AgeAnalysisService { ResponseEntity<NameAgeEntity> getAgeAnalysisForName(String nameToAnalyze); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/beans/NameRequest.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/beans/NameRequest.java
package com.baeldung.accesing_session_attributes.business.beans; public class NameRequest { private String name; public NameRequest() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameRequest other = (NameRequest) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "NameRequestEntity [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-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameCountryEntity.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameCountryEntity.java
package com.baeldung.accesing_session_attributes.business.entities; /** * NameCountryModel * * https://www.countryflagicons.com/ * <img src="https://www.countryflagicons.com/STYLE/size/COUNTRYCODE.png"> * STYLE: FLAT, SHINY * size: 16, 24, 32, 48, 64 * COUNTRYCODE: country_id */ public class NameCountryEntity { private String country_id; private Float probability; public NameCountryEntity() { super(); } public String getCountry_id() { return country_id; } public void setCountry_id(String country_id) { this.country_id = country_id; } public Float getProbability() { return probability; } public void setProbability(Float probability) { this.probability = probability; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((country_id == null) ? 0 : country_id.hashCode()); result = prime * result + ((probability == null) ? 0 : probability.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameCountryEntity other = (NameCountryEntity) obj; if (country_id == null) { if (other.country_id != null) return false; } else if (!country_id.equals(other.country_id)) return false; if (probability == null) { if (other.probability != null) return false; } else if (!probability.equals(other.probability)) return false; return true; } @Override public String toString() { return "NameCountryModel [country_id=" + country_id + ", probability=" + probability + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameAgeEntity.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameAgeEntity.java
package com.baeldung.accesing_session_attributes.business.entities; /** * https://api.agify.io/?name=michael */ public class NameAgeEntity { private Integer age; private Long count; private String name; public NameAgeEntity() { super(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((count == null) ? 0 : count.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameAgeEntity other = (NameAgeEntity) obj; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (count == null) { if (other.count != null) return false; } else if (!count.equals(other.count)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "NameAgeEntity [age=" + age + ", count=" + count + ", 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-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameGenderEntity.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameGenderEntity.java
package com.baeldung.accesing_session_attributes.business.entities; /** * NameGenderModel * https://api.genderize.io/?name=victor */ public class NameGenderEntity { private Long count; private String gender; private String name; private Float probability; public NameGenderEntity() { super(); } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getProbability() { return probability; } public void setProbability(Float probability) { this.probability = probability; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((count == null) ? 0 : count.hashCode()); result = prime * result + ((gender == null) ? 0 : gender.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((probability == null) ? 0 : probability.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameGenderEntity other = (NameGenderEntity) obj; if (count == null) { if (other.count != null) return false; } else if (!count.equals(other.count)) return false; if (gender == null) { if (other.gender != null) return false; } else if (!gender.equals(other.gender)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (probability == null) { if (other.probability != null) return false; } else if (!probability.equals(other.probability)) return false; return true; } @Override public String toString() { return "NameGenderModel [count=" + count + ", gender=" + gender + ", name=" + name + ", probability=" + probability + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameAnalysisEntity.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameAnalysisEntity.java
package com.baeldung.accesing_session_attributes.business.entities; public class NameAnalysisEntity { private String name; private NameAgeEntity age; private NameCountriesEntity countries; private NameGenderEntity gender; public NameAnalysisEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public NameAgeEntity getAge() { return age; } public void setAge(NameAgeEntity age) { this.age = age; } public NameCountriesEntity getCountries() { return countries; } public void setCountries(NameCountriesEntity countries) { this.countries = countries; } public NameGenderEntity getGender() { return gender; } public void setGender(NameGenderEntity gender) { this.gender = gender; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((countries == null) ? 0 : countries.hashCode()); result = prime * result + ((gender == null) ? 0 : gender.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameAnalysisEntity other = (NameAnalysisEntity) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (countries == null) { if (other.countries != null) return false; } else if (!countries.equals(other.countries)) return false; if (gender == null) { if (other.gender != null) return false; } else if (!gender.equals(other.gender)) return false; return true; } @Override public String toString() { return "NameAnalysisEntity [name=" + name + ", age=" + age + ", countries=" + countries + ", gender=" + gender + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameCountriesEntity.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/NameCountriesEntity.java
package com.baeldung.accesing_session_attributes.business.entities; import java.util.List; /** * https://api.nationalize.io/?name=michael */ public class NameCountriesEntity { private String name; private List<NameCountryEntity> country; public NameCountriesEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<NameCountryEntity> getCountry() { return country; } public void setCountry(List<NameCountryEntity> country) { this.country = country; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((country == null) ? 0 : country.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameCountriesEntity other = (NameCountriesEntity) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; return true; } @Override public String toString() { return "NameCountriesModel [name=" + name + ", country=" + country + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/factories/NameAnalysisEntityFactory.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/entities/factories/NameAnalysisEntityFactory.java
package com.baeldung.accesing_session_attributes.business.entities.factories; import org.springframework.stereotype.Service; import com.baeldung.accesing_session_attributes.business.entities.NameAgeEntity; import com.baeldung.accesing_session_attributes.business.entities.NameAnalysisEntity; import com.baeldung.accesing_session_attributes.business.entities.NameCountriesEntity; import com.baeldung.accesing_session_attributes.business.entities.NameGenderEntity; @Service public class NameAnalysisEntityFactory { public NameAnalysisEntity getInstance(String nameRequest, NameGenderEntity gender, NameAgeEntity age, NameCountriesEntity countries) { NameAnalysisEntity nameAnalysis = new NameAnalysisEntity(); nameAnalysis.setName(nameRequest); nameAnalysis.setGender(gender); nameAnalysis.setAge(age); nameAnalysis.setCountries(countries); return nameAnalysis; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/NameAnalysisServiceImpl.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/NameAnalysisServiceImpl.java
package com.baeldung.accesing_session_attributes.business.impl; import java.net.URLEncoder; import java.util.concurrent.CompletableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import com.baeldung.accesing_session_attributes.business.AgeAnalysisService; import com.baeldung.accesing_session_attributes.business.CountryAnalysisService; import com.baeldung.accesing_session_attributes.business.GenderAnalysisService; import com.baeldung.accesing_session_attributes.business.NameAnalysisService; import com.baeldung.accesing_session_attributes.business.beans.NameRequest; import com.baeldung.accesing_session_attributes.business.entities.NameAgeEntity; import com.baeldung.accesing_session_attributes.business.entities.NameAnalysisEntity; import com.baeldung.accesing_session_attributes.business.entities.NameCountriesEntity; import com.baeldung.accesing_session_attributes.business.entities.NameGenderEntity; import com.baeldung.accesing_session_attributes.business.entities.factories.NameAnalysisEntityFactory; @Component public class NameAnalysisServiceImpl implements NameAnalysisService { private NameRequest lastNameRequest; private AgeAnalysisService ageAnalysisService; private CountryAnalysisService countryAnalysisService; private GenderAnalysisService genderAnalysisService; private NameAnalysisEntityFactory nameAnalysisEntityFactory; @Autowired public NameAnalysisServiceImpl(AgeAnalysisService ageAnalysisService, CountryAnalysisService countryAnalysisService, GenderAnalysisService genderAnalysisService, NameAnalysisEntityFactory nameAnalysisEntityFactory) { super(); this.ageAnalysisService = ageAnalysisService; this.countryAnalysisService = countryAnalysisService; this.genderAnalysisService = genderAnalysisService; this.nameAnalysisEntityFactory = nameAnalysisEntityFactory; lastNameRequest = new NameRequest(); lastNameRequest.setName("Rigoberto"); } public NameRequest getLastNameRequest() { return lastNameRequest; } public CompletableFuture<NameAnalysisEntity> searchForName(NameRequest nameRequest) { this.lastNameRequest.setName(nameRequest.getName()); return analyzeName(); } @Async private CompletableFuture<NameAnalysisEntity> analyzeName() { try { String nameToAnalyze = URLEncoder.encode(lastNameRequest.getName(), "UTF-8"); ResponseEntity<NameAgeEntity> ageRequestResponse = ageAnalysisService.getAgeAnalysisForName(nameToAnalyze); ResponseEntity<NameCountriesEntity> countriesRequestResponse = countryAnalysisService.getCountryAnalysisForName(nameToAnalyze); ResponseEntity<NameGenderEntity> genderRequestResponse = genderAnalysisService.getGenderAnalysisForName(nameToAnalyze); NameAnalysisEntity nameAnalysis = nameAnalysisEntityFactory.getInstance(lastNameRequest.getName(), genderRequestResponse.getBody(), ageRequestResponse.getBody(), countriesRequestResponse.getBody()); return CompletableFuture.completedFuture(nameAnalysis); } catch (Exception e) { return CompletableFuture.failedFuture(e); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/CountryAnalysisServiceImpl.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/CountryAnalysisServiceImpl.java
package com.baeldung.accesing_session_attributes.business.impl; import java.net.URI; import java.text.MessageFormat; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.baeldung.accesing_session_attributes.business.CountryAnalysisService; import com.baeldung.accesing_session_attributes.business.entities.NameCountriesEntity; @Component public class CountryAnalysisServiceImpl implements CountryAnalysisService { @Value("${name-analysis-controller.name-countries-api-url:https://api.nationalize.io/?name={0}}") private String nameCountriesApiUrl; @Override public ResponseEntity<NameCountriesEntity> getCountryAnalysisForName(String nameToAnalyze) { RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForEntity(URI.create(MessageFormat.format(nameCountriesApiUrl, nameToAnalyze)), NameCountriesEntity.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/AgeAnalysisServiceImpl.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/AgeAnalysisServiceImpl.java
package com.baeldung.accesing_session_attributes.business.impl; import java.net.URI; import java.text.MessageFormat; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.baeldung.accesing_session_attributes.business.AgeAnalysisService; import com.baeldung.accesing_session_attributes.business.entities.NameAgeEntity; @Component public class AgeAnalysisServiceImpl implements AgeAnalysisService { @Value("${name-analysis-controller.name-age-api-url:https://api.agify.io/?name={0}}") private String nameAgeApiUrl; @Override public ResponseEntity<NameAgeEntity> getAgeAnalysisForName(String nameToAnalyze) { RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForEntity(URI.create(MessageFormat.format(nameAgeApiUrl, nameToAnalyze)), NameAgeEntity.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/GenderAnalysisServiceImpl.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/business/impl/GenderAnalysisServiceImpl.java
package com.baeldung.accesing_session_attributes.business.impl; import java.net.URI; import java.text.MessageFormat; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.baeldung.accesing_session_attributes.business.GenderAnalysisService; import com.baeldung.accesing_session_attributes.business.entities.NameGenderEntity; @Component public class GenderAnalysisServiceImpl implements GenderAnalysisService { @Value("${name-analysis-controller.name-gender-api-url:https://api.genderize.io/?name={0}}") private String nameGenderApiUrl; @Override public ResponseEntity<NameGenderEntity> getGenderAnalysisForName(String nameToAnalyze) { RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForEntity(URI.create(MessageFormat.format(nameGenderApiUrl, nameToAnalyze)), NameGenderEntity.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/SpringWebConfig.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/SpringWebConfig.java
package com.baeldung.accesing_session_attributes.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.templatemode.TemplateMode; @Configuration @EnableWebMvc public class SpringWebConfig implements WebMvcConfigurer { // , ApplicationContextAware { @Autowired public SpringWebConfig(SpringResourceTemplateResolver templateResolver) { super(); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); } /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**") .addResourceLocations("/images/"); registry.addResourceHandler("/css/**") .addResourceLocations("/css/"); registry.addResourceHandler("/js/**") .addResourceLocations("/js/"); } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.addBasenames("name-analysis"); return messageSource; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/beans/SessionNameRequest.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/beans/SessionNameRequest.java
package com.baeldung.accesing_session_attributes.web.beans; import java.util.Date; import com.baeldung.accesing_session_attributes.business.beans.NameRequest; public class SessionNameRequest { private Date requestDate; private NameRequest nameRequest; public SessionNameRequest() { super(); } public Date getRequestDate() { return requestDate; } public void setRequestDate(Date requestDate) { this.requestDate = requestDate; } public NameRequest getNameRequest() { return nameRequest; } public void setNameRequest(NameRequest nameRequest) { this.nameRequest = nameRequest; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((requestDate == null) ? 0 : requestDate.hashCode()); result = prime * result + ((nameRequest == null) ? 0 : nameRequest.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SessionNameRequest other = (SessionNameRequest) obj; if (requestDate == null) { if (other.requestDate != null) return false; } else if (!requestDate.equals(other.requestDate)) return false; if (nameRequest == null) { if (other.nameRequest != null) return false; } else if (!nameRequest.equals(other.nameRequest)) return false; return true; } @Override public String toString() { return "SessionNameRequest [requestDate=" + requestDate + ", nameRequest=" + nameRequest + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/factories/SessionNameRequestFactory.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/factories/SessionNameRequestFactory.java
package com.baeldung.accesing_session_attributes.web.factories; import java.util.Date; import org.springframework.stereotype.Service; import com.baeldung.accesing_session_attributes.business.beans.NameRequest; import com.baeldung.accesing_session_attributes.web.beans.SessionNameRequest; @Service public class SessionNameRequestFactory { public SessionNameRequest getInstance(NameRequest nameRequest) { NameRequest cloned = new NameRequest(); cloned.setName(nameRequest.getName()); SessionNameRequest sessionNameRequest = new SessionNameRequest(); sessionNameRequest.setRequestDate(new Date()); sessionNameRequest.setNameRequest(cloned); return sessionNameRequest; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/controllers/NameAnalysisController.java
spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/src/main/java/com/baeldung/accesing_session_attributes/web/controllers/NameAnalysisController.java
package com.baeldung.accesing_session_attributes.web.controllers; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.thymeleaf.web.IWebSession; import org.thymeleaf.web.servlet.IServletWebExchange; import org.thymeleaf.web.servlet.JakartaServletWebApplication; import com.baeldung.accesing_session_attributes.business.NameAnalysisService; import com.baeldung.accesing_session_attributes.business.beans.NameRequest; import com.baeldung.accesing_session_attributes.business.entities.NameAnalysisEntity; import com.baeldung.accesing_session_attributes.web.beans.SessionNameRequest; import com.baeldung.accesing_session_attributes.web.factories.SessionNameRequestFactory; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Controller public class NameAnalysisController { private NameAnalysisService nameAnalysisService; private SessionNameRequestFactory sessionNameRequestFactory; private JakartaServletWebApplication webApp; @Autowired public NameAnalysisController(NameAnalysisService nameAnalysisService, SessionNameRequestFactory sessionNameRequestFactory, ServletContext servletContext) { super(); this.nameAnalysisService = nameAnalysisService; this.sessionNameRequestFactory = sessionNameRequestFactory; this.webApp = JakartaServletWebApplication.buildApplication(servletContext); } @ModelAttribute("nameRequest") public NameRequest nameRequest() { return nameAnalysisService.getLastNameRequest(); } @RequestMapping({ "/", "/name-analysis" }) public String showNameAnalysis() { return "name-analysis"; } @RequestMapping(value = "/name-analysis", params = { "search" }) public String performNameAnalysis(final NameRequest nameRequest, final BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) { IWebSession webSession = getIWebSession(request, response); performNameRequest(nameRequest, webSession); return "name-analysis"; } @RequestMapping(value = "/name-analysis/clear") public String clearNameAnalysis(HttpServletRequest request, HttpServletResponse response) { IWebSession webSession = getIWebSession(request, response); clearAnalysis(webSession); return "redirect:/name-analysis"; } @RequestMapping(value = "/name-analysis/remove-history-request", params = { "id" }) public String removeRequest(HttpServletRequest request, HttpServletResponse response) { try { IWebSession webSession = getIWebSession(request, response); final Integer rowId = Integer.valueOf(request.getParameter("id")); removeRequest(rowId, webSession); } catch (Exception e) { e.printStackTrace(); } return "redirect:/name-analysis"; } private void removeRequest(Integer rowId, IWebSession webSession) { if (rowId != null) { List<SessionNameRequest> requests = getRequestsFromSession(webSession); if (requests != null) { requests.remove(rowId.intValue()); } } } private void performNameRequest(final NameRequest nameRequest, IWebSession webSession) { try { CompletableFuture<NameAnalysisEntity> nameAnalysis = this.nameAnalysisService.searchForName(nameRequest); NameAnalysisEntity nameAnalysisEntity = nameAnalysis.get(30, TimeUnit.SECONDS); sessionRegisterRequest(nameRequest, webSession); sessionRegisterAnalysis(nameAnalysisEntity, webSession); sessionClearAnalysisError(webSession); } catch (Exception e) { e.printStackTrace(); sessionSetAnalysisError(nameRequest, webSession); } } private void sessionClearAnalysisError(IWebSession webSession) { webSession.removeAttribute("analysisError"); } private void sessionSetAnalysisError(NameRequest nameRequest, IWebSession webSession) { webSession.setAttributeValue("analysisError", nameRequest); } private void clearAnalysis(IWebSession webSession) { webSession.removeAttribute("lastAnalysis"); } private void sessionRegisterAnalysis(NameAnalysisEntity analysis, IWebSession webSession) { webSession.setAttributeValue("lastAnalysis", analysis); } private void sessionRegisterRequest(NameRequest nameRequest, IWebSession webSession) { webSession.setAttributeValue("lastRequest", nameRequest); SessionNameRequest sessionNameRequest = sessionNameRequestFactory.getInstance(nameRequest); List<SessionNameRequest> requests = getRequestsFromSession(webSession); requests.add(0, sessionNameRequest); } private List<SessionNameRequest> getRequestsFromSession(IWebSession session) { Object requests = session.getAttributeValue("requests"); if (requests == null || !(requests instanceof List)) { List<SessionNameRequest> sessionNameRequests = new ArrayList<>(); session.setAttributeValue("requests", sessionNameRequests); requests = sessionNameRequests; } return (List<SessionNameRequest>) requests; } private IWebSession getIWebSession(HttpServletRequest request, HttpServletResponse response) { IServletWebExchange exchange = webApp.buildExchange(request, response); return exchange == null ? null : exchange.getSession(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java
spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java
package com.baeldung.file; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockMultipartFile; class CustomMultipartFileUnitTest { @Test void whenProvidingByteArray_thenMultipartFileCreated() { byte[] inputArray = "Test String".getBytes(); CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray); Assertions.assertFalse(customMultipartFile.isEmpty()); Assertions.assertArrayEquals(inputArray, customMultipartFile.getBytes()); Assertions.assertEquals(inputArray.length, customMultipartFile.getSize()); } @Test void whenProvidingEmptyByteArray_thenMockMultipartFileIsEmpty() { byte[] inputArray = "".getBytes(); MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); Assertions.assertTrue(mockMultipartFile.isEmpty()); } @Test void whenProvidingNullByteArray_thenMockMultipartFileIsEmpty() { byte[] inputArray = null; MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); Assertions.assertTrue(mockMultipartFile.isEmpty()); } @Test void whenProvidingByteArray_thenMultipartFileInputSizeMatches() { byte[] inputArray = "Testing String".getBytes(); CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray); Assertions.assertEquals(inputArray.length, customMultipartFile.getSize()); } @Test void whenProvidingByteArray_thenMockMultipartFileCreated() throws IOException { byte[] inputArray = "Test String".getBytes(); MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); Assertions.assertFalse(mockMultipartFile.isEmpty()); Assertions.assertArrayEquals(inputArray, mockMultipartFile.getBytes()); Assertions.assertEquals(inputArray.length, mockMultipartFile.getSize()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java
spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java
spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java
package com.baeldung.file; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.web.multipart.MultipartFile; public class CustomMultipartFile implements MultipartFile { private byte[] input; public CustomMultipartFile(byte[] input) { this.input = input; } @Override public String getName() { return null; } @Override public String getOriginalFilename() { return null; } @Override public String getContentType() { return null; } @Override public boolean isEmpty() { return input == null || input.length == 0; } @Override public long getSize() { return input.length; } @Override public byte[] getBytes() { return input; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(input); } @Override public void transferTo(File destination) throws IOException, IllegalStateException { try(FileOutputStream fos = new FileOutputStream(destination)) { fos.write(input); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/test/java/com/baeldung/requestmappingvalue/WelcomeControllerUnitTest.java
spring-web-modules/spring-mvc-basics-6/src/test/java/com/baeldung/requestmappingvalue/WelcomeControllerUnitTest.java
package com.baeldung.requestmappingvalue; 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.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc class WelcomeControllerUnitTest { @Autowired private MockMvc mockMvc; @Test public void whenUserAccessToWelcome_thenReturnOK() throws Exception { this.mockMvc.perform(get("/welcome")) .andExpect(status().isOk()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/test/java/com/baeldung/requestparam/QueryStringControllerIntegrationTest.java
spring-web-modules/spring-mvc-basics-6/src/test/java/com/baeldung/requestparam/QueryStringControllerIntegrationTest.java
package com.baeldung.requestparam; import static org.hamcrest.Matchers.containsInRelativeOrder; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; 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.test.web.servlet.MockMvc; @SpringBootTest @AutoConfigureMockMvc class QueryStringControllerIntegrationTest { @Autowired private MockMvc mockMvc; @BeforeEach public void setup() { this.mockMvc = standaloneSetup(new QueryStringController()).build(); } @Test public void whenInvokeGetQueryString_thenReturnTheOriginQueryString() throws Exception { this.mockMvc.perform(get("/api/byGetQueryString?username=bob&roles=admin&roles=stuff")) .andExpect(status().isOk()) .andExpect(content().string("username=bob&roles=admin&roles=stuff")); } @Test public void whenInvokeGetQueryParameter_thenReturnOneParameterValue() throws Exception { this.mockMvc.perform(get("/api/byGetParameter?username=bob")) .andExpect(status().isOk()) .andExpect(content().string("username:bob")); } @Test public void whenInvokeGetParameterValues_thenReturnParameterAsArray() throws Exception { this.mockMvc.perform(get("/api/byGetParameterValues?roles=admin&roles=stuff")) .andExpect(status().isOk()) .andExpect(content().string("roles:[admin, stuff]")); } @ParameterizedTest @CsvSource({ "/api/byGetParameterMap", "/api/byParameterName", "/api/byAnnoRequestParam", "/api/byPojo" }) public void whenPassParameters_thenReturnResolvedModel(String path) throws Exception { this.mockMvc.perform(get(path + "?username=bob&roles=admin&roles=stuff")) .andExpect(status().isOk()) .andExpect(jsonPath("$.username").value("bob")) .andExpect(jsonPath("$.roles").value(containsInRelativeOrder("admin", "stuff"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/Application.java
spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/Application.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestmappingvalue/WelcomeController.java
spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestmappingvalue/WelcomeController.java
package com.baeldung.requestmappingvalue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/${request.value}") public class WelcomeController { @GetMapping public String getWelcomeMessage() { return "Welcome to Baeldung!"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestparam/UserDto.java
spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestparam/UserDto.java
package com.baeldung.requestparam; import java.util.List; public class UserDto { private String username; private List<String> roles; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestparam/QueryStringController.java
spring-web-modules/spring-mvc-basics-6/src/main/java/com/baeldung/requestparam/QueryStringController.java
package com.baeldung.requestparam; import java.util.Arrays; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; @RestController public class QueryStringController { @GetMapping("/api/byGetQueryString") public String byGetQueryString(HttpServletRequest request) { return request.getQueryString(); } @GetMapping("/api/byGetParameter") public String byGetParameter(HttpServletRequest request) { String username = request.getParameter("username"); return "username:" + username; } @GetMapping("/api/byGetParameterValues") public String byGetParameterValues(HttpServletRequest request) { String[] roles = request.getParameterValues("roles"); return "roles:" + Arrays.toString(roles); } @GetMapping("/api/byGetParameterMap") public UserDto byGetParameterMap(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); String[] usernames = parameterMap.get("username"); String[] roles = parameterMap.get("roles"); UserDto userDto = new UserDto(); userDto.setUsername(usernames[0]); userDto.setRoles(Arrays.asList(roles)); return userDto; } @GetMapping("/api/byParameterName") public UserDto byParameterName(String username, String[] roles) { UserDto userDto = new UserDto(); userDto.setUsername(username); userDto.setRoles(Arrays.asList(roles)); return userDto; } @GetMapping("/api/byAnnoRequestParam") public UserDto byAnnoRequestParam(@RequestParam("username") String var1, @RequestParam("roles") List<String> var2) { UserDto userDto = new UserDto(); userDto.setUsername(var1); userDto.setRoles(var2); return userDto; } @GetMapping("/api/byPojo") public UserDto byPojo(UserDto userDto) { return userDto; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/RetrieveUtil.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/RetrieveUtil.java
package com.baeldung.rest; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class RetrieveUtil { // API public static <T> T retrieveResourceFromResponse(final HttpResponse response, final Class<T> clazz) throws IOException { final String jsonFromResponse = EntityUtils.toString(response.getEntity()); final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(jsonFromResponse, clazz); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/GitHubUser.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/GitHubUser.java
package com.baeldung.rest; public class GitHubUser { private String login; public GitHubUser() { super(); } // API public String getLogin() { return login; } public void setLogin(final String login) { this.login = login; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/GithubBasicLiveTest.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/rest/GithubBasicLiveTest.java
package com.baeldung.rest; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.HttpClientBuilder; import org.hamcrest.Matchers; import org.junit.Test; public class GithubBasicLiveTest { // simple request - response @Test public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived() throws ClientProtocolException, IOException { // Given final String name = randomAlphabetic(8); final HttpUriRequest request = new HttpGet("https://api.github.com/users/" + name); // When final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); // Then assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_NOT_FOUND)); } @Test public void givenRequestWithNoAcceptHeader_whenRequestIsExecuted_thenDefaultResponseContentTypeIsJson() throws ClientProtocolException, IOException { // Given final String jsonMimeType = "application/json"; final HttpUriRequest request = new HttpGet("https://api.github.com/users/eugenp"); // When final HttpResponse response = HttpClientBuilder.create().build().execute(request); // Then final String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType(); assertEquals(jsonMimeType, mimeType); } @Test public void givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect() throws ClientProtocolException, IOException { // Given final HttpUriRequest request = new HttpGet("https://api.github.com/users/eugenp"); // When final HttpResponse response = HttpClientBuilder.create().build().execute(request); // Then final GitHubUser resource = RetrieveUtil.retrieveResourceFromResponse(response, GitHubUser.class); assertThat("eugenp", Matchers.is(resource.getLogin())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/requestresponsebody/controllers/ExamplePostControllerResponseIntegrationTest.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/requestresponsebody/controllers/ExamplePostControllerResponseIntegrationTest.java
package com.baeldung.requestresponsebody.controllers; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.SpringBootRestApplication; import com.baeldung.requestresponsebody.ExamplePostController; import com.baeldung.requestresponsebody.LoginForm; import com.baeldung.services.ExampleService; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootRestApplication.class) public class ExamplePostControllerResponseIntegrationTest { MockMvc mockMvc; @Mock private ExampleService exampleService; @InjectMocks private ExamplePostController exampleController; private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}"; private LoginForm lf = new LoginForm(); @Before public void preTest() { MockitoAnnotations.openMocks(this); mockMvc = MockMvcBuilders .standaloneSetup(exampleController) .build(); lf.setPassword("password"); lf.setUsername("username"); } @Test public void requestBodyTest() { try { when(exampleService.fakeAuthenticate(lf)).thenReturn(true); mockMvc .perform(post("/post/response") .content(jsonBody) .contentType("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"text\":\"Thanks For Posting!!!\"}")); } catch (Exception e) { System.out.println("Exception: " + e); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/requestresponsebody/controllers/ExamplePostControllerRequestIntegrationTest.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/requestresponsebody/controllers/ExamplePostControllerRequestIntegrationTest.java
package com.baeldung.requestresponsebody.controllers; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 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.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.SpringBootRestApplication; import com.baeldung.requestresponsebody.ExamplePostController; import com.baeldung.requestresponsebody.LoginForm; import com.baeldung.services.ExampleService; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootRestApplication.class) public class ExamplePostControllerRequestIntegrationTest { MockMvc mockMvc; @Mock private ExampleService exampleService; @InjectMocks private ExamplePostController exampleController; private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}"; private LoginForm lf = new LoginForm(); @Before public void preTest() { MockitoAnnotations.openMocks(this); mockMvc = MockMvcBuilders .standaloneSetup(exampleController) .build(); lf.setPassword("password"); lf.setUsername("username"); } @Test public void requestBodyTest() { try { when(exampleService.fakeAuthenticate(lf)).thenReturn(true); mockMvc .perform(post("/post/request") .content(jsonBody) .contentType("application/json")) .andDo(print()) .andExpect(status().isOk()); } catch (Exception e) { System.out.println("Exception: " + e); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java
package com.baeldung.web; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.persistence.dao.IFooDao; /** * We'll start the whole context, but not the server. We'll mock the REST calls instead. */ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class FooControllerAppIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private IFooDao fooDao; @Before public void setup() { this.fooDao.deleteAll(); } @Test public void whenTestApp_thenEmptyResponse() throws Exception { this.mockMvc.perform(get("/foos")) .andExpect(status().isOk()) .andExpect(content().json("[]")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java
spring-web-modules/spring-boot-rest-simple/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java
package com.baeldung.web; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.persistence.service.IFooService; import com.baeldung.web.controller.FooController; /** * * We'll start only the web layer. * */ @RunWith(SpringRunner.class) @WebMvcTest(FooController.class) public class FooControllerWebLayerIntegrationTest { @Autowired private MockMvc mockMvc; @MockBean private IFooService service; @Test public void whenTestMvcController_thenRetrieveExpectedResult() throws Exception { this.mockMvc.perform(get("/foos")) .andExpect(status().isOk()) .andExpect(content().json("[]")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/SpringBootRestApplication.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/SpringBootRestApplication.java
package com.baeldung; import org.modelmapper.ModelMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } @Bean public ModelMapper modelMapper() { return new ModelMapper(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/services/ExampleService.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/services/ExampleService.java
package com.baeldung.services; import org.springframework.stereotype.Service; import com.baeldung.requestresponsebody.LoginForm; @Service public class ExampleService { public boolean fakeAuthenticate(LoginForm lf) { return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/IOperations.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/IOperations.java
package com.baeldung.persistence; import java.io.Serializable; import java.util.List; import org.springframework.data.domain.Page; public interface IOperations<T extends Serializable> { // read - one T findById(final long id); // read - all List<T> findAll(); Page<T> findPaginated(int page, int size); // write T create(final T entity); T update(final T entity); void delete(final T entity); void deleteById(final long entityId); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/dao/IFooDao.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/dao/IFooDao.java
package com.baeldung.persistence.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.baeldung.persistence.model.Foo; public interface IFooDao extends JpaRepository<Foo, Long> { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/IFooService.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/IFooService.java
package com.baeldung.persistence.service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.baeldung.persistence.IOperations; import com.baeldung.persistence.model.Foo; public interface IFooService extends IOperations<Foo> { Page<Foo> findPaginated(Pageable pageable); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/impl/FooService.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/impl/FooService.java
package com.baeldung.persistence.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.dao.IFooDao; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.persistence.service.common.AbstractService; import com.google.common.collect.Lists; @Service @Transactional public class FooService extends AbstractService<Foo> implements IFooService { @Autowired private IFooDao dao; public FooService() { super(); } // API @Override protected JpaRepository<Foo, Long> getDao() { return dao; } // custom methods @Override public Page<Foo> findPaginated(Pageable pageable) { return dao.findAll(pageable); } // overridden to be secured @Override @Transactional(readOnly = true) public List<Foo> findAll() { return Lists.newArrayList(getDao().findAll()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/common/AbstractService.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/service/common/AbstractService.java
package com.baeldung.persistence.service.common; import java.io.Serializable; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.IOperations; import com.google.common.collect.Lists; @Transactional public abstract class AbstractService<T extends Serializable> implements IOperations<T> { // read - one @Override @Transactional(readOnly = true) public T findById(final long id) { return getDao().findById(id).orElse(null); } // read - all @Override @Transactional(readOnly = true) public List<T> findAll() { return Lists.newArrayList(getDao().findAll()); } @Override public Page<T> findPaginated(final int page, final int size) { return getDao().findAll(PageRequest.of(page, size)); } // write @Override public T create(final T entity) { return getDao().save(entity); } @Override public T update(final T entity) { return getDao().save(entity); } @Override public void delete(final T entity) { getDao().delete(entity); } @Override public void deleteById(final long entityId) { getDao().deleteById(entityId); } protected abstract JpaRepository<T, Long> getDao(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/model/Foo.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/persistence/model/Foo.java
package com.baeldung.persistence.model; import java.io.Serializable; import com.thoughtworks.xstream.annotations.XStreamAlias; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Version; @XStreamAlias("Foo") @Entity public class Foo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String name; @Version private long version; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } // API public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } // @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Foo other = (Foo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/ResponseTransfer.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/ResponseTransfer.java
package com.baeldung.requestresponsebody; public class ResponseTransfer { private String text; public ResponseTransfer(String text) { this.setText(text); } public String getText() { return text; } public void setText(String text) { this.text = text; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java
package com.baeldung.requestresponsebody; import com.baeldung.services.ExampleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.stereotype.Controller; 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.ResponseBody; @Controller @RequestMapping("/post") public class ExamplePostController { private static Logger log = LoggerFactory.getLogger(ExamplePostController.class); @Autowired ExampleService exampleService; @PostMapping("/request") public ResponseEntity postController(@RequestBody LoginForm loginForm) { log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); exampleService.fakeAuthenticate(loginForm); return ResponseEntity.ok(HttpStatus.OK); } @PostMapping("/response") @ResponseBody public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) { log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); return new ResponseTransfer("Thanks For Posting!!!"); } @PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseTransfer postResponseJsonContent(@RequestBody LoginForm loginForm) { log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); return new ResponseTransfer("JSON Content!"); } @PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public ResponseTransfer postResponseXmlContent(@RequestBody LoginForm loginForm) { log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); return new ResponseTransfer("XML Content!"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/LoginForm.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/requestresponsebody/LoginForm.java
package com.baeldung.requestresponsebody; public class LoginForm { private String username; private String password; public LoginForm() { } public LoginForm(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java
package com.baeldung.web.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.web.util.RestPreconditions; import com.google.common.base.Preconditions; @RestController @RequestMapping(value = "/foos") public class FooController { private static final Logger logger = LoggerFactory.getLogger(FooController.class); @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private IFooService service; public FooController() { super(); } // read - one @GetMapping(value = "/{id}") public Foo findById(@PathVariable("id") final Long id) { return RestPreconditions.checkFound(service.findById(id)); } // read - all @GetMapping public List<Foo> findAll() { return service.findAll(); } // write @PostMapping @ResponseStatus(HttpStatus.CREATED) public Foo create(@RequestBody final Foo resource) { Preconditions.checkNotNull(resource); return service.create(resource); } @PutMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { Preconditions.checkNotNull(resource); RestPreconditions.checkFound(service.findById(resource.getId())); service.update(resource); } @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable("id") final Long id) { service.deleteById(id); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/util/RestPreconditions.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/util/RestPreconditions.java
package com.baeldung.web.util; import org.springframework.http.HttpStatus; import com.baeldung.web.exception.MyResourceNotFoundException; /** * Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown */ public final class RestPreconditions { private RestPreconditions() { throw new AssertionError(); } // API /** * Check if some value was found, otherwise throw exception. * * @param expression * has value true if found, otherwise false * @throws MyResourceNotFoundException * if expression is false, means value not found. */ public static void checkFound(final boolean expression) { if (!expression) { throw new MyResourceNotFoundException(); } } /** * Check if some value was found, otherwise throw exception. * * @param expression * has value true if found, otherwise false * @throws MyResourceNotFoundException * if expression is false, means value not found. */ public static <T> T checkFound(final T resource) { if (resource == null) { throw new MyResourceNotFoundException(); } return resource; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java
package com.baeldung.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/BadRequestException.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/BadRequestException.java
package com.baeldung.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST) public class BadRequestException extends RuntimeException { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
spring-web-modules/spring-boot-rest-simple/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
package com.baeldung.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public final class MyResourceNotFoundException extends RuntimeException { public MyResourceNotFoundException() { super(); } public MyResourceNotFoundException(final String message, final Throwable cause) { super(message, cause); } public MyResourceNotFoundException(final String message) { super(message); } public MyResourceNotFoundException(final Throwable cause) { super(cause); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/SpringContextTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/SpringContextTest.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 = Application.class) public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/repository/BookRepositoryUnitTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/repository/BookRepositoryUnitTest.java
package com.baeldung.repository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import com.baeldung.web.dto.Book; public class BookRepositoryUnitTest { private BookRepository repository; @Before public void setUp() { repository = new BookRepository(); } @Test public void givenNoBooks_WhenFindById_ThenReturnEmptyOptional() { assertFalse(repository.findById(1).isPresent()); } @Test public void givenOneMatchingBook_WhenFindById_ThenReturnEmptyOptional() { long id = 1; Book expected = bookWithId(id); repository.add(expected); Optional<Book> found = repository.findById(id); assertTrue(found.isPresent()); assertEquals(expected, found.get()); } private static Book bookWithId(long id) { Book book = new Book(); book.setId(id); return book; } @Test public void givenOneNonMatchingBook_WhenFindById_ThenReturnEmptyOptional() { long id = 1; Book expected = bookWithId(id); repository.add(expected); Optional<Book> found = repository.findById(id + 1); assertFalse(found.isPresent()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/controller/BookControllerIntegrationTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/controller/BookControllerIntegrationTest.java
package com.baeldung.web.controller; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.Application; import com.baeldung.repository.BookRepository; import com.baeldung.web.dto.Book; import com.baeldung.web.error.ApiErrorResponse; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) @WebMvcTest(BookController.class) @ComponentScan(basePackageClasses = Application.class) public class BookControllerIntegrationTest { private static final ObjectMapper MAPPER = new ObjectMapper(); @Autowired private MockMvc mvc; @MockBean private BookRepository repository; @Test public void givenNoExistingBooks_WhenGetBookWithId1_ThenErrorReturned() throws Exception { long id = 1; doReturn(Optional.empty()).when(repository).findById(eq(id)); mvc.perform(get("/api/book/{id}", id)) .andExpect(status().isNotFound()) .andExpect(content().json(MAPPER.writeValueAsString(new ApiErrorResponse("error-0001", "No book found with ID " + id)))); } @Test public void givenMatchingBookExists_WhenGetBookWithId1_ThenBookReturned() throws Exception { long id = 1; Book book = book(id, "foo", "bar"); doReturn(Optional.of(book)).when(repository).findById(eq(id)); mvc.perform(get("/api/book/{id}", id)) .andExpect(status().isOk()) .andExpect(content().json(MAPPER.writeValueAsString(book))); } private static Book book(long id, String title, String author) { Book book = new Book(); book.setId(id); book.setTitle(title); book.setAuthor(author); return book; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java
package com.baeldung.web.controller.mediatypes; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan({ "com.baeldung.web", "com.baeldung.repository" }) public class TestConfig { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java
package com.baeldung.web.util; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; public final class HTTPLinkHeaderUtil { private HTTPLinkHeaderUtil() { throw new AssertionError(); } // /** * ex. <br> * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", <https://api.github.com/users/steveklabnik/gists?page=3>; rel="last" */ public static List<String> extractAllURIs(final String linkHeader) { Preconditions.checkNotNull(linkHeader); final List<String> linkHeaders = Lists.newArrayList(); final String[] links = linkHeader.split(", "); for (final String link : links) { final int positionOfSeparator = link.indexOf(';'); linkHeaders.add(link.substring(1, positionOfSeparator - 1)); } return linkHeaders; } public static String extractURIByRel(final String linkHeader, final String rel) { if (linkHeader == null) { return null; } String uriWithSpecifiedRel = null; final String[] links = linkHeader.split(", "); String linkRelation = null; for (final String link : links) { final int positionOfSeparator = link.indexOf(';'); linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); if (extractTypeOfRelation(linkRelation).equals(rel)) { uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1); break; } } return uriWithSpecifiedRel; } static Object extractTypeOfRelation(final String linkRelation) { final int positionOfEquals = linkRelation.indexOf('='); return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); } /** * ex. <br> * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next" */ public static String extractSingleURI(final String linkHeader) { Preconditions.checkNotNull(linkHeader); final int positionOfSeparator = linkHeader.indexOf(';'); return linkHeader.substring(1, positionOfSeparator - 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-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java
package com.baeldung.web.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import okhttp3.Request; import okhttp3.RequestBody; public class TestRestTemplateBasicLiveTest { private RestTemplate restTemplate; private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos"; private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest"; @Before public void beforeTest() { restTemplate = new RestTemplate(); } // GET @Test public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); restTemplateBuilder.configure(restTemplate); TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); restTemplateBuilder.build(); TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); restTemplateBuilder.configure(restTemplate); TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd"); ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd"). getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. HttpClientOption.ENABLE_COOKIES); ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } // HEAD @Test public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { TestRestTemplate testRestTemplate = new TestRestTemplate(); final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); } // POST @Test public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), "{\"id\":1,\"name\":\"Jim\"}"); final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); } // PUT @Test public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), "{\"id\":1,\"name\":\"Jim\"}"); final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java
package com.baeldung.web.test; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import com.baeldung.web.dto.Foo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.common.base.Charsets; public class RestTemplateBasicLiveTest { private RestTemplate restTemplate; private static final String fooResourceUrl = "http://localhost:8082/spring-rest/foos"; @Before public void beforeTest() { restTemplate = new RestTemplate(); // restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); } // GET @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { final ResponseEntity<Foo> response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { final RestTemplate template = new RestTemplate(); final ResponseEntity<String> response = template.getForEntity(fooResourceUrl + "/1", String.class); final ObjectMapper mapper = new XmlMapper(); final JsonNode root = mapper.readTree(response.getBody()); final JsonNode name = root.path("name"); assertThat(name.asText(), notNullValue()); } @Test public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); assertThat(foo.getName(), notNullValue()); assertThat(foo.getId(), is(1L)); } // HEAD, OPTIONS @Test public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); assertTrue(httpHeaders.getContentType() .includes(MediaType.APPLICATION_JSON)); } // POST @Test public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar")); final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); assertThat(foo, notNullValue()); assertThat(foo.getName(), is("bar")); } @Test public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar")); final URI location = restTemplate.postForLocation(fooResourceUrl, request); assertThat(location, notNullValue()); } @Test public void givenFooService_whenPostResource_thenResourceIsCreated() { final Foo foo = new Foo("bar"); final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); final Foo fooResponse = response.getBody(); assertThat(fooResponse, notNullValue()); assertThat(fooResponse.getName(), is("bar")); } @Test public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); } // PUT @Test public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers); // Create Resource final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); // Update Resource final Foo updatedInstance = new Foo("newName"); updatedInstance.setId(createResponse.getBody() .getId()); final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers); restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); // Check that Resource was updated final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); final Foo foo = updateResponse.getBody(); assertThat(foo.getName(), is(updatedInstance.getName())); } @Test public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers); // Create entity ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); // Update entity final Foo updatedInstance = new Foo("newName"); updatedInstance.setId(response.getBody() .getId()); final String resourceUrl = fooResourceUrl + '/' + response.getBody() .getId(); restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); // Check that entity was updated response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); final Foo foo = response.getBody(); assertThat(foo.getName(), is(updatedInstance.getName())); } // PATCH @Test public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() { final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers); // Create Resource final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); // Update Resource final Foo updatedResource = new Foo("newName"); updatedResource.setId(createResponse.getBody() .getId()); final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers); final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); // Check that Resource was updated final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); final Foo foo = updateResponse.getBody(); assertThat(foo.getName(), is(updatedResource.getName())); } // DELETE @Test public void givenFooService_whenCallDelete_thenEntityIsRemoved() { final Foo foo = new Foo("remove me"); final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); final String entityUrl = fooResourceUrl + "/" + response.getBody() .getId(); restTemplate.delete(entityUrl); try { restTemplate.getForEntity(entityUrl, Foo.class); fail(); } catch (final HttpClientErrorException ex) { assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); } } @Test public void givenFooService_whenFormSubmit_thenResourceIsCreated() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "1"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); final String fooResponse = response.getBody(); assertThat(fooResponse, notNullValue()); assertThat(fooResponse, is("1")); } private HttpHeaders prepareBasicAuthHeaders() { final HttpHeaders headers = new HttpHeaders(); final String encodedLogPass = getBase64EncodedLogPass(); headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); return headers; } private String getBase64EncodedLogPass() { final String logPass = "user1:user1Pass"; final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); return new String(authHeaderBytes, Charsets.US_ASCII); } private RequestCallback requestCallback(final Foo updatedInstance) { return clientHttpRequest -> { final ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); clientHttpRequest.getHeaders() .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); clientHttpRequest.getHeaders() .add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); }; } // Simply setting restTemplate timeout using ClientHttpRequestFactory ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { final int timeout = 5; final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setConnectTimeout(timeout * 1000); return clientHttpRequestFactory; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java
package com.baeldung.web.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import org.junit.Test; import io.restassured.RestAssured; public class RequestMappingLiveTest { private static String BASE_URI = "http://localhost:8082/spring-rest/ex/"; @Test public void givenSimplePath_whenGetFoos_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "foos") .then() .assertThat() .body(equalTo("Simple Get some Foos")); } @Test public void whenPostFoos_thenOk() { RestAssured.given() .accept("text/html") .post(BASE_URI + "foos") .then() .assertThat() .body(equalTo("Post some Foos")); } @Test public void givenOneHeader_whenGetFoos_thenOk() { RestAssured.given() .accept("text/html") .header("key", "val") .get(BASE_URI + "foos") .then() .assertThat() .body(equalTo("Get some Foos with Header")); } @Test public void givenMultipleHeaders_whenGetFoos_thenOk() { RestAssured.given() .accept("text/html") .headers("key1", "val1", "key2", "val2") .get(BASE_URI + "foos") .then() .assertThat() .body(equalTo("Get some Foos with Header")); } @Test public void givenAcceptHeader_whenGetFoos_thenOk() { RestAssured.given() .accept("application/json") .get(BASE_URI + "foos") .then() .assertThat() .body(containsString("Get some Foos with Header New")); } @Test public void givenPathVariable_whenGetFoos_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "foos/1") .then() .assertThat() .body(equalTo("Get a specific Foo with id=1")); } @Test public void givenMultiplePathVariable_whenGetFoos_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "foos/1/bar/2") .then() .assertThat() .body(equalTo("Get a specific Bar with id=2 from a Foo with id=1")); } @Test public void givenPathVariable_whenGetBars_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "bars/1") .then() .assertThat() .body(equalTo("Get a specific Bar with id=1")); } @Test public void givenParams_whenGetBars_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "bars?id=100&second=something") .then() .assertThat() .body(equalTo("Get a specific Bar with id=100")); } @Test public void whenGetFoosOrBars_thenOk() { RestAssured.given() .accept("text/html") .get(BASE_URI + "advanced/foos") .then() .assertThat() .body(equalTo("Advanced - Get some Foos or Bars")); RestAssured.given() .accept("text/html") .get(BASE_URI + "advanced/bars") .then() .assertThat() .body(equalTo("Advanced - Get some Foos or Bars")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java
spring-web-modules/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java
package com.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.baeldung.config.converter.KryoHttpMessageConverter; import com.baeldung.web.dto.Foo; import com.baeldung.web.dto.FooProtos; /** * Integration Test class. Tests methods hits the server's rest services. */ public class SpringHttpMessageConvertersLiveTest { private static String BASE_URI = "http://localhost:8082/spring-rest/"; /** * Without specifying Accept Header, uses the default response from the * server (in this case json) */ @Test public void whenRetrievingAFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); final Foo resource = restTemplate.getForObject(URI, Foo.class, "1"); assertThat(resource, notNullValue()); } @Test public void givenConsumingXml_whenReadingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); final HttpEntity<String> entity = new HttpEntity<String>(headers); final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1"); final Foo resource = response.getBody(); assertThat(resource, notNullValue()); } @Test public void givenConsumingJson_whenReadingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); final HttpEntity<String> entity = new HttpEntity<String>(headers); final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1"); final Foo resource = response.getBody(); assertThat(resource, notNullValue()); } @Test public void givenConsumingXml_whenWritingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); final Foo resource = new Foo(4, "jason"); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType((MediaType.APPLICATION_XML)); final HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers); final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.PUT, entity, Foo.class, resource.getId()); final Foo fooResponse = response.getBody(); Assert.assertEquals(resource.getId(), fooResponse.getId()); } @Test public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter())); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF)); final HttpEntity<String> entity = new HttpEntity<String>(headers); final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1"); final FooProtos.Foo resource = response.getBody(); assertThat(resource, notNullValue()); } @Test public void givenConsumingKryo_whenReadingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); restTemplate.setMessageConverters(Arrays.asList(new KryoHttpMessageConverter())); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(KryoHttpMessageConverter.KRYO)); final HttpEntity<String> entity = new HttpEntity<String>(headers); final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1"); final Foo resource = response.getBody(); assertThat(resource, notNullValue()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/Application.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/Application.java
package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @EnableAutoConfiguration @SpringBootApplication public class Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.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-simple/src/main/java/com/baeldung/apachefileupload/UploadController.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/apachefileupload/UploadController.java
package com.baeldung.apachefileupload; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.List; import org.apache.commons.fileupload2.core.FileItem; import org.apache.commons.fileupload2.core.FileItemInput; import org.apache.commons.fileupload2.core.FileItemInputIterator; import org.apache.commons.fileupload2.core.DiskFileItemFactory; import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; @RestController public class UploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleUpload(HttpServletRequest request) { System.out.println(System.getProperty("java.io.tmpdir")); boolean isMultipart = JakartaServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = DiskFileItemFactory.builder().get(); // Configure a repository (to ensure a secure temp location is used) JakartaServletFileUpload upload = new JakartaServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { try (InputStream uploadedStream = item.getInputStream(); OutputStream out = new FileOutputStream("file.mov");) { IOUtils.copy(uploadedStream, out); out.close(); } } } // Parse the request with Streaming API upload = new JakartaServletFileUpload(); FileItemInputIterator iterStream = upload.getItemIterator(request); while (iterStream.hasNext()) { FileItemInput item = iterStream.next(); String name = item.getFieldName(); InputStream stream = item.getInputStream(); if (!item.isFormField()) { //Process the InputStream } else { //process form fields String formFieldValue = IOUtils.toString(stream, StandardCharsets.UTF_8); } } return "success!"; } catch (IOException ex) { return "failed: " + ex.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-simple/src/main/java/com/baeldung/repository/BookRepository.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/repository/BookRepository.java
package com.baeldung.repository; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Repository; import com.baeldung.web.dto.Book; @Repository public class BookRepository { private List<Book> books = new ArrayList<>(); public Optional<Book> findById(long id) { return books.stream() .filter(book -> book.getId() == id) .findFirst(); } public void add(Book book) { books.add(book); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java
spring-web-modules/spring-rest-simple/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.StringHttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; 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 com.baeldung.config.converter.KryoHttpMessageConverter; 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.web", "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")); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true) .build())); messageConverters.add(createXmlHttpMessageConverter()); // messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new ProtobufHttpMessageConverter()); messageConverters.add(new KryoHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); } private HttpMessageConverter<Object> createXmlHttpMessageConverter() { final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); xmlConverter.setMarshaller(xstreamMarshaller); xmlConverter.setUnmarshaller(xstreamMarshaller); return xmlConverter; } @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-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java
package com.baeldung.config.converter; import java.io.IOException; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import com.baeldung.web.dto.Foo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** * An {@code HttpMessageConverter} that can read and write Kryo messages. */ public class KryoHttpMessageConverter extends AbstractHttpMessageConverter<Object> { public static final MediaType KRYO = new MediaType("application", "x-kryo"); private static final ThreadLocal<Kryo> kryoThreadLocal = new ThreadLocal<Kryo>() { @Override protected Kryo initialValue() { final Kryo kryo = new Kryo(); kryo.register(Foo.class, 1); return kryo; } }; public KryoHttpMessageConverter() { super(KRYO); } @Override protected boolean supports(final Class<?> clazz) { return Object.class.isAssignableFrom(clazz); } @Override protected Object readInternal(final Class<? extends Object> clazz, final HttpInputMessage inputMessage) throws IOException { final Input input = new Input(inputMessage.getBody()); return kryoThreadLocal.get().readClassAndObject(input); } @Override protected void writeInternal(final Object object, final HttpOutputMessage outputMessage) throws IOException { final Output output = new Output(outputMessage.getBody()); kryoThreadLocal.get().writeClassAndObject(output, object); output.flush(); } @Override protected MediaType getDefaultContentType(final Object object) { return KRYO; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java
package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.web.dto.Foo; import com.baeldung.web.dto.FooProtos; import com.google.common.collect.Lists; @Controller public class FooController { public FooController() { super(); } @RequestMapping(method = RequestMethod.GET, value = "/foos") @ResponseBody public List<Foo> findListOfFoo() { return Lists.newArrayList(new Foo(1, randomAlphabetic(4))); } // API - read @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo(id, randomAlphabetic(4)); } // API - write @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo patchFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.POST, value = "/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo postFoo(@RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.HEAD, value = "/foos") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo headFoo() { return new Foo(1, randomAlphabetic(4)); } @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" }) @ResponseBody public FooProtos.Foo findProtoById(@PathVariable final long id) { return FooProtos.Foo.newBuilder() .setId(1) .setName("Foo Name") .build(); } @RequestMapping(method = RequestMethod.POST, value = "/foos/new") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo createFoo(@RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public long deleteFoo(@PathVariable final long id) { return id; } @RequestMapping(method = RequestMethod.POST, value = "/foos/form") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public String submitFoo(@RequestParam("id") String id) { return id; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/ApiExceptionHandler.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/ApiExceptionHandler.java
package com.baeldung.web.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.baeldung.web.error.ApiErrorResponse; import com.baeldung.web.error.BookNotFoundException; @RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(BookNotFoundException.class) public ResponseEntity<ApiErrorResponse> handleApiException( BookNotFoundException ex) { ApiErrorResponse response = new ApiErrorResponse("error-0001", "No book found with ID " + ex.getId()); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/BookController.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/controller/BookController.java
package com.baeldung.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.baeldung.repository.BookRepository; import com.baeldung.web.dto.Book; import com.baeldung.web.error.BookNotFoundException; @RestController @RequestMapping("/api/book") public class BookController { @Autowired private BookRepository repository; @GetMapping("/{id}") public Book findById(@PathVariable long id) { return repository.findById(id) .orElseThrow(() -> new BookNotFoundException(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-simple/src/main/java/com/baeldung/web/dto/FooProtos.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: FooProtos.proto package com.baeldung.web.dto; public final class FooProtos { private FooProtos() { } public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { } public interface FooOrBuilder extends // @@protoc_insertion_point(interface_extends:baeldung.Foo) com.google.protobuf.MessageOrBuilder { /** * <code>required int64 id = 1;</code> */ boolean hasId(); /** * <code>required int64 id = 1;</code> */ long getId(); /** * <code>required string name = 2;</code> */ boolean hasName(); /** * <code>required string name = 2;</code> */ java.lang.String getName(); /** * <code>required string name = 2;</code> */ com.google.protobuf.ByteString getNameBytes(); } /** * Protobuf type {@code baeldung.Foo} */ public static final class Foo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:baeldung.Foo) FooOrBuilder { // Use Foo.newBuilder() to construct. private Foo(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Foo defaultInstance; public static Foo getDefaultInstance() { return defaultInstance; } public Foo getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Foo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; id_ = input.readInt64(); break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; name_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } public static com.google.protobuf.Parser<Foo> PARSER = new com.google.protobuf.AbstractParser<Foo>() { public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Foo(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Foo> getParserForType() { return PARSER; } private int bitField0_; public static final int ID_FIELD_NUMBER = 1; private long id_; /** * <code>required int64 id = 1;</code> */ public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int64 id = 1;</code> */ public long getId() { return id_; } public static final int NAME_FIELD_NUMBER = 2; private java.lang.Object name_; /** * <code>required string name = 2;</code> */ public boolean hasName() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>required string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { id_ = 0L; name_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasId()) { memoizedIsInitialized = 0; return false; } if (!hasName()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt64(1, id_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getNameBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.baeldung.web.dto.FooProtos.Foo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code baeldung.Foo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:baeldung.Foo) com.baeldung.web.dto.FooProtos.FooOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } // Construct using com.baeldung.web.dto.FooProtos.Foo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); id_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); name_ = ""; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } public com.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { return com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); } public com.baeldung.web.dto.FooProtos.Foo build() { com.baeldung.web.dto.FooProtos.Foo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.baeldung.web.dto.FooProtos.Foo buildPartial() { com.baeldung.web.dto.FooProtos.Foo result = new com.baeldung.web.dto.FooProtos.Foo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.id_ = id_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.name_ = name_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.baeldung.web.dto.FooProtos.Foo) { return mergeFrom((com.baeldung.web.dto.FooProtos.Foo) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.baeldung.web.dto.FooProtos.Foo other) { if (other == com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; if (other.hasId()) { setId(other.getId()); } if (other.hasName()) { bitField0_ |= 0x00000002; name_ = other.name_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasId()) { return false; } if (!hasName()) { return false; } return true; } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.baeldung.web.dto.FooProtos.Foo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long id_; /** * <code>required int64 id = 1;</code> */ public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int64 id = 1;</code> */ public long getId() { return id_; } /** * <code>required int64 id = 1;</code> */ public Builder setId(long value) { bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } /** * <code>required int64 id = 1;</code> */ public Builder clearId() { bitField0_ = (bitField0_ & ~0x00000001); id_ = 0L; onChanged(); return this; } private java.lang.Object name_ = ""; /** * <code>required string name = 2;</code> */ public boolean hasName() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string name = 2;</code> */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; name_ = value; onChanged(); return this; } /** * <code>required string name = 2;</code> */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000002); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>required string name = 2;</code> */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; name_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:baeldung.Foo) } static { defaultInstance = new Foo(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:baeldung.Foo) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024com.baeldung.web" + ".dtoB\tFooProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", }); } // @@protoc_insertion_point(outer_class_scope) }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java
spring-web-modules/spring-rest-simple/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-simple/src/main/java/com/baeldung/web/dto/Book.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/dto/Book.java
package com.baeldung.web.dto; public class Book { private long id; private String title; private String author; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String 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-simple/src/main/java/com/baeldung/web/dto/Bazz.java
spring-web-modules/spring-rest-simple/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-simple/src/main/java/com/baeldung/web/util/LinkUtil.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java
package com.baeldung.web.util; import jakarta.servlet.http.HttpServletResponse; /** * Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object */ public final class LinkUtil { public static final String REL_COLLECTION = "collection"; public static final String REL_NEXT = "next"; public static final String REL_PREV = "prev"; public static final String REL_FIRST = "first"; public static final String REL_LAST = "last"; private LinkUtil() { throw new AssertionError(); } // /** * Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user * * @param uri * the base uri * @param rel * the relative path * * @return the complete url */ public static String createLinkHeader(final String uri, final String rel) { return "<" + uri + ">; rel=\"" + rel + "\""; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/error/BookNotFoundException.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/error/BookNotFoundException.java
package com.baeldung.web.error; @SuppressWarnings("serial") public class BookNotFoundException extends RuntimeException { private long id; public BookNotFoundException(long id) { this.id = id; } public long getId() { return id; } public void setId(long id) { this.id = 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-simple/src/main/java/com/baeldung/web/error/ApiErrorResponse.java
spring-web-modules/spring-rest-simple/src/main/java/com/baeldung/web/error/ApiErrorResponse.java
package com.baeldung.web.error; public class ApiErrorResponse { private String error; private String message; public ApiErrorResponse(String error, String message) { super(); this.error = error; this.message = message; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = 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-query-language/src/test/java/com/baeldung/SpringContextTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.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; import com.baeldung.spring.Application; /** * Note: In the IDE, remember to generate query type classes before running the Integration Test (e.g. in Eclipse right-click on the project > Run As > Maven generate sources) * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java
package com.baeldung.persistence.query; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIn.isIn; import static org.hamcrest.core.IsNot.not; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.dao.IUserDAO; import com.baeldung.persistence.model.User; import com.baeldung.spring.PersistenceConfig; import com.baeldung.web.util.SearchCriteria; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback public class JPACriteriaQueryIntegrationTest { @Autowired private IUserDAO userApi; private User userJohn; private User userTom; @Before public void init() { userJohn = new User(); userJohn.setFirstName("john"); userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); userApi.save(userJohn); userTom = new User(); userTom.setFirstName("tom"); userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); userApi.save(userTom); } @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); params.add(new SearchCriteria("firstName", ":", "john")); params.add(new SearchCriteria("lastName", ":", "doe")); final List<User> results = userApi.searchUser(params); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); params.add(new SearchCriteria("lastName", ":", "doe")); final List<User> results = userApi.searchUser(params); assertThat(userJohn, isIn(results)); assertThat(userTom, isIn(results)); } @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); params.add(new SearchCriteria("lastName", ":", "doe")); params.add(new SearchCriteria("age", ">", "25")); final List<User> results = userApi.searchUser(params); assertThat(userTom, isIn(results)); assertThat(userJohn, not(isIn(results))); } @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); params.add(new SearchCriteria("firstName", ":", "adam")); params.add(new SearchCriteria("lastName", ":", "fox")); final List<User> results = userApi.searchUser(params); assertThat(userJohn, not(isIn(results))); assertThat(userTom, not(isIn(results))); } @Test public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); params.add(new SearchCriteria("firstName", ":", "jo")); final List<User> results = userApi.searchUser(params); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPASpecificationLiveTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPASpecificationLiveTest.java
package com.baeldung.persistence.query; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; import com.baeldung.persistence.model.User; //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(classes = { ConfigTest.class, // PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class JPASpecificationLiveTest { // @Autowired // private UserRepository repository; private User userJohn; private User userTom; private final String URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/spec?search="; @Before public void init() { userJohn = new User(); userJohn.setFirstName("john"); userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); // repository.save(userJohn); userTom = new User(); userTom.setFirstName("tom"); userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); // repository.save(userTom); } private final String EURL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/espec?search="; @Test public void givenFirstOrLastName_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(EURL_PREFIX + "firstName:john,'lastName:doe"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertTrue(result.contains(userTom.getEmail())); } @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "firstName:john,lastName:doe"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertFalse(result.contains(userTom.getEmail())); } @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "firstName!john"); final String result = response.body() .asString(); assertTrue(result.contains(userTom.getEmail())); assertFalse(result.contains(userJohn.getEmail())); } @Test public void givenMinAge_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "age>25"); final String result = response.body() .asString(); assertTrue(result.contains(userTom.getEmail())); assertFalse(result.contains(userJohn.getEmail())); } @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "firstName:jo*"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertFalse(result.contains(userTom.getEmail())); } @Test public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "firstName:*n"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertFalse(result.contains(userTom.getEmail())); } @Test public void givenFirstNameSubstring_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "firstName:*oh*"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertFalse(result.contains(userTom.getEmail())); } @Test public void givenAgeRange_whenGettingListOfUsers_thenCorrect() { final Response response = RestAssured.get(URL_PREFIX + "age>20,age<25"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertFalse(result.contains(userTom.getEmail())); } private final String ADV_URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/spec/adv?search="; @Test public void givenFirstOrLastName_whenGettingAdvListOfUsers_thenCorrect() { final Response response = RestAssured.get(ADV_URL_PREFIX + "firstName:john OR lastName:doe"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); assertTrue(result.contains(userTom.getEmail())); } @Test public void givenFirstOrFirstNameAndAge_whenGettingAdvListOfUsers_thenCorrect() { final Response response = RestAssured.get(ADV_URL_PREFIX + "( firstName:john OR firstName:tom ) AND age>22"); final String result = response.body() .asString(); assertFalse(result.contains(userJohn.getEmail())); assertTrue(result.contains(userTom.getEmail())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPAQuerydslIntegrationTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPAQuerydslIntegrationTest.java
package com.baeldung.persistence.query; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsEmptyIterable.emptyIterable; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.core.IsNot.not; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.dao.MyUserPredicatesBuilder; import com.baeldung.persistence.dao.MyUserRepository; import com.baeldung.persistence.model.MyUser; import com.baeldung.spring.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback public class JPAQuerydslIntegrationTest { @Autowired private MyUserRepository repo; private MyUser userJohn; private MyUser userTom; @Before public void init() { userJohn = new MyUser(); userJohn.setFirstName("john"); userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repo.save(userJohn); userTom = new MyUser(); userTom.setFirstName("tom"); userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repo.save(userTom); } @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe"); final Iterable<MyUser> results = repo.findAll(builder.build()); assertThat(results, containsInAnyOrder(userJohn, userTom)); } @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "john").with("lastName", ":", "doe"); final Iterable<MyUser> results = repo.findAll(builder.build()); assertThat(results, contains(userJohn)); assertThat(results, not(contains(userTom))); } @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe").with("age", ">", "25"); final Iterable<MyUser> results = repo.findAll(builder.build()); assertThat(results, contains(userTom)); assertThat(results, not(contains(userJohn))); } @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "adam").with("lastName", ":", "fox"); final Iterable<MyUser> results = repo.findAll(builder.build()); assertThat(results, emptyIterable()); } @Test public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "jo"); final Iterable<MyUser> results = repo.findAll(builder.build()); assertThat(results, contains(userJohn)); assertThat(results, not(contains(userTom))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPASpecificationIntegrationTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/JPASpecificationIntegrationTest.java
package com.baeldung.persistence.query; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.dao.GenericSpecificationsBuilder; import com.baeldung.persistence.dao.UserRepository; import com.baeldung.persistence.dao.UserSpecification; import com.baeldung.persistence.dao.UserSpecificationsBuilder; import com.baeldung.persistence.model.User; import com.baeldung.spring.PersistenceConfig; import com.baeldung.web.util.CriteriaParser; import com.baeldung.web.util.SearchOperation; import com.baeldung.web.util.SpecSearchCriteria; import java.util.List; import java.util.function.Function; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsIn.isIn; import static org.hamcrest.core.IsNot.not; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback public class JPASpecificationIntegrationTest { @Autowired private UserRepository repository; private User userJohn; private User userTom; private User userPercy; @Before public void init() { userJohn = new User(); userJohn.setFirstName("john"); userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repository.save(userJohn); userTom = new User(); userTom.setFirstName("tom"); userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repository.save(userTom); userPercy = new User(); userPercy.setFirstName("percy"); userPercy.setLastName("blackney"); userPercy.setEmail("percy@blackney.com"); userPercy.setAge(30); repository.save(userPercy); } @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "john")); final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("lastName", SearchOperation.EQUALITY, "doe")); final List<User> results = repository.findAll(Specification .where(spec) .and(spec1)); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenFirstOrLastName_whenGettingListOfUsers_thenCorrect() { UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); SpecSearchCriteria spec = new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "john"); SpecSearchCriteria spec1 = new SpecSearchCriteria("'","lastName", SearchOperation.EQUALITY, "doe"); List<User> results = repository.findAll(builder .with(spec) .with(spec1) .build()); assertThat(results, hasSize(2)); assertThat(userJohn, isIn(results)); assertThat(userTom, isIn(results)); } @Test public void givenFirstOrLastNameAndAgeGenericBuilder_whenGettingListOfUsers_thenCorrect() { GenericSpecificationsBuilder<User> builder = new GenericSpecificationsBuilder<>(); Function<SpecSearchCriteria, Specification<User>> converter = UserSpecification::new; CriteriaParser parser=new CriteriaParser(); List<User> results = repository.findAll(builder.build(parser.parse("( lastName:doe OR firstName:john ) AND age:22"), converter)); assertThat(results, hasSize(1)); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenFirstOrLastNameGenericBuilder_whenGettingListOfUsers_thenCorrect() { GenericSpecificationsBuilder<User> builder = new GenericSpecificationsBuilder<>(); Function<SpecSearchCriteria, Specification<User>> converter = UserSpecification::new; builder.with("firstName", ":", "john", null, null); builder.with("'", "lastName", ":", "doe", null, null); List<User> results = repository.findAll(builder.build(converter)); assertThat(results, hasSize(2)); assertThat(userJohn, isIn(results)); assertThat(userTom, isIn(results)); } @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.NEGATION, "john")); final List<User> results = repository.findAll(Specification.where(spec)); assertThat(userTom, isIn(results)); assertThat(userJohn, not(isIn(results))); } @Test public void givenMinAge_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("age", SearchOperation.GREATER_THAN, "25")); final List<User> results = repository.findAll(Specification.where(spec)); assertThat(userTom, isIn(results)); assertThat(userJohn, not(isIn(results))); } @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.STARTS_WITH, "jo")); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.ENDS_WITH, "n")); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenFirstNameSubstring_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.CONTAINS, "oh")); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenAgeRange_whenGettingListOfUsers_thenCorrect() { final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("age", SearchOperation.GREATER_THAN, "20")); final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("age", SearchOperation.LESS_THAN, "25")); final List<User> results = repository.findAll(Specification .where(spec) .and(spec1)); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/RsqlIntegrationTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/persistence/query/RsqlIntegrationTest.java
package com.baeldung.persistence.query; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIn.isIn; import static org.hamcrest.core.IsNot.not; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.dao.UserRepository; import com.baeldung.persistence.dao.rsql.CustomRsqlVisitor; import com.baeldung.persistence.model.User; import com.baeldung.spring.PersistenceConfig; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback public class RsqlIntegrationTest { @Autowired private UserRepository repository; private User userJohn; private User userTom; @Before public void init() { userJohn = new User(); userJohn.setFirstName("john"); userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repository.save(userJohn); userTom = new User(); userTom.setFirstName("tom"); userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repository.save(userTom); } @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final Node rootNode = new RSQLParser().parse("firstName==john;lastName==doe"); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { final Node rootNode = new RSQLParser().parse("firstName!=john"); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final List<User> results = repository.findAll(spec); assertThat(userTom, isIn(results)); assertThat(userJohn, not(isIn(results))); } @Test public void givenMinAge_whenGettingListOfUsers_thenCorrect() { final Node rootNode = new RSQLParser().parse("age>25"); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final List<User> results = repository.findAll(spec); assertThat(userTom, isIn(results)); assertThat(userJohn, not(isIn(results))); } @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { final Node rootNode = new RSQLParser().parse("firstName==jo*"); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } @Test public void givenListOfFirstName_whenGettingListOfUsers_thenCorrect() { final Node rootNode = new RSQLParser().parse("firstName=in=(john,jack)"); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final List<User> results = repository.findAll(spec); assertThat(userJohn, isIn(results)); assertThat(userTom, not(isIn(results))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/web/MyUserLiveTest.java
spring-web-modules/spring-rest-query-language/src/test/java/com/baeldung/web/MyUserLiveTest.java
package com.baeldung.web; import static org.junit.Assert.assertEquals; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; import com.baeldung.persistence.model.MyUser; @ActiveProfiles("test") public class MyUserLiveTest { private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); private String URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/api/myusers"; @Test public void whenGettingListOfUsers_thenCorrect() { final Response response = givenAuth().get(URL_PREFIX); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenFirstName_whenGettingListOfUsers_thenCorrect() { final Response response = givenAuth().get(URL_PREFIX + "?firstName=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 1); assertEquals(result[0].getEmail(), userJohn.getEmail()); } @Test public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() { final Response response = givenAuth().get(URL_PREFIX + "?lastName=do"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenEmail_whenGettingListOfUsers_thenIgnored() { final Response response = givenAuth().get(URL_PREFIX + "?email=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } private RequestSpecification givenAuth() { return RestAssured.given().auth().preemptive().basic("user1", "user1Pass"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserRepository.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserRepository.java
package com.baeldung.persistence.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.baeldung.persistence.model.User; public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<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-query-language/src/main/java/com/baeldung/persistence/dao/UserSpecification.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserSpecification.java
package com.baeldung.persistence.dao; import org.springframework.data.jpa.domain.Specification; import com.baeldung.persistence.model.User; import com.baeldung.web.util.SpecSearchCriteria; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; public class UserSpecification implements Specification<User> { private SpecSearchCriteria criteria; public UserSpecification(final SpecSearchCriteria criteria) { super(); this.criteria = criteria; } public SpecSearchCriteria getCriteria() { return criteria; } @Override public Predicate toPredicate(final Root<User> root, final CriteriaQuery<?> query, final CriteriaBuilder builder) { switch (criteria.getOperation()) { case EQUALITY: return builder.equal(root.get(criteria.getKey()), criteria.getValue()); case NEGATION: return builder.notEqual(root.get(criteria.getKey()), criteria.getValue()); case GREATER_THAN: return builder.greaterThan(root.get(criteria.getKey()), criteria.getValue().toString()); case LESS_THAN: return builder.lessThan(root.get(criteria.getKey()), criteria.getValue().toString()); case LIKE: return builder.like(root.get(criteria.getKey()), criteria.getValue().toString()); case STARTS_WITH: return builder.like(root.get(criteria.getKey()), criteria.getValue() + "%"); case ENDS_WITH: return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue()); case CONTAINS: return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue() + "%"); default: return 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-query-language/src/main/java/com/baeldung/persistence/dao/MyUserPredicatesBuilder.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/MyUserPredicatesBuilder.java
package com.baeldung.persistence.dao; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import com.baeldung.web.util.SearchCriteria; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; public final class MyUserPredicatesBuilder { private final List<SearchCriteria> params; public MyUserPredicatesBuilder() { params = new ArrayList<>(); } public MyUserPredicatesBuilder with(final String key, final String operation, final Object value) { params.add(new SearchCriteria(key, operation, value)); return this; } public BooleanExpression build() { if (params.size() == 0) { return null; } final List<BooleanExpression> predicates = params.stream().map(param -> { MyUserPredicate predicate = new MyUserPredicate(param); return predicate.getPredicate(); }).filter(Objects::nonNull).collect(Collectors.toList()); BooleanExpression result = Expressions.asBoolean(true).isTrue(); for (BooleanExpression predicate : predicates) { result = result.and(predicate); } return result; } static class BooleanExpressionWrapper { private BooleanExpression result; public BooleanExpressionWrapper(final BooleanExpression result) { super(); this.result = result; } public BooleanExpression getResult() { return result; } public void setResult(BooleanExpression result) { this.result = result; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserSpecificationsBuilder.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserSpecificationsBuilder.java
package com.baeldung.persistence.dao; import java.util.ArrayList; import java.util.List; import org.springframework.data.jpa.domain.Specification; import com.baeldung.persistence.model.User; import com.baeldung.web.util.SearchOperation; import com.baeldung.web.util.SpecSearchCriteria; public final class UserSpecificationsBuilder { private final List<SpecSearchCriteria> params; public UserSpecificationsBuilder() { params = new ArrayList<>(); } // API public final UserSpecificationsBuilder with(final String key, final String operation, final Object value, final String prefix, final String suffix) { return with(null, key, operation, value, prefix, suffix); } public final UserSpecificationsBuilder with(final String orPredicate, final String key, final String operation, final Object value, final String prefix, final String suffix) { SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0)); if (op != null) { if (op == SearchOperation.EQUALITY) { // the operation may be complex operation final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX); final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX); if (startWithAsterisk && endWithAsterisk) { op = SearchOperation.CONTAINS; } else if (startWithAsterisk) { op = SearchOperation.ENDS_WITH; } else if (endWithAsterisk) { op = SearchOperation.STARTS_WITH; } } params.add(new SpecSearchCriteria(orPredicate, key, op, value)); } return this; } public Specification<User> build() { if (params.size() == 0) return null; Specification<User> result = new UserSpecification(params.get(0)); for (int i = 1; i < params.size(); i++) { result = params.get(i).isOrPredicate() ? Specification.where(result).or(new UserSpecification(params.get(i))) : Specification.where(result).and(new UserSpecification(params.get(i))); } return result; } public final UserSpecificationsBuilder with(UserSpecification spec) { params.add(spec.getCriteria()); return this; } public final UserSpecificationsBuilder with(SpecSearchCriteria criteria) { params.add(criteria); return this; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserDAO.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserDAO.java
package com.baeldung.persistence.dao; import java.util.List; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import com.baeldung.persistence.model.User; import com.baeldung.web.util.SearchCriteria; @Repository public class UserDAO implements IUserDAO { @PersistenceContext private EntityManager entityManager; @Override public List<User> searchUser(final List<SearchCriteria> params) { final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery<User> query = builder.createQuery(User.class); final Root r = query.from(User.class); Predicate predicate = builder.conjunction(); UserSearchQueryCriteriaConsumer searchConsumer = new UserSearchQueryCriteriaConsumer(predicate, builder, r); params.stream().forEach(searchConsumer); predicate = searchConsumer.getPredicate(); query.where(predicate); return entityManager.createQuery(query).getResultList(); } @Override public void save(final User entity) { entityManager.persist(entity); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserSearchQueryCriteriaConsumer.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/UserSearchQueryCriteriaConsumer.java
package com.baeldung.persistence.dao; import java.util.function.Consumer; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import com.baeldung.web.util.SearchCriteria; public class UserSearchQueryCriteriaConsumer implements Consumer<SearchCriteria>{ private Predicate predicate; private CriteriaBuilder builder; private Root r; public UserSearchQueryCriteriaConsumer(Predicate predicate, CriteriaBuilder builder, Root r) { super(); this.predicate = predicate; this.builder = builder; this.r= r; } @Override public void accept(SearchCriteria param) { if (param.getOperation().equalsIgnoreCase(">")) { predicate = builder.and(predicate, builder.greaterThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); } else if (param.getOperation().equalsIgnoreCase("<")) { predicate = builder.and(predicate, builder.lessThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); } else if (param.getOperation().equalsIgnoreCase(":")) { if (r.get(param.getKey()).getJavaType() == String.class) { predicate = builder.and(predicate, builder.like(r.get(param.getKey()), "%" + param.getValue() + "%")); } else { predicate = builder.and(predicate, builder.equal(r.get(param.getKey()), param.getValue())); } } } public Predicate getPredicate() { return predicate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/IUserDAO.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/IUserDAO.java
package com.baeldung.persistence.dao; import java.util.List; import com.baeldung.persistence.model.User; import com.baeldung.web.util.SearchCriteria; public interface IUserDAO { List<User> searchUser(List<SearchCriteria> params); void save(User entity); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/GenericSpecificationsBuilder.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/GenericSpecificationsBuilder.java
package com.baeldung.persistence.dao; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.data.jpa.domain.Specification; import com.baeldung.web.util.SearchOperation; import com.baeldung.web.util.SpecSearchCriteria; public class GenericSpecificationsBuilder<U> { private final List<SpecSearchCriteria> params; public GenericSpecificationsBuilder() { this.params = new ArrayList<>(); } public final GenericSpecificationsBuilder<U> with(final String key, final String operation, final Object value, final String prefix, final String suffix) { return with(null, key, operation, value, prefix, suffix); } public final GenericSpecificationsBuilder<U> with(final String precedenceIndicator, final String key, final String operation, final Object value, final String prefix, final String suffix) { SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0)); if (op != null) { if (op == SearchOperation.EQUALITY) // the operation may be complex operation { final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX); final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX); if (startWithAsterisk && endWithAsterisk) { op = SearchOperation.CONTAINS; } else if (startWithAsterisk) { op = SearchOperation.ENDS_WITH; } else if (endWithAsterisk) { op = SearchOperation.STARTS_WITH; } } params.add(new SpecSearchCriteria(precedenceIndicator, key, op, value)); } return this; } public Specification<U> build(Function<SpecSearchCriteria, Specification<U>> converter) { if (params.size() == 0) { return null; } final List<Specification<U>> specs = params.stream() .map(converter) .collect(Collectors.toCollection(ArrayList::new)); Specification<U> result = specs.get(0); for (int idx = 1; idx < specs.size(); idx++) { result = params.get(idx) .isOrPredicate() ? Specification.where(result) .or(specs.get(idx)) : Specification.where(result) .and(specs.get(idx)); } return result; } public Specification<U> build(Deque<?> postFixedExprStack, Function<SpecSearchCriteria, Specification<U>> converter) { Deque<Specification<U>> specStack = new LinkedList<>(); Collections.reverse((List<?>) postFixedExprStack); while (!postFixedExprStack.isEmpty()) { Object mayBeOperand = postFixedExprStack.pop(); if (!(mayBeOperand instanceof String)) { specStack.push(converter.apply((SpecSearchCriteria) mayBeOperand)); } else { Specification<U> operand1 = specStack.pop(); Specification<U> operand2 = specStack.pop(); if (mayBeOperand.equals(SearchOperation.AND_OPERATOR)) specStack.push(Specification.where(operand1) .and(operand2)); else if (mayBeOperand.equals(SearchOperation.OR_OPERATOR)) specStack.push(Specification.where(operand1) .or(operand2)); } } return specStack.pop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/MyUserRepository.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/MyUserRepository.java
package com.baeldung.persistence.dao; import com.baeldung.persistence.model.QMyUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.querydsl.binding.SingleValueBinding; import com.baeldung.persistence.model.MyUser; import com.querydsl.core.types.dsl.StringExpression; import com.querydsl.core.types.dsl.StringPath; public interface MyUserRepository extends JpaRepository<MyUser, Long>, QuerydslPredicateExecutor<MyUser>, QuerydslBinderCustomizer<QMyUser> { @Override default public void customize(final QuerydslBindings bindings, final QMyUser root) { bindings.bind(String.class) .first((SingleValueBinding<StringPath, String>) StringExpression::containsIgnoreCase); bindings.excluding(root.email); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/MyUserPredicate.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/MyUserPredicate.java
package com.baeldung.persistence.dao; import com.baeldung.persistence.model.MyUser; import com.baeldung.web.util.SearchCriteria; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.NumberPath; import com.querydsl.core.types.dsl.PathBuilder; import com.querydsl.core.types.dsl.StringPath; public class MyUserPredicate { private SearchCriteria criteria; public MyUserPredicate(final SearchCriteria criteria) { this.criteria = criteria; } public BooleanExpression getPredicate() { final PathBuilder<MyUser> entityPath = new PathBuilder<>(MyUser.class, "myUser"); if (isNumeric(criteria.getValue().toString())) { final NumberPath<Integer> path = entityPath.getNumber(criteria.getKey(), Integer.class); final int value = Integer.parseInt(criteria.getValue().toString()); switch (criteria.getOperation()) { case ":": return path.eq(value); case ">": return path.goe(value); case "<": return path.loe(value); } } else { final StringPath path = entityPath.getString(criteria.getKey()); if (criteria.getOperation().equalsIgnoreCase(":")) { return path.containsIgnoreCase(criteria.getValue().toString()); } } return null; } public SearchCriteria getCriteria() { return criteria; } public void setCriteria(final SearchCriteria criteria) { this.criteria = criteria; } public static boolean isNumeric(final String str) { try { Integer.parseInt(str); } catch (final NumberFormatException e) { return false; } return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java
package com.baeldung.persistence.dao.rsql; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.AndNode; import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.OrNode; import cz.jirutka.rsql.parser.ast.RSQLVisitor; public class CustomRsqlVisitor<T> implements RSQLVisitor<Specification<T>, Void> { private GenericRsqlSpecBuilder<T> builder; public CustomRsqlVisitor() { builder = new GenericRsqlSpecBuilder<T>(); } @Override public Specification<T> visit(final AndNode node, final Void param) { return builder.createSpecification(node); } @Override public Specification<T> visit(final OrNode node, final Void param) { return builder.createSpecification(node); } @Override public Specification<T> visit(final ComparisonNode node, final Void params) { return builder.createSpecification(node); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java
package com.baeldung.persistence.dao.rsql; import java.util.List; import java.util.stream.Collectors; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.ComparisonOperator; public class GenericRsqlSpecification<T> implements Specification<T> { private String property; private ComparisonOperator operator; private List<String> arguments; public GenericRsqlSpecification(final String property, final ComparisonOperator operator, final List<String> arguments) { super(); this.property = property; this.operator = operator; this.arguments = arguments; } @Override public Predicate toPredicate(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder builder) { final List<Object> args = castArguments(root); final Object argument = args.get(0); switch (RsqlSearchOperation.getSimpleOperator(operator)) { case EQUAL: { if (argument instanceof String) { return builder.like(root.get(property), argument.toString().replace('*', '%')); } else if (argument == null) { return builder.isNull(root.get(property)); } else { return builder.equal(root.get(property), argument); } } case NOT_EQUAL: { if (argument instanceof String) { return builder.notLike(root.<String> get(property), argument.toString().replace('*', '%')); } else if (argument == null) { return builder.isNotNull(root.get(property)); } else { return builder.notEqual(root.get(property), argument); } } case GREATER_THAN: { return builder.greaterThan(root.<String> get(property), argument.toString()); } case GREATER_THAN_OR_EQUAL: { return builder.greaterThanOrEqualTo(root.<String> get(property), argument.toString()); } case LESS_THAN: { return builder.lessThan(root.<String> get(property), argument.toString()); } case LESS_THAN_OR_EQUAL: { return builder.lessThanOrEqualTo(root.<String> get(property), argument.toString()); } case IN: return root.get(property).in(args); case NOT_IN: return builder.not(root.get(property).in(args)); } return null; } // === private private List<Object> castArguments(final Root<T> root) { final Class<? extends Object> type = root.get(property).getJavaType(); final List<Object> args = arguments.stream().map(arg -> { if (type.equals(Integer.class)) { return Integer.parseInt(arg); } else if (type.equals(Long.class)) { return Long.parseLong(arg); } else { return arg; } }).collect(Collectors.toList()); return 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-query-language/src/main/java/com/baeldung/persistence/dao/rsql/RsqlSearchOperation.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/RsqlSearchOperation.java
package com.baeldung.persistence.dao.rsql; import cz.jirutka.rsql.parser.ast.ComparisonOperator; import cz.jirutka.rsql.parser.ast.RSQLOperators; import java.util.Arrays; public enum RsqlSearchOperation { EQUAL(RSQLOperators.EQUAL), NOT_EQUAL(RSQLOperators.NOT_EQUAL), GREATER_THAN(RSQLOperators.GREATER_THAN), GREATER_THAN_OR_EQUAL(RSQLOperators.GREATER_THAN_OR_EQUAL), LESS_THAN(RSQLOperators.LESS_THAN), LESS_THAN_OR_EQUAL( RSQLOperators.LESS_THAN_OR_EQUAL), IN(RSQLOperators.IN), NOT_IN(RSQLOperators.NOT_IN); private ComparisonOperator operator; RsqlSearchOperation(final ComparisonOperator operator) { this.operator = operator; } public static RsqlSearchOperation getSimpleOperator(final ComparisonOperator operator) { return Arrays.stream(values()) .filter(operation -> operation.getOperator() == operator) .findAny().orElse(null); } public ComparisonOperator getOperator() { return operator; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java
package com.baeldung.persistence.dao.rsql; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.LogicalNode; import cz.jirutka.rsql.parser.ast.LogicalOperator; import cz.jirutka.rsql.parser.ast.Node; public class GenericRsqlSpecBuilder<T> { public Specification<T> createSpecification(final Node node) { if (node instanceof LogicalNode) { return createSpecification((LogicalNode) node); } if (node instanceof ComparisonNode) { return createSpecification((ComparisonNode) node); } return null; } public Specification<T> createSpecification(final LogicalNode logicalNode) { List<Specification<T>> specs = logicalNode.getChildren() .stream() .map(node -> createSpecification(node)) .filter(Objects::nonNull) .collect(Collectors.toList()); Specification<T> result = specs.get(0); if (logicalNode.getOperator() == LogicalOperator.AND) { for (int i = 1; i < specs.size(); i++) { result = Specification.where(result).and(specs.get(i)); } } else if (logicalNode.getOperator() == LogicalOperator.OR) { for (int i = 1; i < specs.size(); i++) { result = Specification.where(result).or(specs.get(i)); } } return result; } public Specification<T> createSpecification(final ComparisonNode comparisonNode) { return Specification.where(new GenericRsqlSpecification<T>(comparisonNode.getSelector(), comparisonNode.getOperator(), comparisonNode.getArguments())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/MyUser.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/MyUser.java
package com.baeldung.persistence.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; // used for Querydsl test @Entity public class MyUser { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private int age; public MyUser() { super(); } public MyUser(final String firstName, final String lastName, final String email, final int age) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.age = age; } // public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MyUser user = (MyUser) obj; if (!email.equals(user.email)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("MyUser [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/User_.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/User_.java
package com.baeldung.persistence.model; import jakarta.persistence.metamodel.SingularAttribute; import jakarta.persistence.metamodel.StaticMetamodel; @StaticMetamodel(User.class) public class User_ { public static volatile SingularAttribute<User, Long> id; public static volatile SingularAttribute<User, String> firstName; public static volatile SingularAttribute<User, String> lastName; public static volatile SingularAttribute<User, Integer> age; public static volatile SingularAttribute<User, String> email; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/User.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/persistence/model/User.java
package com.baeldung.persistence.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private int age; public User() { super(); } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final User user = (User) obj; return email.equals(user.email); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/PersistenceConfig.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/PersistenceConfig.java
package com.baeldung.spring; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "com.baeldung.persistence" }) // @ImportResource("classpath*:springDataPersistenceConfig.xml") @EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao") public class PersistenceConfig { @Autowired private Environment env; public PersistenceConfig() { super(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.set em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/WebConfig.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/WebConfig.java
package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("com.baeldung.web") @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } // API @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/homepage.html"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/Application.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/spring/Application.java
package com.baeldung.spring; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.context.request.RequestContextListener; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java * class to run up a Jetty Server (on http://localhost:8082/spring-rest-query-language) * */ @EnableScheduling @EnableAutoConfiguration @ComponentScan("com.baeldung") @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } @Override public void onStartup(ServletContext sc) throws ServletException { // Manages the lifecycle of the root application context sc.addListener(new RequestContextListener()); } public static void main(final String[] args) { SpringApplication.run(Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false