diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java index 624e289812..aa5941c763 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java +++ b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java @@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId getCommitId() { Map result = new HashMap<>(); - result.put("Commit message",commitMessage); + result.put("Commit message", commitMessage); result.put("Commit branch", branch); result.put("Commit id", commitId); return result; diff --git a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java index 284cda5d31..c43b13ea0b 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java @@ -11,8 +11,8 @@ import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration public class WebjarsdemoApplicationTests { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index e16791881e..c0fc1befd3 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -32,13 +32,10 @@ public class CommitIdTest { LOG.info(commitMessage); LOG.info(branch); - assertThat(commitMessage) - .isNotEqualTo("UNKNOWN"); + assertThat(commitMessage).isNotEqualTo("UNKNOWN"); - assertThat(branch) - .isNotEqualTo("UNKNOWN"); + assertThat(branch).isNotEqualTo("UNKNOWN"); - assertThat(commitId) - .isNotEqualTo("UNKNOWN"); + assertThat(commitId).isNotEqualTo("UNKNOWN"); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java index ac7bcd62a9..1255180e44 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java @@ -31,22 +31,15 @@ public class SpringBootApplicationTest { private WebApplicationContext webApplicationContext; private MockMvc mockMvc; - @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), - MediaType.APPLICATION_JSON.getSubtype(), - Charset.forName("utf8")); + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")). - andExpect(MockMvcResultMatchers.status().isOk()). - andExpect(MockMvcResultMatchers.content().contentType(contentType)). - andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java index d36a7906a3..f4ce158661 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java @@ -69,7 +69,6 @@ public class SpringBootMailTest { return wiserMessage.getMimeMessage().getSubject(); } - private SimpleMailMessage composeEmailMessage() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(userTo); diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java index c594610be2..ba0da968ad 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java @@ -30,8 +30,7 @@ public class DetailsServiceClientTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")) - .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index 60548dd6e3..820e7e8004 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -18,9 +18,9 @@ public class SpringDemoApplication extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringDemoApplication.class); } - + @Bean - public RestTemplate getRestTemplate(){ - return new RestTemplate(); + public RestTemplate getRestTemplate() { + return new RestTemplate(); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java index 201b14cf0b..c357ab8596 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java @@ -19,22 +19,27 @@ public class Campus { @Field @NotNull private Point location; - + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Point getLocation() { return location; } + public void setLocation(Point location) { this.location = location; } @@ -42,13 +47,13 @@ public class Campus { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(name != null) { + if (name != null) { hash = hash * 31 + name.hashCode(); } - if(location != null) { + if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; @@ -56,30 +61,33 @@ public class Campus { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } - + @SuppressWarnings("unused") - private Campus() {} - + private Campus() { + } + public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } - + public static class Builder { private String id; private String name; private Point location; - + public static Builder newInstance() { return new Builder(); } - + public Campus build() { return new Campus(this); } @@ -93,7 +101,7 @@ public class Campus { this.name = name; return this; } - + public Builder location(Point location) { this.location = location; return this; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java index 9220e157ed..fd41427d20 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java @@ -24,7 +24,7 @@ public class Person { private DateTime created; @Field private DateTime updated; - + public Person(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; @@ -34,44 +34,53 @@ public class Person { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } - + @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } return hash; @@ -79,8 +88,10 @@ public class Person { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Person other = (Person) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java index 9c266c2c62..726ed2347e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java @@ -20,13 +20,13 @@ public class Student { private String id; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String firstName; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String lastName; @Field @Past @@ -38,8 +38,9 @@ public class Student { private DateTime updated; @Version private long version; - - public Student() {} + + public Student() { + } public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { this.id = id; @@ -51,36 +52,47 @@ public class Student { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getDateOfBirth() { return dateOfBirth; } + public void setDateOfBirth(DateTime dateOfBirth) { this.dateOfBirth = dateOfBirth; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } @@ -88,16 +100,16 @@ public class Student { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } - if(dateOfBirth != null) { + if (dateOfBirth != null) { hash = hash * 31 + dateOfBirth.hashCode(); } return hash; @@ -105,8 +117,10 @@ public class Student { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Student other = (Student) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index 66b672a4fd..751895502c 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository { private CouchbaseTemplate template; public List findByFirstNameStartsWith(String s) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName") - .startKey(s) - .stale(Stale.FALSE), - Student.class); + return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java index 14b77759e3..717feb858f 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java index 331ddc553d..9bbdeec642 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository, CustomStudentRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 90cc36780a..49548bdbfb 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("PersonRepositoryService") public class PersonRepositoryService implements PersonService { - + private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 45e9b90a19..8398847f65 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("PersonTemplateService") public class PersonTemplateService implements PersonService { - + private static final String DESIGN_DOC = "person"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Person findOne(String id) { - return template.findById(id, Person.class); + public Person findOne(String id) { + return template.findById(id, Person.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index 58304afc1c..65f5a6e78e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("StudentRepositoryService") public class StudentRepositoryService implements StudentService { - + private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java index c3808e0015..8d1292b5e4 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("StudentTemplateService") public class StudentTemplateService implements StudentService { - + private static final String DESIGN_DOC = "student"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Student findOne(String id) { - return template.findById(id, Student.class); + public Student findOne(String id) { + return template.findById(id, Student.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index 2cf388f518..b1857222c5 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository; public interface CampusRepository extends CrudRepository { - @View(designDocument="campus", viewName="byName") + @View(designDocument = "campus", viewName = "byName") Set findByName(String name); - @Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation") + @Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation") Set findByLocationNear(Point point, Distance distance); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java index e441bec6e4..ef37106c6d 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java index 2a960d37de..0d790d2f39 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java index d098c39011..58f00dda25 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -7,14 +7,14 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; public interface CampusService { - + Campus find(String id); Set findByName(String name); Set findByLocationNear(Point point, Distance distance); - + Set findAll(); - + void save(Campus campus); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index 612774fec9..586f5f0dc1 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -15,21 +15,22 @@ import org.springframework.stereotype.Service; public class CampusServiceImpl implements CampusService { private CampusRepository repo; + @Autowired public void setCampusRepository(CampusRepository repo) { this.repo = repo; } - + @Override public Campus find(String id) { return repo.findOne(id); } - + @Override public Set findByName(String name) { return repo.findByName(name); } - + @Override public Set findByLocationNear(Point point, Distance distance) { return repo.findByLocationNear(point, distance); @@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService { public Set findAll() { Set campuses = new HashSet<>(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { campuses.add(it.next()); } return campuses; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index f1ff513bff..fe0a9e48cd 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class PersonServiceImpl implements PersonService { private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class PersonServiceImpl implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 65400636cf..248d824081 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class StudentServiceImpl implements StudentService { private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class StudentServiceImpl implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index 8e6b971dbf..a37e918101 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -12,9 +12,9 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String BUCKET_NAME = "baeldung"; public static final String BUCKET_PASSWORD = ""; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java index 79948cbedf..0bf2c5d673 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java @@ -30,27 +30,17 @@ public abstract class StudentServiceTest extends IntegrationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + StudentService studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); @@ -60,7 +50,7 @@ public abstract class StudentServiceTest extends IntegrationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -130,11 +120,11 @@ public abstract class StudentServiceTest extends IntegrationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index f419ba3499..fe32305feb 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -38,29 +38,25 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { protected String getBucketPassword() { return DEFAULT_BUCKET_PASSWORD; } - + @Bean public Bucket campusBucket() throws Exception { return couchbaseCluster().openBucket("baeldung2", ""); } - + @Bean(name = "campusTemplate") public CouchbaseTemplate campusTemplate() throws Exception { - CouchbaseTemplate template = new CouchbaseTemplate( - couchbaseClusterInfo(), - campusBucket(), - mappingCouchbaseConverter(), - translationService()); + CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService()); template.setDefaultConsistency(getDefaultConsistency()); return template; } - + @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { baseMapping.mapEntity(Campus.class, campusTemplate()); } catch (Exception e) { - //custom Exception handling + // custom Exception handling } } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java index 7e24952e32..d3982e1ecc 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java @@ -19,61 +19,29 @@ import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; public class CampusServiceImplTest extends MultiBucketIntegationTest { - + @Autowired private CampusServiceImpl campusService; - + @Autowired private CampusRepository campusRepo; - - private final Campus Brown = Campus.Builder.newInstance() - .id("campus:Brown") - .name("Brown") - .location(new Point(71.4025, 51.8268)) - .build(); - private final Campus Cornell = Campus.Builder.newInstance() - .id("campus:Cornell") - .name("Cornell") - .location(new Point(76.4833, 42.4459)) - .build(); - - private final Campus Columbia = Campus.Builder.newInstance() - .id("campus:Columbia") - .name("Columbia") - .location(new Point(73.9626, 40.8075)) - .build(); - - private final Campus Dartmouth = Campus.Builder.newInstance() - .id("campus:Dartmouth") - .name("Dartmouth") - .location(new Point(72.2887, 43.7044)) - .build(); + private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build(); - private final Campus Harvard = Campus.Builder.newInstance() - .id("campus:Harvard") - .name("Harvard") - .location(new Point(71.1167, 42.3770)) - .build(); + private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build(); - private final Campus Penn = Campus.Builder.newInstance() - .id("campus:Penn") - .name("Penn") - .location(new Point(75.1932, 39.9522)) - .build(); + private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build(); + + private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build(); + + private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build(); + + private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build(); + + private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build(); + + private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build(); - private final Campus Princeton = Campus.Builder.newInstance() - .id("campus:Princeton") - .name("Princeton") - .location(new Point(74.6514, 40.3340)) - .build(); - - private final Campus Yale = Campus.Builder.newInstance() - .id("campus:Yale") - .name("Yale") - .location(new Point(72.9223, 41.3163)) - .build(); - private final Point Boston = new Point(71.0589, 42.3601); private final Point NewYorkCity = new Point(74.0059, 40.7128); @@ -88,7 +56,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { campusRepo.save(Princeton); campusRepo.save(Yale); } - + @Test public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Exception { Set campuses = campusService.findByName(Harvard.getName()); @@ -97,14 +65,14 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.size() == 1); assertTrue(campuses.contains(Harvard)); } - + @Test public final void givenHarvardId_whenFind_thenReturnsHarvard() throws Exception { Campus actual = campusService.find(Harvard.getId()); assertNotNull(actual); assertEquals(Harvard, actual); } - + @Test public final void whenFindAll_thenReturnsAll() throws Exception { Set campuses = campusService.findAll(); @@ -125,7 +93,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.contains(Harvard)); assertFalse(campuses.contains(Columbia)); } - + @Test public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception { Set campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL)); diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java index 220c2c3b00..c503726377 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java @@ -31,28 +31,18 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + @Autowired StudentServiceImpl studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); @@ -62,7 +52,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -77,7 +67,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -87,7 +77,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -132,11 +122,11 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -146,8 +136,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -157,8 +147,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java index db304ee78d..4ab5d40788 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -43,8 +43,7 @@ public class ElasticSearchUnitTests { @Test public void givenJsonString_whenJavaObject_thenIndexDocument() { String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String index = response.getIndex(); String type = response.getType(); assertTrue(response.isCreated()); @@ -55,8 +54,7 @@ public class ElasticSearchUnitTests { @Test public void givenDocumentId_whenJavaObject_thenDeleteDocument() { String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String id = response.getId(); DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get(); assertTrue(deleteResponse.isFound()); @@ -77,29 +75,11 @@ public class ElasticSearchUnitTests { @Test public void givenSearchParamters_thenReturnResults() { boolean isExecutedSuccessfully = true; - SearchResponse response = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response2 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response2 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response3 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.matchQuery("John", "Name*")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); try { response2.getHits(); response3.getHits(); @@ -114,14 +94,8 @@ public class ElasticSearchUnitTests { @Test public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { - XContentBuilder builder = XContentFactory.jsonBuilder() - .startObject() - .field("fullName", "Test") - .field("salary", "11500") - .field("age", "10") - .endObject(); - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(builder).get(); + XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get(); assertTrue(response.isCreated()); } } diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java index 06ad21647b..bb4b268ca7 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java @@ -140,7 +140,7 @@ public class GridFSIntegrationTest { assertNotNull(gridFSDBFiles); assertThat(gridFSDBFiles.size(), is(2)); } - + @Test public void givenMetadataAndFilesExist_whenFindingAllFilesOnQuery_thenFilesWithMetadataAreFoundOnQuery() { DBObject metaDataUser1 = new BasicDBObject(); diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index ac9a7260be..fb4fda1497 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; - -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver") - .setURI(URL); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 2b6394184d..81935b2293 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; - @EnableTransactionManagement -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -@Profile({"embedded", "test"}) +@Profile({ "embedded", "test" }) public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index e48dfaf276..029754c0fc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.Collection; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Movie { @@ -21,9 +21,11 @@ public class Movie { private int released; private String tagline; - @Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List roles; + @Relationship(type = "ACTED_IN", direction = Relationship.INCOMING) + private List roles; - public Movie() { } + public Movie() { + } public String getTitle() { return title; @@ -56,6 +58,5 @@ public class Movie { public void setRoles(List roles) { this.roles = roles; } - - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index d96dc07530..dc5a850f29 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.GraphId; @@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { @GraphId @@ -21,7 +20,8 @@ public class Person { @Relationship(type = "ACTED_IN") private List movies; - public Person() { } + public Person() { + } public String getName() { return name; @@ -46,5 +46,5 @@ public class Person { public void setMovies(List movies) { this.movies = movies; } - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 20512a10ad..40dabb054b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; @@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode; import java.util.Collection; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { @GraphId diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 850d2336ba..1bd605a7bc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository { Collection findByTitleContaining(@Param("title") String title); @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}") - List> graph(@Param("limit") int limit); + List> graph(@Param("limit") int limit); } - - diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index 4c287f99a4..f7f694c07f 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -4,8 +4,7 @@ import com.baeldung.spring.data.neo4j.domain.Person; import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.stereotype.Repository; - @Repository public interface PersonRepository extends GraphRepository { - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index 532cc79091..d760d19066 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -15,31 +15,31 @@ public class MovieService { MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels= new ArrayList>(); - int i=0; + List> nodes = new ArrayList>(); + List> rels = new ArrayList>(); + int i = 0; while (result.hasNext()) { Map row = result.next(); - nodes.add(map("title",row.get("movie"),"label","movie")); - int target=i; + nodes.add(map("title", row.get("movie"), "label", "movie")); + int target = i; i++; for (Object name : (Collection) row.get("cast")) { - Map actor = map("title", name,"label","actor"); + Map actor = map("title", name, "label", "actor"); int source = nodes.indexOf(actor); if (source == -1) { nodes.add(actor); source = i++; } - rels.add(map("source",source,"target",target)); + rels.add(map("source", source, "target", target)); } } return map("nodes", nodes, "links", rels); } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); - result.put(key1,value1); - result.put(key2,value2); + Map result = new HashMap(2); + result.put(key1, value1); + result.put(key2, value2); return result; } diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java index 8061b3c2a7..0e54208c31 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java @@ -82,8 +82,7 @@ public class MovieRepositoryTest { @DirtiesContext public void testFindAll() { System.out.println("findAll"); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertNotNull(result); assertEquals(1, result.size()); } @@ -93,8 +92,7 @@ public class MovieRepositoryTest { public void testFindByTitleContaining() { System.out.println("findByTitleContaining"); String title = "Italian"; - Collection result = - movieRepository.findByTitleContaining(title); + Collection result = movieRepository.findByTitleContaining(title); assertNotNull(result); assertEquals(1, result.size()); } @@ -126,8 +124,7 @@ public class MovieRepositoryTest { public void testDeleteAll() { System.out.println("deleteAll"); movieRepository.deleteAll(); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertEquals(0, result.size()); } } diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java index 9a42545d6c..4c55fc3179 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.redis.queue; - public interface MessagePublisher { void publish(final String message); diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index f4b3180a37..2a595305bd 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(final RedisTemplate redisTemplate, - final ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java index 9c4fd55fa4..64f12e82e9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java @@ -18,16 +18,16 @@ import javax.sql.DataSource; @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) public class InvalidResourceUsageExceptionTest { - @Autowired - private IFooService fooService; + @Autowired + private IFooService fooService; - @Autowired - private DataSource restDataSource; + @Autowired + private DataSource restDataSource; - @Test(expected = InvalidDataAccessResourceUsageException.class) - public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.execute("revoke select from tutorialuser"); + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("revoke select from tutorialuser"); try { fooService.findAll(); @@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest { } } - @Test(expected = BadSqlGrammarException.class) - public void whenIncorrectSql_thenBadSqlGrammarException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); - } + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java index b8b012c061..957207b7e6 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -4,78 +4,78 @@ import java.io.Serializable; public class Item implements Serializable { - private static final long serialVersionUID = 1L; - private Integer itemId; - private String itemName; - private String itemDescription; - private Integer itemPrice; + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; - // constructors - public Item() { + // constructors + public Item() { - } + } - public Item(final Integer itemId, final String itemName, final String itemDescription) { - super(); - this.itemId = itemId; - this.itemName = itemName; - this.itemDescription = itemDescription; - } + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.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 Item other = (Item) obj; - if (itemId == null) { - if (other.itemId != null) - return false; - } else if (!itemId.equals(other.itemId)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } - public Integer getItemId() { - return itemId; - } + public Integer getItemId() { + return itemId; + } - public void setItemId(final Integer itemId) { - this.itemId = itemId; - } + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } - public String getItemName() { - return itemName; - } + public String getItemName() { + return itemName; + } - public void setItemName(final String itemName) { - this.itemName = itemName; - } + public void setItemName(final String itemName) { + this.itemName = itemName; + } - public String getItemDescription() { - return itemDescription; - } + public String getItemDescription() { + return itemDescription; + } - public Integer getItemPrice() { - return itemPrice; - } + public Integer getItemPrice() { + return itemPrice; + } - public void setItemPrice(final Integer itemPrice) { - this.itemPrice = itemPrice; - } + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } - public void setItemDescription(final String itemDescription) { - this.itemDescription = itemDescription; - } + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java index 57f32cfe50..ff9ccb017b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -5,16 +5,15 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - + @SuppressWarnings("deprecation") public static Session getHibernateSession() { - final SessionFactory sf = new Configuration() - .configure("criteria.cfg.xml").buildSessionFactory(); + final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory(); - // factory = new Configuration().configure().buildSessionFactory(); - final Session session = sf.openSession(); - return session; + // factory = new Configuration().configure().buildSessionFactory(); + final Session session = sf.openSession(); + return session; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 4db94f2ad7..83e3c2f9a5 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil; public class ApplicationView { - // default Constructor - public ApplicationView() { + // default Constructor + public ApplicationView() { - } + } - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + Transaction tx = null; - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.add(Restrictions.like("itemName", "%item One%")); + final List results = cr.list(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + tx = session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.gt("itemPrice", 1000)); + final List greaterThanItemsList = cr.list(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); + } + session.close(); + return greaterThanItems; + } - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.lt("itemPrice", 1000)); + final List lessThanItemsList = cr.list(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i).getItemName(); + } + session.close(); + return lessThanItems; + } - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.like("itemName", "%chair%")); + final List likeItemsList = cr.list(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i).getItemName(); + } + session.close(); + return likeItems; + } - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.ilike("itemName", "%Chair%")); + final List ilikeItemsList = cr.list(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i).getItemName(); + } + session.close(); + return ilikeItems; + } - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + // To get items having price more than 1000 + cr.add(Restrictions.between("itemPrice", 100, 200)); + final List betweenItemsList = cr.list(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i).getItemName(); + } + session.close(); + return betweenItems; + } - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + final List nullItemsList = cr.list(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i).getItemName(); + } + session.close(); + return nullDescItems; + } - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNotNull("itemDescription")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + cr.add(Restrictions.like("itemName", "chair%")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + cr.add(andExample); + final List andItemsList = cr.list(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i).getItemName(); + } + session.close(); + return andItems; + } - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); + cr.add(orExample); + final List orItemsList = cr.list(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i).getItemName(); + } + session.close(); + return orItems; + } - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()) - .list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.addOrder(Order.asc("itemName")); + cr.addOrder(Order.desc("itemPrice")).list(); + final List sortedItemsList = cr.list(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i).getItemName(); + } + session.close(); + return sortedItems; + } - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class) - .setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index ec8dc32200..f4a9b8a678 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -5,54 +5,54 @@ import java.io.Serializable; import java.sql.Date; @Entity -@Table (name = "USER_ORDER") -public class OrderDetail implements Serializable{ +@Table(name = "USER_ORDER") +public class OrderDetail implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="ORDER_ID") - private Long orderId; - - public OrderDetail(){ - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.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; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } + private static final long serialVersionUID = 1L; - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } + @Id + @GeneratedValue + @Column(name = "ORDER_ID") + private Long orderId; + + public OrderDetail() { + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.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; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } - - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 22b4fdc76c..2559d5f048 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -6,66 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserEager implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserEager() { - } + private static final long serialVersionUID = 1L; - public UserEager(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserEager other = (UserEager) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserEager() { + } - public Long getUserId() { - return userId; - } + public UserEager(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index 5038fb90ef..5852e74418 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -6,67 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserLazy implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserLazy() { - } + private static final long serialVersionUID = 1L; - public UserLazy(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserLazy other = (UserLazy) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserLazy() { + } - public Long getUserId() { - return userId; - } + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index bbd7729232..c7be96abb7 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - SessionFactory sf; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - - // fetching.cfg.xml is used for this example - return sf.openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + // two config files are there + // one with lazy loading enabled + // another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } public static Session getHibernateSession() { - return new Configuration() - .configure("fetching.cfg.xml") - .buildSessionFactory() - .openSession(); + return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java index bdd48d6aa6..d36a1e58cf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java @@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; -@NamedNativeQueries({ - @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), - @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) @Entity @Audited // @Proxy(lazy = false) public class Foo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); - public Foo() { - super(); - } + public Foo() { + super(); + } - public Foo(final String name) { - super(); - this.name = name; - } + public Foo(final String name) { + super(); + this.name = name; + } - // + // - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(final Bar bar) { - this.bar = bar; - } + public void setBar(final Bar bar) { + this.bar = bar; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final 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 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 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(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java index 3bd8c5ee00..88186098cc 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java @@ -14,178 +14,170 @@ import com.baeldung.hibernate.criteria.view.ApplicationView; public class HibernateCriteriaTest { - final private ApplicationView av = new ApplicationView(); + final private ApplicationView av = new ApplicationView(); - @Test - public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); - } - - @Test - public void testLikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); - final String expectedLikeItems[] = new String[expectedLikeList.size()]; - for (int i = 0; i < expectedLikeList.size(); i++) { - expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLikeItems, av.likeCriteria()); - } + @Test + public void testPerformanceOfCriteria() { + assertTrue(av.checkIfCriteriaTimeLower()); + } - @Test - public void testILikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); - final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; - for (int i = 0; i < expectedChairCaseList.size(); i++) { - expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); + @Test + public void testLikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, av.likeCriteria()); + } - } + @Test + public void testILikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - @Test - public void testNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null") - .list(); - final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { - expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); - } + } - @Test - public void testIsNotNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNotNullDescItemsList = session - .createQuery("From Item where itemDescription is not null").list(); - final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { - expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); + @Test + public void testNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list(); + final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { + expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); + } - } + @Test + public void testIsNotNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list(); + final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { + expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); - @Test - public void testAverageProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item") - .list(); + } - final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; - for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { - expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); + @Test + public void testAverageProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list(); - } + final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; + for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { + expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); - @Test - public void testRowCountProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); - final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; - for (int i = 0; i < expectedCountProjItemsList.size(); i++) { - expectedCountProjItems[i] = expectedCountProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); - } + } - @Test - public void testOrCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedOrCritItemsList = session - .createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); - final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; - for (int i = 0; i < expectedOrCritItemsList.size(); i++) { - expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); - } + @Test + public void testRowCountProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); + final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; + for (int i = 0; i < expectedCountProjItemsList.size(); i++) { + expectedCountProjItems[i] = expectedCountProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); + } - @Test - public void testAndCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAndCritItemsList = session - .createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); - final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; - for (int i = 0; i < expectedAndCritItemsList.size(); i++) { - expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); - } + @Test + public void testOrCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); + final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; + for (int i = 0; i < expectedOrCritItemsList.size(); i++) { + expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); + } - @Test - public void testMultiCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedMultiCritItemsList = session - .createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); - final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; - for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { - expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); - } + @Test + public void testAndCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); + final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; + for (int i = 0; i < expectedAndCritItemsList.size(); i++) { + expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); + } - @Test - public void testSortCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedSortCritItemsList = session - .createQuery("From Item order by itemName asc, itemPrice desc").list(); - final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; - for (int i = 0; i < expectedSortCritItemsList.size(); i++) { - expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); - } + @Test + public void testMultiCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); + final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; + for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { + expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); + } - @Test - public void testGreaterThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); - final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; - for (int i = 0; i < expectedGreaterThanList.size(); i++) { - expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); - } + @Test + public void testSortCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list(); + final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; + for (int i = 0; i < expectedSortCritItemsList.size(); i++) { + expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); + } - @Test - public void testLessThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); - final String expectedLessThanItems[] = new String[expectedLessList.size()]; - for (int i = 0; i < expectedLessList.size(); i++) { - expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); - } + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); + } - @Test - public void betweenCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200") - .list(); - final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; - for (int i = 0; i < expectedBetweenList.size(); i++) { - expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); - } + @Test + public void testLessThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); + } + + @Test + public void betweenCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java index 8341df9fcb..99164efb7a 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure; public class HibernateCriteriaTestRunner { - public static void main(final String[] args) { - Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); - for (Failure failure : result.getFailures()) { - - } - } + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java index ab27a6ba82..2911fb4725 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -7,5 +7,5 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ HibernateCriteriaTest.class }) public class HibernateCriteriaTestSuite { - + } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index a650f8eb37..42245ca89e 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -13,31 +13,30 @@ import static org.junit.Assert.assertTrue; public class HibernateFetchingTest { + // this loads sample data in the database + @Before + public void addFecthingTestData() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } - //this loads sample data in the database - @Before - public void addFecthingTestData(){ - FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - } - - //testLazyFetching() tests the lazy loading - //Since it lazily loaded so orderDetalSetLazy won't - //be initialized - @Test - public void testLazyFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetLazy = fav.lazyLoaded(); - assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); - } - - //testEagerFetching() tests the eager loading - //Since it eagerly loaded so orderDetalSetLazy would - //be initialized - @Test - public void testEagerFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetEager = fav.eagerLoaded(); - assertTrue(Hibernate.isInitialized(orderDetalSetEager)); - } + // testLazyFetching() tests the lazy loading + // Since it lazily loaded so orderDetalSetLazy won't + // be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + // testEagerFetching() tests the eager loading + // Since it eagerly loaded so orderDetalSetLazy would + // be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java index aadaefbe44..2e729c5680 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java @@ -1,6 +1,5 @@ package com.baeldung.persistence.save; - import com.baeldung.persistence.model.Person; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -25,16 +24,9 @@ public class SaveMethodsTest { @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration() - .addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( - configuration.getProperties()).build(); + Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } @@ -44,7 +36,6 @@ public class SaveMethodsTest { session.beginTransaction(); } - @Test public void whenPersistTransient_thenSavedToDatabaseOnCommit() { @@ -244,7 +235,6 @@ public class SaveMethodsTest { assertNotNull(session.get(Person.class, person.getId())); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java index 238b228101..db64107405 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java @@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo; import com.baeldung.spring.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooStoredProceduresIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); @@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getFoosByNameExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getAllFoosExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo(randomAlphabetic(6))); // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity( - Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); @SuppressWarnings("unchecked") List allFoos = sqlQuery.list(); for (Foo foo : allFoos) { @@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo("NewFooName")); // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)") - .addEntity(Foo.class).setParameter("fooName", "NewFooName"); + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName = sqlQuery.list(); for (Foo foo : allFoosByName) { @@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest { } // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName") - .setParameter("fooName", "NewFooName"); + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName2 = namedQuery.list(); for (Foo foo : allFoosByName2) { diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java index 439bc6caad..c0761939ad 100644 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -12,8 +12,7 @@ public class DefaultTextMessageSenderTest { @SuppressWarnings("resource") @BeforeClass public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext( - "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java index da9bb0294d..117f8bed82 100644 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -12,8 +12,7 @@ public class MapMessageConvertAndSendTest { @SuppressWarnings("resource") @BeforeClass public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext( - "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index f97f53b82c..907043b8ce 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest { final Foo foo = new Foo(randomAlphabetic(6)); fooService.create(foo); fooService.findOne(foo.getId()); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest { return nativeQuery.executeUpdate(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @Test public final void givenCacheableQueryIsExecuted_thenItIsCached() { new TransactionTemplate(platformTransactionManager).execute(status -> { - return entityManager.createQuery("select f from Foo f") - .setHint("org.hibernate.cacheable", true) - .getResultList(); + return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); assertThat(size, greaterThan(0)); } } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 67e4c6ae1d..58a92002c8 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -30,7 +30,7 @@ public class User { private String email; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JsonApiToMany @JsonApiIncludeByDefault private Set roles; diff --git a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java index 32be4c6a0a..94309cf1a6 100644 --- a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java +++ b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MocksApplication { - public static void main(String[] args) { - SpringApplication.run(MocksApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MocksApplication.class, args); + } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index 679a455f3f..10b54e345c 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -17,13 +17,12 @@ public class MainController { @Autowired private ITutorialsService tutService; - @RequestMapping(value ="/", method = RequestMethod.GET) + @RequestMapping(value = "/", method = RequestMethod.GET) public String welcomePage() { - return "index"; + return "index"; } - - - @RequestMapping(value ="/list", method = RequestMethod.GET) + + @RequestMapping(value = "/list", method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); @@ -37,6 +36,5 @@ public class MainController { public void setTutService(ITutorialsService tutService) { this.tutService = tutService; } - - + } \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java index 24059f2662..237b603590 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java @@ -6,5 +6,5 @@ import java.util.List; public interface ITutorialsService { - List listTutorials(); + List listTutorials(); } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java index f67cc0824f..9d48e130c8 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java @@ -10,9 +10,6 @@ import java.util.List; public class TutorialsService implements ITutorialsService { public List listTutorials() { - return Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); + return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")); } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java index ce8ce1919a..17388b52b0 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"}) +@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java index a9fb242755..1f90b0fc67 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java @@ -38,7 +38,6 @@ public class DataContentControllerTest { @Before public void setUp() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @@ -53,9 +52,9 @@ public class DataContentControllerTest { mockMvc.perform(get("/list")).andExpect(xpath("//table").exists()); mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists()); } - + @Test - public void whenCallingIndex_thenViewOK() throws Exception{ + public void whenCallingIndex_thenViewOK() throws Exception { mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0)); } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java index 8b84bcdd23..a75cd1291a 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java @@ -8,7 +8,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration public class TestConfig { - @Bean public ViewResolver viewResolver() { @@ -19,14 +18,12 @@ public class TestConfig { bean.setSuffix(".vm"); return bean; } - + @Bean public VelocityConfigurer velocityConfig() { VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setResourceLoaderPath("/"); return velocityConfigurer; } - - } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 76351b96f7..b5238b04d5 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index bee09b742a..f299c46dbc 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - @Bean - public MessageSource messageSource() { + @Bean + public MessageSource messageSource() { - final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); - ms.setBasenames("messages"); - return ms; - } + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - @Bean - public ResourceBundle getBeanResourceBundle() { + @Bean + public ResourceBundle getBeanResourceBundle() { - final Locale locale = Locale.getDefault(); - return new MessageSourceResourceBundle(messageSource(), locale); - } + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); - return bean; - } + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index aa25f47a2a..fa76933f8f 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee; @Controller public class EmployeeController { - Map employeeMap = new HashMap<>(); + Map employeeMap = new HashMap<>(); - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } - @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - employeeMap.put(employee.getId(), employee); - return "employeeView"; - } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index cc9d66d4d4..17f0801a6e 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -11,8 +11,7 @@ public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java index 614888ae42..c7f3adb594 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using ControllerClassNameHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using ControllerClassNameHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java index 6ed3d06ab7..a0be507125 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using BeanNameUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using BeanNameUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java index 39dabf86ed..71d9ad7845 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java @@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PersonController { - @Autowired - PersonValidator validator; + @Autowired + PersonValidator validator; - @RequestMapping(value = "/person", method = RequestMethod.GET) - public ModelAndView showForm(final Model model) { + @RequestMapping(value = "/person", method = RequestMethod.GET) + public ModelAndView showForm(final Model model) { - initData(model); - return new ModelAndView("personForm", "person", new Person()); - } + initData(model); + return new ModelAndView("personForm", "person", new Person()); + } - @RequestMapping(value = "/addPerson", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, - final ModelMap modelMap, final Model model) { + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) { - validator.validate(person, result); + validator.validate(person, result); - if (result.hasErrors()) { + if (result.hasErrors()) { - initData(model); - return "personForm"; - } + initData(model); + return "personForm"; + } - modelMap.addAttribute("person", person); + modelMap.addAttribute("person", person); - return "personView"; - } + return "personView"; + } - private void initData(final Model model) { + private void initData(final Model model) { - final List favouriteLanguageItem = new ArrayList(); - favouriteLanguageItem.add("Java"); - favouriteLanguageItem.add("C++"); - favouriteLanguageItem.add("Perl"); - model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); + final List favouriteLanguageItem = new ArrayList(); + favouriteLanguageItem.add("Java"); + favouriteLanguageItem.add("C++"); + favouriteLanguageItem.add("Perl"); + model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); - final List jobItem = new ArrayList(); - jobItem.add("Full time"); - jobItem.add("Part time"); - model.addAttribute("jobItem", jobItem); + final List jobItem = new ArrayList(); + jobItem.add("Full time"); + jobItem.add("Part time"); + model.addAttribute("jobItem", jobItem); - final Map countryItems = new LinkedHashMap(); - countryItems.put("US", "United Stated"); - countryItems.put("IT", "Italy"); - countryItems.put("UK", "United Kingdom"); - countryItems.put("FR", "Grance"); - model.addAttribute("countryItems", countryItems); + final Map countryItems = new LinkedHashMap(); + countryItems.put("US", "United Stated"); + countryItems.put("IT", "Italy"); + countryItems.put("UK", "United Kingdom"); + countryItems.put("FR", "Grance"); + model.addAttribute("countryItems", countryItems); - final List fruit = new ArrayList(); - fruit.add("Banana"); - fruit.add("Mango"); - fruit.add("Apple"); - model.addAttribute("fruit", fruit); + final List fruit = new ArrayList(); + fruit.add("Banana"); + fruit.add("Mango"); + fruit.add("Apple"); + model.addAttribute("fruit", fruit); - final List books = new ArrayList(); - books.add("The Great Gatsby"); - books.add("Nineteen Eighty-Four"); - books.add("The Lord of the Rings"); - model.addAttribute("books", books); - } + final List books = new ArrayList(); + books.add("The Great Gatsby"); + books.add("Nineteen Eighty-Four"); + books.add("The Lord of the Rings"); + model.addAttribute("books", books); + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java index 5459481674..2760fb8f89 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -11,8 +11,7 @@ public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); - model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java index 88e4f9ff4c..01638fbe76 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java @@ -7,146 +7,146 @@ import org.springframework.web.multipart.MultipartFile; public class Person { - private long id; + private long id; - private String name; - private String email; - private String dateOfBirth; + private String name; + private String email; + private String dateOfBirth; - @NotEmpty - private String password; - private String sex; - private String country; - private String book; - private String job; - private boolean receiveNewsletter; - private String[] hobbies; - private List favouriteLanguage; - private List fruit; - private String notes; - private MultipartFile file; + @NotEmpty + private String password; + private String sex; + private String country; + private String book; + private String job; + private boolean receiveNewsletter; + private String[] hobbies; + private List favouriteLanguage; + private List fruit; + private String notes; + private MultipartFile file; - public Person() { - super(); - } + public Person() { + super(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(final String email) { - this.email = email; - } + public void setEmail(final String email) { + this.email = email; + } - public String getDateOfBirth() { - return dateOfBirth; - } + public String getDateOfBirth() { + return dateOfBirth; + } - public void setDateOfBirth(final String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } + public void setDateOfBirth(final String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(final String password) { - this.password = password; - } + public void setPassword(final String password) { + this.password = password; + } - public String getSex() { - return sex; - } + public String getSex() { + return sex; + } - public void setSex(final String sex) { - this.sex = sex; - } + public void setSex(final String sex) { + this.sex = sex; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(final String country) { - this.country = country; - } + public void setCountry(final String country) { + this.country = country; + } - public String getJob() { - return job; - } + public String getJob() { + return job; + } - public void setJob(final String job) { - this.job = job; - } + public void setJob(final String job) { + this.job = job; + } - public boolean isReceiveNewsletter() { - return receiveNewsletter; - } + public boolean isReceiveNewsletter() { + return receiveNewsletter; + } - public void setReceiveNewsletter(final boolean receiveNewsletter) { - this.receiveNewsletter = receiveNewsletter; - } + public void setReceiveNewsletter(final boolean receiveNewsletter) { + this.receiveNewsletter = receiveNewsletter; + } - public String[] getHobbies() { - return hobbies; - } + public String[] getHobbies() { + return hobbies; + } - public void setHobbies(final String[] hobbies) { - this.hobbies = hobbies; - } + public void setHobbies(final String[] hobbies) { + this.hobbies = hobbies; + } - public List getFavouriteLanguage() { - return favouriteLanguage; - } + public List getFavouriteLanguage() { + return favouriteLanguage; + } - public void setFavouriteLanguage(final List favouriteLanguage) { - this.favouriteLanguage = favouriteLanguage; - } + public void setFavouriteLanguage(final List favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } - public String getNotes() { - return notes; - } + public String getNotes() { + return notes; + } - public void setNotes(final String notes) { - this.notes = notes; - } + public void setNotes(final String notes) { + this.notes = notes; + } - public List getFruit() { - return fruit; - } + public List getFruit() { + return fruit; + } - public void setFruit(final List fruit) { - this.fruit = fruit; - } + public void setFruit(final List fruit) { + this.fruit = fruit; + } - public String getBook() { - return book; - } + public String getBook() { + return book; + } - public void setBook(final String book) { - this.book = book; - } + public void setBook(final String book) { + this.book = book; + } - public MultipartFile getFile() { - return file; - } + public MultipartFile getFile() { + return file; + } - public void setFile(final MultipartFile file) { - this.file = file; - } + public void setFile(final MultipartFile file) { + this.file = file; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java index 3a271f6545..f7625bacd9 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java @@ -9,14 +9,14 @@ import org.springframework.validation.Validator; @Component public class PersonValidator implements Validator { - @Override - public boolean supports(final Class calzz) { - return Person.class.isAssignableFrom(calzz); - } + @Override + public boolean supports(final Class calzz) { + return Person.class.isAssignableFrom(calzz); + } - @Override - public void validate(final Object obj, final Errors errors) { + @Override + public void validate(final Object obj, final Errors errors) { - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); - } + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); + } } \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java index e51e4ad43d..547ef78d84 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java @@ -10,7 +10,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SpringQuartzApp { public static void main(String[] args) { - new SpringApplicationBuilder(SpringQuartzApp.class) - .showBanner(false).run(args); + new SpringApplicationBuilder(SpringQuartzApp.class).showBanner(false).run(args); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index a944f8fe43..6601df6c94 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -45,8 +45,7 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) - throws SchedulerException, IOException { + public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); @@ -64,9 +63,7 @@ public class QrtzScheduler { @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class).storeDurably() - .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) - .withDescription("Invoke Sample Job service...").build(); + return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean @@ -75,10 +72,6 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) - .withDescription("Sample trigger") - .withSchedule( - simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) - .build(); + return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 9474272a3c..7c50f9a231 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -19,8 +19,7 @@ public class SampleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), - context.getFireTime()); + logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), context.getFireTime()); jobService.executeSampleJob(); diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java index 0e24238467..d3034ae7af 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java @@ -11,21 +11,17 @@ import org.springframework.scheduling.quartz.SpringBeanJobFactory; * Adds auto-wiring support to quartz jobs. * @see "https://gist.github.com/jelies/5085593" */ -public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory - implements ApplicationContextAware { +public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; - - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { beanFactory = applicationContext.getAutowireCapableBeanFactory(); } @Override - protected Object createJobInstance(final TriggerFiredBundle bundle) - throws Exception { + protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java index d640ac671d..aa694c08ed 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java @@ -8,9 +8,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class CompanyController { - @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) - public Company getCompanyRest() { - final Company company = new Company(1, "Xpto"); - return company; - } + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java index f3e3738bfe..1cc3eae432 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java @@ -14,26 +14,26 @@ import com.fasterxml.jackson.annotation.JsonView; @RestController public class ItemController { - @JsonView(Views.Public.class) - @RequestMapping("/items/{id}") - public Item getItemPublic(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Public.class) + @RequestMapping("/items/{id}") + public Item getItemPublic(@PathVariable final int id) { + return ItemManager.getById(id); + } - @JsonView(Views.Internal.class) - @RequestMapping("/items/internal/{id}") - public Item getItemInternal(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Internal.class) + @RequestMapping("/items/internal/{id}") + public Item getItemInternal(@PathVariable final int id) { + return ItemManager.getById(id); + } - @RequestMapping("/date") - public Date getCurrentDate() throws Exception { - return new Date(); - } + @RequestMapping("/date") + public Date getCurrentDate() throws Exception { + return new Date(); + } - @RequestMapping("/delay/{seconds}") - public void getCurrentTime(@PathVariable final int seconds) throws Exception { + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { - Thread.sleep(seconds * 1000); - } + Thread.sleep(seconds * 1000); + } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java index 7d62cc0c66..996f229128 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java index 348ee6d596..458bdaf170 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java @@ -3,8 +3,8 @@ package org.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message") +@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message") public class ForbiddenException extends RuntimeException { - private static final long serialVersionUID = 6826605655586311552L; + private static final long serialVersionUID = 6826605655586311552L; } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java index c7d0718140..3164d604ad 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java @@ -2,37 +2,37 @@ package org.baeldung.web.dto; public class Company { - private long id; - private String name; + private long id; + private String name; - public Company() { - super(); - } + public Company() { + super(); + } - public Company(final long id, final String name) { - this.id = id; - this.name = name; - } + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - @Override - public String toString() { - return "Company [id=" + id + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java index 61251ea33a..8ca96c38fc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java @@ -4,617 +4,594 @@ package org.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 { - - /** - * required int64 id = 1; - */ - boolean hasId(); - /** - * required int64 id = 1; - */ - long getId(); - - /** - * required string name = 2; - */ - boolean hasName(); - /** - * required string name = 2; - */ - java.lang.String getName(); - /** - * required string name = 2; - */ - 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; + private FooProtos() { } - public Foo getDefaultInstanceForType() { - return defaultInstance; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { } - 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 org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + public interface FooOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Foo) + com.google.protobuf.MessageOrBuilder { + + /** + * required int64 id = 1; + */ + boolean hasId(); + + /** + * required int64 id = 1; + */ + long getId(); + + /** + * required string name = 2; + */ + boolean hasName(); + + /** + * required string name = 2; + */ + java.lang.String getName(); + + /** + * required string name = 2; + */ + com.google.protobuf.ByteString getNameBytes(); } - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - 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 getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int ID_FIELD_NUMBER = 1; - private long id_; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - - public static final int NAME_FIELD_NUMBER = 2; - private java.lang.Object name_; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - 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; - } - } - /** - * required string name = 2; - */ - 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 org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.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 org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.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(org.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 implements - // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - // Construct using org.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) { + 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 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 org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); - } - - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private Foo(boolean noInit) { + this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - return result; - } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + private static final Foo defaultInstance; + + public static Foo getDefaultInstance() { + return defaultInstance; } - result.id_ = id_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; + + public Foo getDefaultInstanceForType() { + return defaultInstance; } - result.name_ = name_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other); - } else { - super.mergeFrom(other); - return this; + private final com.google.protobuf.UnknownFieldSet unknownFields; + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; - if (other.hasId()) { - setId(other.getId()); + 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(); + } } - if (other.hasName()) { - bitField0_ |= 0x00000002; - name_ = other.name_; - onChanged(); + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - public final boolean isInitialized() { - if (!hasId()) { - - return false; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); } - if (!hasName()) { - - return false; - } - return true; - } - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private long id_ ; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - /** - * required int64 id = 1; - */ - public Builder setId(long value) { - bitField0_ |= 0x00000001; - id_ = value; - onChanged(); - return this; - } - /** - * required int64 id = 1; - */ - public Builder clearId() { - bitField0_ = (bitField0_ & ~0x00000001); - id_ = 0L; - onChanged(); - return this; - } - - private java.lang.Object name_ = ""; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - 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; - } - } - /** - * required string name = 2; - */ - 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; - } - } - /** - * required string name = 2; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000002); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * required string name = 2; - */ - 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\024org.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; - } + public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Foo(input, extensionRegistry); + } }; - 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.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + 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; + } + } + + /** + * required string name = 2; + */ + 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 org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.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 org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + + public static org.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 org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.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(org.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 implements + // @@protoc_insertion_point(builder_implements:baeldung.Foo) + org.baeldung.web.dto.FooProtos.FooOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + // Construct using org.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 org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + } + + public org.baeldung.web.dto.FooProtos.Foo build() { + org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.baeldung.web.dto.FooProtos.Foo buildPartial() { + org.baeldung.web.dto.FooProtos.Foo result = new org.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 org.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { + if (other == org.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 { + org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + /** + * required int64 id = 1; + */ + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + + /** + * required int64 id = 1; + */ + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + 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; + } + } + + /** + * required string name = 2; + */ + 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; + } + } + + /** + * required string name = 2; + */ + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + 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\024org.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) } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java index 1344d2d40e..c50e1b4f43 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java @@ -32,13 +32,11 @@ public class ExampleControllerTest { @Test public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception { - mockMvc.perform(get("/controller")) - .andExpect(status().isNotAcceptable()); + mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable()); } @Test public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception { - mockMvc.perform(get("/exception")) - .andExpect(status().isForbidden()); + mockMvc.perform(get("/exception")).andExpect(status().isForbidden()); } } diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index c662c32738..e6c77110b3 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -51,9 +51,7 @@ public class MyUserDetailsService implements UserDetailsService { private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = roles.stream() - .map(role -> new SimpleGrantedAuthority(role.toString())) - .collect(Collectors.toList()); + final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); return new User(username, password, true, true, true, true, authorities); } diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 67d9abbae5..616c2a7684 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:on } - } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java index 80af01aeeb..3d727fc19f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java @@ -8,9 +8,9 @@ import org.springframework.web.context.request.RequestContextListener; public class ListenerConfig implements WebApplicationInitializer { - @Override - public void onStartup(ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new RequestContextListener()); - } + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index 57e9b32a62..efdb2bc8d4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("org.baeldung.web") @EnableWebMvc -public class WebConfig extends WebMvcConfigurerAdapter{ +public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { super(); @@ -39,11 +39,11 @@ public class WebConfig extends WebMvcConfigurerAdapter{ registry.addViewController("/homepage.html"); } - @Override - public void addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - registry.addInterceptor(new UserInterceptor()); - registry.addInterceptor(new SessionTimerInterceptor()); - } + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java index f5c1626989..90199347b4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -13,44 +13,41 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SessionTimerInterceptor extends HandlerInterceptorAdapter { - private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); - private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; - @Autowired - private HttpSession session; + @Autowired + private HttpSession session; - /** - * Executed before actual handler is executed - **/ - @Override - public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) - throws Exception { - log.info("Pre handle method - check handling start time"); - long startTime = System.currentTimeMillis(); - request.setAttribute("executionTime", startTime); - if (UserInterceptor.isUserLogged()) { - session = request.getSession(); - log.info("Time since last request in this session: {} ms", - System.currentTimeMillis() - request.getSession().getLastAccessedTime()); - if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { - log.warn("Logging out, due to inactive session"); - SecurityContextHolder.clearContext(); - request.logout(); - response.sendRedirect("/spring-security-rest-full/logout"); - } - } - return true; - } + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("Pre handle method - check handling start time"); + long startTime = System.currentTimeMillis(); + request.setAttribute("executionTime", startTime); + if (UserInterceptor.isUserLogged()) { + session = request.getSession(); + log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession().getLastAccessedTime()); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + request.logout(); + response.sendRedirect("/spring-security-rest-full/logout"); + } + } + return true; + } - /** - * Executed before after handler is executed - **/ - @Override - public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, - final ModelAndView model) throws Exception { - log.info("Post handle method - check execution time of handling"); - long startTime = (Long) request.getAttribute("executionTime"); - log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); - } + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView model) throws Exception { + log.info("Post handle method - check execution time of handling"); + long startTime = (Long) request.getAttribute("executionTime"); + log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java index 4ba12d0138..6b808d885e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java @@ -31,8 +31,7 @@ public class UserInterceptor extends HandlerInterceptorAdapter { * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle **/ @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) - throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception { if (model != null && !isRedirectView(model)) { if (isUserLogged()) { addToModelUserDetails(model); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java index a29de04bb4..916a849c63 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java @@ -30,27 +30,26 @@ import org.springframework.web.context.WebApplicationContext; @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class SessionTimerInterceptorTest { - @Autowired - WebApplicationContext wac; + @Autowired + WebApplicationContext wac; - private MockMvc mockMvc; + private MockMvc mockMvc; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } - /** - * After execution of HTTP GET logs from interceptor will be displayed in - * the console - */ - @Test - public void testInterceptors() throws Exception { - HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn() - .getRequest().getSession(); - Thread.sleep(51000); - mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); - } + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn().getRequest().getSession(); + Thread.sleep(51000); + mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java index 0b65311203..ff40c86906 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java @@ -23,8 +23,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -@ContextConfiguration(classes = {SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class}) -@WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class UserInterceptorTest { @Autowired @@ -46,8 +46,7 @@ public class UserInterceptorTest { */ @Test public void testInterceptors() throws Exception { - mockMvc.perform(get("/auth/admin")) - .andExpect(status().is2xxSuccessful()); + mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()); } }