formatting work
This commit is contained in:
parent
eb7650eead
commit
856be0a08a
|
@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringE
|
|||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -11,7 +11,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
|||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" })
|
||||
@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" })
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
|
|
|
@ -7,9 +7,9 @@ import org.springframework.web.bind.annotation.PathVariable;
|
|||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class RestController{
|
||||
public class RestController {
|
||||
|
||||
@GetMapping(value="/student/{studentId}")
|
||||
@GetMapping(value = "/student/{studentId}")
|
||||
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
|
||||
Student student = new Student();
|
||||
student.setName("Peter");
|
||||
|
|
|
@ -22,12 +22,12 @@ public class Student {
|
|||
}
|
||||
|
||||
@Override
|
||||
public int hashCode(){
|
||||
public int hashCode() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj){
|
||||
return this.name.equals(((Student)obj).getName());
|
||||
public boolean equals(Object obj) {
|
||||
return this.name.equals(((Student) obj).getName());
|
||||
}
|
||||
}
|
|
@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
|
|||
super();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
||||
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
||||
|
|
|
@ -11,7 +11,6 @@ public class Foo {
|
|||
|
||||
private static final AtomicInteger instanceCount = new AtomicInteger(0);
|
||||
|
||||
|
||||
private final int instanceNum;
|
||||
|
||||
public Foo() {
|
||||
|
|
|
@ -18,10 +18,9 @@ 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 )
|
||||
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
|
||||
public class ControllerAnnotationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
@ -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();
|
||||
|
||||
|
|
|
@ -19,7 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration({"classpath:test-mvc.xml"})
|
||||
@ContextConfiguration({ "classpath:test-mvc.xml" })
|
||||
public class ControllerTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
@ -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();
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
|
|||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class})
|
||||
@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
|
||||
public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
|
||||
|
||||
@Autowired
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package org.baeldung.spring43.defaultmethods;
|
||||
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ public class FooService {
|
|||
@FormatterType("Foo")
|
||||
private Formatter formatter;
|
||||
|
||||
public String doStuff(){
|
||||
public String doStuff() {
|
||||
return formatter.format();
|
||||
}
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ import java.lang.annotation.Target;
|
|||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER})
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface FormatterType {
|
||||
|
||||
|
|
|
@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
|||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
|
||||
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooServiceTest {
|
||||
|
||||
@Autowired
|
||||
FooService fooService;
|
||||
|
||||
@Test
|
||||
public void whenFooFormatterType_thenReturnFoo(){
|
||||
public void whenFooFormatterType_thenReturnFoo() {
|
||||
Assert.assertEquals("foo", fooService.doStuff());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
|||
@Controller
|
||||
public class TestController {
|
||||
|
||||
@RequestMapping(value="/")
|
||||
public String welcome(Model model){
|
||||
@RequestMapping(value = "/")
|
||||
public String welcome(Model model) {
|
||||
return "index";
|
||||
}
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean;
|
|||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git"})
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
|
||||
public class CommitIdApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CommitIdApplication.class, args);
|
||||
|
@ -21,6 +21,3 @@ public class CommitIdApplication {
|
|||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -22,7 +22,7 @@ public class CommitInfoController {
|
|||
@RequestMapping("/commitId")
|
||||
public Map<String, String> getCommitId() {
|
||||
Map<String, String> 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;
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -69,7 +69,6 @@ public class SpringBootMailTest {
|
|||
return wiserMessage.getMimeMessage().getSubject();
|
||||
}
|
||||
|
||||
|
||||
private SimpleMailMessage composeEmailMessage() {
|
||||
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
||||
mailMessage.setTo(userTo);
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -20,7 +20,7 @@ public class SpringDemoApplication extends SpringBootServletInitializer {
|
|||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate getRestTemplate(){
|
||||
public RestTemplate getRestTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
@ -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,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;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
@ -65,13 +74,13 @@ public class Person {
|
|||
@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();
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService {
|
|||
public List<Person> findAll() {
|
||||
List<Person> people = new ArrayList<Person>();
|
||||
Iterator<Person> it = repo.findAll().iterator();
|
||||
while(it.hasNext()) {
|
||||
while (it.hasNext()) {
|
||||
people.add(it.next());
|
||||
}
|
||||
return people;
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
|
@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService {
|
|||
public List<Student> findAll() {
|
||||
List<Student> people = new ArrayList<Student>();
|
||||
Iterator<Student> it = repo.findAll().iterator();
|
||||
while(it.hasNext()) {
|
||||
while (it.hasNext()) {
|
||||
people.add(it.next());
|
||||
}
|
||||
return people;
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository;
|
|||
|
||||
public interface CampusRepository extends CrudRepository<Campus, String> {
|
||||
|
||||
@View(designDocument="campus", viewName="byName")
|
||||
@View(designDocument = "campus", viewName = "byName")
|
||||
Set<Campus> findByName(String name);
|
||||
|
||||
@Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation")
|
||||
@Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation")
|
||||
Set<Campus> findByLocationNear(Point point, Distance distance);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService {
|
|||
public Set<Campus> findAll() {
|
||||
Set<Campus> campuses = new HashSet<>();
|
||||
Iterator<Campus> it = repo.findAll().iterator();
|
||||
while(it.hasNext()) {
|
||||
while (it.hasNext()) {
|
||||
campuses.add(it.next());
|
||||
}
|
||||
return campuses;
|
||||
|
|
|
@ -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<Person> findAll() {
|
||||
List<Person> people = new ArrayList<Person>();
|
||||
Iterator<Person> it = repo.findAll().iterator();
|
||||
while(it.hasNext()) {
|
||||
while (it.hasNext()) {
|
||||
people.add(it.next());
|
||||
}
|
||||
return people;
|
||||
|
|
|
@ -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<Student> findAll() {
|
||||
List<Student> people = new ArrayList<Student>();
|
||||
Iterator<Student> it = repo.findAll().iterator();
|
||||
while(it.hasNext()) {
|
||||
while (it.hasNext()) {
|
||||
people.add(it.next());
|
||||
}
|
||||
return people;
|
||||
|
|
|
@ -12,7 +12,7 @@ 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<String> NODE_LIST = Arrays.asList("localhost");
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
@ -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";
|
||||
|
@ -133,8 +123,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
|||
|
||||
private boolean resultContains(List<Student> 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<Student> 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<Student> 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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
@ -60,7 +56,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
|||
try {
|
||||
baseMapping.mapEntity(Campus.class, campusTemplate());
|
||||
} catch (Exception e) {
|
||||
//custom Exception handling
|
||||
// custom Exception handling
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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;
|
||||
|
@ -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";
|
||||
|
@ -135,8 +125,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
|||
|
||||
private boolean resultContains(List<Student> 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<Student> 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<Student> 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;
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
@ -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<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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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<Movie> movies;
|
||||
|
||||
public Person() { }
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository<Movie> {
|
|||
Collection<Movie> 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<Map<String,Object>> graph(@Param("limit") int limit);
|
||||
List<Map<String, Object>> graph(@Param("limit") int limit);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -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> {
|
||||
|
||||
|
|
|
@ -15,31 +15,31 @@ public class MovieService {
|
|||
MovieRepository movieRepository;
|
||||
|
||||
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
|
||||
List<Map<String,Object>> nodes = new ArrayList<Map<String,Object>>();
|
||||
List<Map<String,Object>> rels= new ArrayList<Map<String,Object>>();
|
||||
int i=0;
|
||||
List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
|
||||
List<Map<String, Object>> rels = new ArrayList<Map<String, Object>>();
|
||||
int i = 0;
|
||||
while (result.hasNext()) {
|
||||
Map<String, Object> 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<String, Object> actor = map("title", name,"label","actor");
|
||||
Map<String, Object> 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<String, Object> map(String key1, Object value1, String key2, Object value2) {
|
||||
Map<String, Object> result = new HashMap<String,Object>(2);
|
||||
result.put(key1,value1);
|
||||
result.put(key2,value2);
|
||||
Map<String, Object> result = new HashMap<String, Object>(2);
|
||||
result.put(key1, value1);
|
||||
result.put(key2, value2);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.spring.data.redis.queue;
|
||||
|
||||
|
||||
public interface MessagePublisher {
|
||||
|
||||
void publish(final String message);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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++) {
|
||||
|
|
|
@ -5,17 +5,17 @@ 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")
|
||||
@Column(name = "ORDER_ID")
|
||||
private Long orderId;
|
||||
|
||||
public OrderDetail(){
|
||||
public OrderDetail() {
|
||||
}
|
||||
|
||||
public OrderDetail(Date orderDate, String orderDesc) {
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -6,14 +6,14 @@ 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")
|
||||
@Column(name = "USER_ID")
|
||||
private Long userId;
|
||||
|
||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
|
||||
|
|
|
@ -6,14 +6,14 @@ 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")
|
||||
@Column(name = "USER_ID")
|
||||
private Long userId;
|
||||
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
|
||||
|
@ -60,7 +60,6 @@ public class UserLazy implements Serializable {
|
|||
this.userId = userId;
|
||||
}
|
||||
|
||||
|
||||
public Set<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
|
|
@ -8,9 +8,9 @@ public class HibernateUtil {
|
|||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static Session getHibernateSession(String fetchMethod) {
|
||||
//two config files are there
|
||||
//one with lazy loading enabled
|
||||
//another lazy = false
|
||||
// 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();
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -13,17 +13,16 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
public class HibernateFetchingTest {
|
||||
|
||||
|
||||
//this loads sample data in the database
|
||||
// this loads sample data in the database
|
||||
@Before
|
||||
public void addFecthingTestData(){
|
||||
public void addFecthingTestData() {
|
||||
FetchingAppView fav = new FetchingAppView();
|
||||
fav.createTestData();
|
||||
}
|
||||
|
||||
//testLazyFetching() tests the lazy loading
|
||||
//Since it lazily loaded so orderDetalSetLazy won't
|
||||
//be initialized
|
||||
// testLazyFetching() tests the lazy loading
|
||||
// Since it lazily loaded so orderDetalSetLazy won't
|
||||
// be initialized
|
||||
@Test
|
||||
public void testLazyFetching() {
|
||||
FetchingAppView fav = new FetchingAppView();
|
||||
|
@ -31,9 +30,9 @@ public class HibernateFetchingTest {
|
|||
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
|
||||
}
|
||||
|
||||
//testEagerFetching() tests the eager loading
|
||||
//Since it eagerly loaded so orderDetalSetLazy would
|
||||
//be initialized
|
||||
// testEagerFetching() tests the eager loading
|
||||
// Since it eagerly loaded so orderDetalSetLazy would
|
||||
// be initialized
|
||||
@Test
|
||||
public void testEagerFetching() {
|
||||
FetchingAppView fav = new FetchingAppView();
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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<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) {
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<Role> roles;
|
||||
|
|
|
@ -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";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value ="/list", method = RequestMethod.GET)
|
||||
@RequestMapping(value = "/list", method = RequestMethod.GET)
|
||||
public String listTutorialsPage(Model model) {
|
||||
List<Tutorial> list = tutService.listTutorials();
|
||||
model.addAttribute("tutorials", list);
|
||||
|
@ -38,5 +37,4 @@ public class MainController {
|
|||
this.tutService = tutService;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -39,7 +39,6 @@ public class DataContentControllerTest {
|
|||
@Before
|
||||
public void setUp() {
|
||||
|
||||
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
|
@ -55,7 +54,7 @@ public class DataContentControllerTest {
|
|||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -3,7 +3,7 @@ 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;
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -407,7 +398,7 @@ public final class FooProtos {
|
|||
|
||||
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);
|
||||
return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other);
|
||||
} else {
|
||||
super.mergeFrom(other);
|
||||
return this;
|
||||
|
@ -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_ ;
|
||||
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)
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
// @formatter:on
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue