formatting work

This commit is contained in:
eugenp 2016-10-12 08:02:05 +03:00
parent eb7650eead
commit 856be0a08a
128 changed files with 2039 additions and 2275 deletions

View File

@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringE
}
}

View File

@ -27,9 +27,7 @@ public class SpringAkkaTest extends AbstractJUnit4SpringContextTests {
@Test
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
ActorRef greeter = system.actorOf(
SPRING_EXTENSION_PROVIDER.get(system)
.props("greetingActor"), "greeter");
ActorRef greeter = system.actorOf(SPRING_EXTENSION_PROVIDER.get(system).props("greetingActor"), "greeter");
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
Timeout timeout = Timeout.durationToTimeout(duration);

View File

@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
super();
}
@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() {
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();

View File

@ -11,7 +11,6 @@ public class Foo {
private static final AtomicInteger instanceCount = new AtomicInteger(0);
private final int instanceNum;
public Foo() {

View File

@ -18,7 +18,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
@ -43,9 +42,7 @@ public class ControllerAnnotationTest {
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
.andReturn()
.getModelAndView();
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@ -57,9 +54,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@ -72,9 +67,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();

View File

@ -41,9 +41,7 @@ public class ControllerTest {
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
.andReturn()
.getModelAndView();
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@ -55,9 +53,7 @@ public class ControllerTest {
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@ -70,9 +66,7 @@ public class ControllerTest {
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();

View File

@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
String result = this.mockMvc.perform(get("/test")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assert.assertEquals("login = john, query = invoices", result);
}

View File

@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
this.mockMvc.perform(get("/appointments")
.accept(MediaType.ALL))
.andExpect(status().isOk());
this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
verify(appointmentService);
}

View File

@ -1,6 +1,5 @@
package org.baeldung.spring43.defaultmethods;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;

View File

@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
MockHttpSession session = new MockHttpSession();
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request")
.session(session)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request")
.session(session)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
}
@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session")
.session(session1)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session")
.session(session1)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session")
.session(session2)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application")
.session(session1)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application")
.session(session2)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);

View File

@ -21,6 +21,3 @@ public class CommitIdApplication {
return c;
}
}

View File

@ -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");
}
}

View File

@ -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)));
}
}

View File

@ -69,7 +69,6 @@ public class SpringBootMailTest {
return wiserMessage.getMimeMessage().getSubject();
}
private SimpleMailMessage composeEmailMessage() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userTo);

View File

@ -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

View File

@ -23,18 +23,23 @@ public class Campus {
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;
}
@ -56,14 +61,17 @@ 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;

View File

@ -34,30 +34,39 @@ 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;
}
@ -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();
}

View File

@ -39,7 +39,8 @@ public class Student {
@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;
}
@ -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();
}

View File

@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository {
private CouchbaseTemplate template;
public List<Student> 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);
}
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstName(String firstName);
List<Person> findByLastName(String lastName);
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
List<Student> findByFirstName(String firstName);
List<Student> findByLastName(String lastName);
}

View File

@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
public class PersonRepositoryService implements PersonService {
private PersonRepository repo;
@Autowired
public void setPersonRepository(PersonRepository repo) {
this.repo = repo;

View File

@ -18,6 +18,7 @@ public class PersonTemplateService implements PersonService {
private static final String DESIGN_DOC = "person";
private CouchbaseTemplate template;
@Autowired
public void setCouchbaseTemplate(CouchbaseTemplate template) {
this.template = template;

View File

@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
public class StudentRepositoryService implements StudentService {
private StudentRepository repo;
@Autowired
public void setStudentRepository(StudentRepository repo) {
this.repo = repo;

View File

@ -18,6 +18,7 @@ public class StudentTemplateService implements StudentService {
private static final String DESIGN_DOC = "student";
private CouchbaseTemplate template;
@Autowired
public void setCouchbaseTemplate(CouchbaseTemplate template) {
this.template = template;

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstName(String firstName);
List<Person> findByLastName(String lastName);
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, String> {
List<Student> findByFirstName(String firstName);
List<Student> findByLastName(String lastName);
}

View File

@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
public class CampusServiceImpl implements CampusService {
private CampusRepository repo;
@Autowired
public void setCampusRepository(CampusRepository repo) {
this.repo = repo;

View File

@ -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;

View File

@ -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;

View File

@ -30,24 +30,14 @@ 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;

View File

@ -46,11 +46,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
@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;
}

View File

@ -26,53 +26,21 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest {
@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 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 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 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 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 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 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 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 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);

View File

@ -31,24 +31,14 @@ 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;

View File

@ -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());
}
}

View File

@ -9,7 +9,6 @@ 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" })
@Configuration
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
@ -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;
}

View File

@ -10,7 +10,6 @@ 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" })
@Configuration
@ -21,9 +20,7 @@ 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;
}

View File

@ -21,9 +21,11 @@ public class Movie {
private int released;
private String tagline;
@Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List<Role> roles;
@Relationship(type = "ACTED_IN", direction = Relationship.INCOMING)
private List<Role> roles;
public Movie() { }
public Movie() {
}
public String getTitle() {
return title;
@ -57,5 +59,4 @@ public class Movie {
this.roles = roles;
}
}

View File

@ -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;
@ -21,7 +20,8 @@ public class Person {
@Relationship(type = "ACTED_IN")
private List<Movie> movies;
public Person() { }
public Person() {
}
public String getName() {
return name;

View File

@ -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;

View File

@ -20,5 +20,3 @@ public interface MovieRepository extends GraphRepository<Movie> {
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
List<Map<String, Object>> graph(@Param("limit") int limit);
}

View File

@ -4,7 +4,6 @@ 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<Person> {

View File

@ -82,8 +82,7 @@ public class MovieRepositoryTest {
@DirtiesContext
public void testFindAll() {
System.out.println("findAll");
Collection<Movie> result =
(Collection<Movie>) movieRepository.findAll();
Collection<Movie> result = (Collection<Movie>) 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<Movie> result =
movieRepository.findByTitleContaining(title);
Collection<Movie> 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<Movie> result =
(Collection<Movie>) movieRepository.findAll();
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
assertEquals(0, result.size());
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.spring.data.redis.queue;
public interface MessagePublisher {
void publish(final String message);

View File

@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher {
public RedisMessagePublisher() {
}
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate,
final ChannelTopic topic) {
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
this.redisTemplate = redisTemplate;
this.topic = topic;
}

View File

@ -9,8 +9,7 @@ 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();

View File

@ -226,8 +226,7 @@ public class ApplicationView {
// Set projections Row Count
public Long[] projectionRowCount() {
final Session session = HibernateUtil.getHibernateSession();
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount())
.list();
final List<Long> 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);
@ -239,8 +238,7 @@ public class ApplicationView {
// 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 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++) {

View File

@ -29,6 +29,7 @@ public class OrderDetail implements Serializable{
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
@ -50,9 +51,8 @@ public class OrderDetail implements Serializable{
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
}

View File

@ -60,7 +60,6 @@ public class UserLazy implements Serializable {
this.userId = userId;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}

View File

@ -23,10 +23,7 @@ public class HibernateUtil {
}
public static Session getHibernateSession() {
return new Configuration()
.configure("fetching.cfg.xml")
.buildSessionFactory()
.openSession();
return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession();
}
}

View File

@ -16,9 +16,7 @@ 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)

View File

@ -49,8 +49,7 @@ public class HibernateCriteriaTest {
@Test
public void testNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null")
.list();
final List<Item> 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();
@ -62,8 +61,7 @@ public class HibernateCriteriaTest {
@Test
public void testIsNotNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNotNullDescItemsList = session
.createQuery("From Item where itemDescription is not null").list();
final List<Item> 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();
@ -76,8 +74,7 @@ public class HibernateCriteriaTest {
@Test
public void testAverageProjection() {
final Session session = HibernateUtil.getHibernateSession();
final List<Double> expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item")
.list();
final List<Double> 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++) {
@ -103,8 +100,7 @@ public class HibernateCriteriaTest {
@Test
public void testOrCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedOrCritItemsList = session
.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list();
final List<Item> 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();
@ -116,8 +112,7 @@ public class HibernateCriteriaTest {
@Test
public void testAndCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedAndCritItemsList = session
.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list();
final List<Item> 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();
@ -129,8 +124,7 @@ public class HibernateCriteriaTest {
@Test
public void testMultiCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedMultiCritItemsList = session
.createQuery("From Item where itemDescription is null and itemName like'chair%'").list();
final List<Item> 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();
@ -142,8 +136,7 @@ public class HibernateCriteriaTest {
@Test
public void testSortCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedSortCritItemsList = session
.createQuery("From Item order by itemName asc, itemPrice desc").list();
final List<Item> 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();
@ -179,8 +172,7 @@ public class HibernateCriteriaTest {
@Test
public void betweenCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200")
.list();
final List<Item> 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();

View File

@ -13,7 +13,6 @@ import static org.junit.Assert.assertTrue;
public class HibernateFetchingTest {
// this loads sample data in the database
@Before
public void addFecthingTestData() {

View File

@ -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

View File

@ -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<Foo> 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<Foo> 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<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) {

View File

@ -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");
}

View File

@ -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");
}

View File

@ -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));
}
}

View File

@ -22,7 +22,6 @@ public class MainController {
return "index";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listTutorialsPage(Model model) {
List<Tutorial> list = tutService.listTutorials();
@ -38,5 +37,4 @@ public class MainController {
this.tutService = tutService;
}
}

View File

@ -10,9 +10,6 @@ import java.util.List;
public class TutorialsService implements ITutorialsService {
public List<Tutorial> listTutorials() {
return Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
);
return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
}
}

View File

@ -39,7 +39,6 @@ public class DataContentControllerTest {
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

View File

@ -9,7 +9,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
public class TestConfig {
@Bean
public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
@ -27,6 +26,4 @@ public class TestConfig {
return velocityConfigurer;
}
}

View File

@ -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.<br>This request was mapped" +
" using SimpleUrlHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
return model;
}

View File

@ -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.<br>This request was mapped" +
" using ControllerClassNameHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using ControllerClassNameHandlerMapping.");
return model;
}

View File

@ -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.<br>This request was mapped" +
" using BeanNameUrlHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using BeanNameUrlHandlerMapping.");
return model;
}

View File

@ -33,8 +33,7 @@ public class PersonController {
}
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result,
final ModelMap modelMap, final Model model) {
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) {
validator.validate(person, result);

View File

@ -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.<br>This request was mapped" +
" using SimpleUrlHandlerMapping.");
model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
return model;
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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();

View File

@ -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);

View File

@ -4,10 +4,12 @@
package org.baeldung.web.dto;
public final class FooProtos {
private FooProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
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 {
@ -16,6 +18,7 @@ public final class FooProtos {
* <code>required int64 id = 1;</code>
*/
boolean hasId();
/**
* <code>required int64 id = 1;</code>
*/
@ -25,21 +28,22 @@ public final class FooProtos {
* <code>required string name = 2;</code>
*/
boolean hasName();
/**
* <code>required string name = 2;</code>
*/
java.lang.String getName();
/**
* <code>required string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
com.google.protobuf.ByteString getNameBytes();
}
/**
* Protobuf type {@code baeldung.Foo}
*/
public static final class Foo extends
com.google.protobuf.GeneratedMessage implements
public static final class Foo extends com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:baeldung.Foo)
FooOrBuilder {
// Use Foo.newBuilder() to construct.
@ -47,9 +51,13 @@ public final class FooProtos {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private Foo(boolean noInit) {
this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private static final Foo defaultInstance;
public static Foo getDefaultInstance() {
return defaultInstance;
}
@ -59,19 +67,16 @@ public final class FooProtos {
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
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 {
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();
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
@ -81,8 +86,7 @@ public final class FooProtos {
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
@ -103,31 +107,23 @@ public final class FooProtos {
} 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);
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() {
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);
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<Foo> PARSER =
new com.google.protobuf.AbstractParser<Foo>() {
public Foo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
public static com.google.protobuf.Parser<Foo> PARSER = new com.google.protobuf.AbstractParser<Foo>() {
public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return new Foo(input, extensionRegistry);
}
};
@ -140,12 +136,14 @@ public final class FooProtos {
private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private long id_;
/**
* <code>required int64 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 id = 1;</code>
*/
@ -155,12 +153,14 @@ public final class FooProtos {
public static final int NAME_FIELD_NUMBER = 2;
private java.lang.Object name_;
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
@ -169,8 +169,7 @@ public final class FooProtos {
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
@ -178,16 +177,14 @@ public final class FooProtos {
return s;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
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);
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
@ -199,11 +196,15 @@ public final class FooProtos {
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 (isInitialized == 1)
return true;
if (isInitialized == 0)
return false;
if (!hasId()) {
memoizedIsInitialized = 0;
@ -217,8 +218,7 @@ public final class FooProtos {
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt64(1, id_);
@ -230,18 +230,18 @@ public final class FooProtos {
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
if (size != -1)
return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, id_);
size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getNameBytes());
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
@ -249,95 +249,86 @@ public final class FooProtos {
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
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 {
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 {
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 {
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 {
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 {
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 {
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 Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
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); }
public Builder toBuilder() {
return newBuilder(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code baeldung.Foo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:baeldung.Foo)
org.baeldung.web.dto.FooProtos.FooOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
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);
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()
@ -345,15 +336,16 @@ public final class FooProtos {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
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();
}
@ -371,8 +363,7 @@ public final class FooProtos {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
}
@ -415,7 +406,8 @@ public final class FooProtos {
}
public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) {
if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this;
if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance())
return this;
if (other.hasId()) {
setId(other.getId());
}
@ -440,10 +432,7 @@ public final class FooProtos {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
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);
@ -457,21 +446,25 @@ public final class FooProtos {
}
return this;
}
private int bitField0_;
private long id_;
/**
* <code>required int64 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 id = 1;</code>
*/
public long getId() {
return id_;
}
/**
* <code>required int64 id = 1;</code>
*/
@ -481,6 +474,7 @@ public final class FooProtos {
onChanged();
return this;
}
/**
* <code>required int64 id = 1;</code>
*/
@ -492,20 +486,21 @@ public final class FooProtos {
}
private java.lang.Object name_ = "";
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
@ -515,27 +510,25 @@ public final class FooProtos {
return (java.lang.String) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
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);
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public Builder setName(
java.lang.String value) {
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
@ -544,6 +537,7 @@ public final class FooProtos {
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
@ -553,11 +547,11 @@ public final class FooProtos {
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
@ -578,42 +572,25 @@ public final class FooProtos {
// @@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;
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() {
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
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) {
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", });
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)

View File

@ -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());
}
}

View File

@ -51,9 +51,7 @@ public class MyUserDetailsService implements UserDetailsService {
private User createUser(final String username, final String password, final List<SecurityRole> roles) {
logger.info("Create user " + username);
final List<GrantedAuthority> authorities = roles.stream()
.map(role -> new SimpleGrantedAuthority(role.toString()))
.collect(Collectors.toList());
final List<GrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList());
return new User(username, password, true, true, true, true, authorities);
}

View File

@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @formatter:on
}
}

View File

@ -24,15 +24,13 @@ public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
* Executed before actual handler is executed
**/
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
throws Exception {
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());
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();
@ -47,8 +45,7 @@ public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
* Executed before after handler is executed
**/
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView model) throws Exception {
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);

View File

@ -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);

View File

@ -47,8 +47,7 @@ public class SessionTimerInterceptorTest {
*/
@Test
public void testInterceptors() throws Exception {
HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn()
.getRequest().getSession();
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());
}

View File

@ -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());
}
}