diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..9c5cdb8f2d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "testgitrepo"] + path = testgitrepo + url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/ diff --git a/cdi/pom.xml b/cdi/pom.xml index 2a9d32188b..b771857938 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,52 +1,52 @@ - + 4.0.0 com.baeldung cdi 1.0-SNAPSHOT - - 4.3.1.RELEASE - + - - - junit - junit - 4.12 - - org.springframework spring-core ${spring.version} - org.springframework spring-context ${spring.version} - + + + org.aspectj + aspectjweaver + 1.8.9 + + + org.jboss.weld.se + weld-se-core + 2.3.5.Final + + + + junit + junit + 4.12 + test + org.springframework spring-test ${spring.version} test - - - org.aspectj - aspectjweaver - 1.8.9 - - - - org.jboss.weld.se - weld-se-core - 2.3.5.Final - + + + + 4.3.1.RELEASE + + \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/interceptor/Audited.java b/cdi/src/main/java/com/baeldung/interceptor/Audited.java index 4065450b09..3df4bef95e 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/Audited.java +++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java @@ -1,12 +1,14 @@ package com.baeldung.interceptor; -import javax.interceptor.InterceptorBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.interceptor.InterceptorBinding; + @InterceptorBinding -@Target( {ElementType.METHOD, ElementType.TYPE } ) -@Retention(RetentionPolicy.RUNTIME ) -public @interface Audited {} +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Audited { +} diff --git a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java index 46ab9b33c8..c62d9a4127 100644 --- a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java +++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java @@ -3,12 +3,13 @@ package com.baeldung.interceptor; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; -import java.lang.reflect.Method; -@Audited @Interceptor +@Audited +@Interceptor public class AuditedInterceptor { public static boolean calledBefore = false; public static boolean calledAfter = false; + @AroundInvoke public Object auditMethod(InvocationContext ctx) throws Exception { calledBefore = true; diff --git a/cdi/src/main/java/com/baeldung/service/SuperService.java b/cdi/src/main/java/com/baeldung/service/SuperService.java index e1e57a4e0d..e15f049342 100644 --- a/cdi/src/main/java/com/baeldung/service/SuperService.java +++ b/cdi/src/main/java/com/baeldung/service/SuperService.java @@ -5,6 +5,6 @@ import com.baeldung.interceptor.Audited; public class SuperService { @Audited public String deliverService(String uid) { - return uid; + return uid; } } diff --git a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java index 8c2ff2600b..e48039706d 100644 --- a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -1,26 +1,23 @@ package com.baeldung.spring.aspect; -import org.aspectj.lang.JoinPoint; +import java.util.List; + import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; -import javax.inject.Inject; -import java.util.List; - @Aspect public class SpringTestAspect { @Autowired private List accumulator; @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") - public Object advice(ProceedingJoinPoint jp) throws Throwable { + public Object auditMethod(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); - accumulator.add("Call to "+methodName); + accumulator.add("Call to " + methodName); Object obj = jp.proceed(); - accumulator.add("Method called successfully: "+methodName); + accumulator.add("Method called successfully: " + methodName); return obj; } } diff --git a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java index 6cfc8f8743..b30c4a1326 100644 --- a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java +++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java @@ -1,13 +1,14 @@ package com.baeldung.spring.configuration; -import com.baeldung.spring.aspect.SpringTestAspect; -import com.baeldung.spring.service.SpringSuperService; +import java.util.ArrayList; +import java.util.List; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; -import java.util.ArrayList; -import java.util.List; +import com.baeldung.spring.aspect.SpringTestAspect; +import com.baeldung.spring.service.SpringSuperService; @Configuration @EnableAspectJAutoProxy @@ -18,12 +19,12 @@ public class AppConfig { } @Bean - public SpringTestAspect springTestAspect(){ + public SpringTestAspect springTestAspect() { return new SpringTestAspect(); } @Bean - public List getAccumulator(){ + public List getAccumulator() { return new ArrayList(); } } diff --git a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java index 72dbd1c006..082eb2e0f8 100644 --- a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java +++ b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java @@ -1,7 +1,7 @@ package com.baeldung.spring.service; public class SpringSuperService { - public String getInfoFromService(String code){ + public String getInfoFromService(String code) { return code; } } diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java index d1b851c94f..3529a796d2 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -1,8 +1,5 @@ package com.baeldung.test; -import com.baeldung.interceptor.Audited; -import com.baeldung.interceptor.AuditedInterceptor; -import com.baeldung.service.SuperService; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.After; @@ -10,24 +7,21 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import javax.enterprise.inject.spi.BeanManager; -import javax.enterprise.inject.spi.InterceptionType; -import javax.enterprise.inject.spi.Interceptor; -import javax.enterprise.util.AnnotationLiteral; - -import static javafx.beans.binding.Bindings.select; +import com.baeldung.interceptor.AuditedInterceptor; +import com.baeldung.service.SuperService; public class TestInterceptor { Weld weld; WeldContainer container; + @Before - public void init(){ + public void init() { weld = new Weld(); container = weld.initialize(); } @After - public void shutdown(){ + public void shutdown() { weld.shutdown(); } @@ -36,7 +30,9 @@ public class TestInterceptor { SuperService superService = container.select(SuperService.class).get(); String code = "123456"; superService.deliverService(code); + Assert.assertTrue(AuditedInterceptor.calledBefore); Assert.assertTrue(AuditedInterceptor.calledAfter); } + } diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java index b5aedd4b76..1f3a8d83e3 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java @@ -1,25 +1,21 @@ package com.baeldung.test; -import com.baeldung.spring.configuration.AppConfig; -import com.baeldung.spring.service.SpringSuperService; +import static org.hamcrest.CoreMatchers.is; + +import java.util.List; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import javax.inject.Inject; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; +import com.baeldung.spring.configuration.AppConfig; +import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {AppConfig.class}) +@ContextConfiguration(classes = { AppConfig.class }) public class TestSpringInterceptor { @Autowired SpringSuperService springSuperService; @@ -28,11 +24,11 @@ public class TestSpringInterceptor { private List accumulator; @Test - public void givenService_whenServiceAndAspectExecuted_thenOk(){ + public void givenService_whenServiceAndAspectExecuted_thenOk() { String code = "123456"; String result = springSuperService.getInfoFromService(code); Assert.assertThat(accumulator.size(), is(2)); - Assert.assertThat(accumulator.get(0),is("Call to getInfoFromService")); - Assert.assertThat(accumulator.get(1),is("Method called successfully: getInfoFromService")); + Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService")); + Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService")); } } diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java new file mode 100644 index 0000000000..5363a73afa --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -0,0 +1,209 @@ +package com.baeldung.completablefuture; + +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class CompletableFutureTest { + + @Test + public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { + + Future completableFuture = calculateAsync(); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + public Future calculateAsync() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); + + return completableFuture; + } + + @Test + public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { + + Future completableFuture = CompletableFuture.completedFuture("Hello"); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + + public Future calculateAsyncWithCancellation() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); + + return completableFuture; + } + + + @Test(expected = CancellationException.class) + public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { + + Future future = calculateAsyncWithCancellation(); + future.get(); + + } + + @Test + public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { + + CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); + + assertEquals("Hello", future.get()); + + } + + @Test + public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); + + future.get(); + + } + + @Test + public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); + + future.get(); + + } + + @Test + public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApply(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + + @Test + public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> s1 + s2); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> System.out.println(s1 + s2)); + + } + + @Test + public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { + + CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); + CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); + CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); + + CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3); + + // ... + + combinedFuture.get(); + + assertTrue(future1.isDone()); + assertTrue(future2.isDone()); + assertTrue(future3.isDone()); + + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); + + assertEquals("Hello Beautiful World", combined); + + } + + @Test + public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { + + String name = null; + + // ... + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + if (name == null) { + throw new RuntimeException("Computation error!"); + } + return "Hello, " + name; + }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); + + assertEquals("Hello, Stranger!", completableFuture.get()); + + } + + @Test(expected = ExecutionException.class) + public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = new CompletableFuture<>(); + + // ... + + completableFuture.completeExceptionally(new RuntimeException("Calculation failed!")); + + // ... + + completableFuture.get(); + + } + + @Test + public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + +} \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index ef443ebd15..7867bbb955 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -12,9 +12,9 @@ org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE - + @@ -33,60 +33,68 @@ 2.6 2.19.1 2.7 - + 1.3.16 + 1.4.3 + 1.4.0.RELEASE - + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-aop - com.netflix.hystrix hystrix-core ${hystrix-core.version} - com.netflix.hystrix hystrix-metrics-event-stream - 1.3.16 + ${hystrix-metrics-event-stream.version} - - - - + ${hystrix-dashboard.version} + com.netflix.rxjava rxjava-core ${rxjava-core.version} - org.hamcrest hamcrest-all ${hamcrest-all.version} test - junit junit ${junit.version} test - + + org.springframework + spring-test + test + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter-test.version} + test + diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java index c2e4af8edb..3a650c2f4f 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java @@ -17,6 +17,28 @@ public class HystrixAspect { private HystrixCommandProperties.Setter commandProperties; private HystrixThreadPoolProperties.Setter threadPoolProperties; + @Value("${remoteservice.command.execution.timeout}") + private int executionTimeout; + + @Value("${remoteservice.command.sleepwindow}") + private int sleepWindow; + + @Value("${remoteservice.command.threadpool.maxsize}") + private int maxThreadCount; + + @Value("${remoteservice.command.threadpool.coresize}") + private int coreThreadCount; + + @Value("${remoteservice.command.task.queue.size}") + private int queueCount; + + @Value("${remoteservice.command.group.key}") + private String groupKey; + + @Value("${remoteservice.command.key}") + private String key; + + @Around("@annotation(com.baeldung.hystrix.HystrixCircuitBreaker)") public Object circuitBreakerAround(final ProceedingJoinPoint aJoinPoint) { return new RemoteServiceCommand(config, aJoinPoint).execute(); @@ -31,7 +53,7 @@ public class HystrixAspect { this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout); this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow); - this.threadPoolProperties= HystrixThreadPoolProperties.Setter(); + this.threadPoolProperties = HystrixThreadPoolProperties.Setter(); this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount); this.config.andCommandPropertiesDefaults(commandProperties); @@ -58,24 +80,4 @@ public class HystrixAspect { } } - @Value("${remoteservice.command.execution.timeout}") - private int executionTimeout; - - @Value("${remoteservice.command.sleepwindow}") - private int sleepWindow; - - @Value("${remoteservice.command.threadpool.maxsize}") - private int maxThreadCount; - - @Value("${remoteservice.command.threadpool.coresize}") - private int coreThreadCount; - - @Value("${remoteservice.command.task.queue.size}") - private int queueCount; - - @Value("${remoteservice.command.group.key}") - private String groupKey; - - @Value("${remoteservice.command.key}") - private String key; } diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java index a8ca0adef2..69d9e30ff8 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java @@ -10,8 +10,13 @@ public class HystrixController { @Autowired private SpringExistingClient client; - @RequestMapping("/") - public String index() throws InterruptedException{ - return client.invokeRemoteService(); + @RequestMapping("/withHystrix") + public String withHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithHystrix(); + } + + @RequestMapping("/withOutHystrix") + public String withOutHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithOutHystrix(); } } diff --git a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java index fab8e611d4..525c7b4785 100644 --- a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java @@ -10,8 +10,11 @@ public class SpringExistingClient { private int remoteServiceDelay; @HystrixCircuitBreaker - public String invokeRemoteService() throws InterruptedException{ + public String invokeRemoteServiceWithHystrix() throws InterruptedException{ return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); } + public String invokeRemoteServiceWithOutHystrix() throws InterruptedException{ + return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); + } } diff --git a/hystrix/src/main/resources/application.properties b/hystrix/src/main/resources/application.properties index abde975550..50c241d03f 100644 --- a/hystrix/src/main/resources/application.properties +++ b/hystrix/src/main/resources/application.properties @@ -5,4 +5,4 @@ remoteservice.command.threadpool.coresize=5 remoteservice.command.threadpool.maxsize=10 remoteservice.command.task.queue.size=5 remoteservice.command.sleepwindow=5000 -remoteservice.timeout=5000 \ No newline at end of file +remoteservice.timeout=15000 \ No newline at end of file diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java new file mode 100644 index 0000000000..a5303e6c0d --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeShortCircuitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixThreadPoolProperties; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.junit.runners.MethodSorters; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@FixMethodOrder(MethodSorters.JVM) +public class HystrixTimeShortCircuitTest { + + private HystrixCommand.Setter config; + private HystrixCommandProperties.Setter commandProperties; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + commandProperties = HystrixCommandProperties.Setter(); + config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + } + + @Test + public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() + throws InterruptedException { + + commandProperties.withExecutionTimeoutInMilliseconds(1000); + + commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000); + commandProperties.withExecutionIsolationStrategy( + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + commandProperties.withCircuitBreakerEnabled(true); + commandProperties.withCircuitBreakerRequestVolumeThreshold(1); + + config.andCommandPropertiesDefaults(commandProperties); + + config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() + .withMaxQueueSize(1) + .withCoreSize(1) + .withQueueSizeRejectionThreshold(1)); + + assertThat(this.invokeRemoteService(10000), equalTo(null)); + assertThat(this.invokeRemoteService(10000), equalTo(null)); + Thread.sleep(5000); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + } + + String invokeRemoteService(long timeout) throws InterruptedException { + String response = null; + try { + response = new RemoteServiceTestCommand(config, + new RemoteServiceTestSimulator(timeout)).execute(); + } catch (HystrixRuntimeException ex) { + System.out.println("ex = " + ex); + } + return response; + } + +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index 34eb334b32..878d7808a0 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -5,18 +5,18 @@ import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.exception.HystrixRuntimeException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.*; import org.junit.rules.ExpectedException; +import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +@FixMethodOrder(MethodSorters.JVM) public class HystrixTimeoutTest { private HystrixCommand.Setter config; - private HystrixCommandProperties.Setter commandProperties ; + private HystrixCommandProperties.Setter commandProperties; @Rule @@ -26,37 +26,45 @@ public class HystrixTimeoutTest { public void setup() { commandProperties = HystrixCommandProperties.Setter(); config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); } @Test - public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){ + public void givenInputBobAndDefaultSettings_whenExecuted_thenReturnHelloBob(){ assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @Test - public void givenServiceTimeoutEqualTo100_andDefaultSettings_thenReturnSuccess() throws InterruptedException { - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success")); + public void givenSvcTimeoutOf100AndDefaultSettings_whenExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), + equalTo("Success")); } @Test - public void givenServiceTimeoutEqualTo10000_andDefaultSettings_thenExpectHRE() throws InterruptedException { + public void givenSvcTimeoutOf10000AndDefaultSettings__whenExecuted_thenExpectHRE() throws InterruptedException { exception.expect(HystrixRuntimeException.class); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); } @Test - public void givenServiceTimeoutEqualTo500_andExecutionTimeoutEqualTo10000_thenReturnSuccess() + public void givenSvcTimeoutOf5000AndExecTimeoutOf10000__whenExecuted_thenReturnSuccess() throws InterruptedException { commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } @Test - public void givenServiceTimeoutEqualTo15000_andExecutionTimeoutEqualTo5000_thenExpectHRE() + public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() throws InterruptedException { exception.expect(HystrixRuntimeException.class); commandProperties.withExecutionTimeoutInMilliseconds(5_000); @@ -65,7 +73,7 @@ public class HystrixTimeoutTest { } @Test - public void givenServiceTimeoutEqual_andExecutionTimeout_andThreadPool_thenReturnSuccess() + public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() throws InterruptedException { commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); @@ -73,49 +81,8 @@ public class HystrixTimeoutTest { .withMaxQueueSize(10) .withCoreSize(3) .withQueueSizeRejectionThreshold(10)); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), equalTo("Success")); } - - @Test - public void givenCircuitBreakerSetup_thenReturnSuccess() throws InterruptedException { - - commandProperties.withExecutionTimeoutInMilliseconds(1000); - - commandProperties.withCircuitBreakerSleepWindowInMilliseconds(4000); - commandProperties.withExecutionIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); - commandProperties.withCircuitBreakerEnabled(true); - commandProperties.withCircuitBreakerRequestVolumeThreshold(1); - - config.andCommandPropertiesDefaults(commandProperties); - - config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() - .withMaxQueueSize(1) - .withCoreSize(1) - .withQueueSizeRejectionThreshold(1)); - - assertThat(this.invokeRemoteService(10000), equalTo(null)); - assertThat(this.invokeRemoteService(10000), equalTo(null)); - Thread.sleep(5000); - - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); - } - - public String invokeRemoteService(long timeout) throws InterruptedException{ - String response = null; - try{ - response = new RemoteServiceTestCommand(config, - new RemoteServiceTestSimulator(timeout)).execute(); - }catch(HystrixRuntimeException ex){ - System.out.println("ex = " + ex); - } - return response; - } - } diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java new file mode 100644 index 0000000000..004314b0ed --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppConfig.class) +public class SpringAndHystrixIntegrationTest { + + @Autowired + private HystrixController hystrixController; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void givenTimeOutOf15000_whenClientCalledWithHystrix_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + hystrixController.withHystrix(); + } + + @Test + public void givenTimeOutOf15000_whenClientCalledWithOutHystrix_thenExpectSuccess() throws InterruptedException { + assertThat(hystrixController.withOutHystrix(), equalTo("Success")); + } + +} diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml new file mode 100644 index 0000000000..8a28ae9511 --- /dev/null +++ b/mapstruct/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + mapstruct + mapstruct + com.baeldung + 1.0 + jar + + + 1.0.0.Final + + + + org.mapstruct + mapstruct-jdk8 + ${org.mapstruct.version} + + + junit + junit + 4.12 + test + + + + mapstruct + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + diff --git a/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java new file mode 100644 index 0000000000..67b9ffc024 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/dto/EmployeeDTO.java @@ -0,0 +1,42 @@ +package org.baeldung.dto; + +public class EmployeeDTO { + + private int employeeId; + private String employeeName; + private int divisionId; + private String divisionName; + + public int getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(int employeeId) { + this.employeeId = employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public int getDivisionId() { + return divisionId; + } + + public void setDivisionId(int divisionId) { + this.divisionId = divisionId; + } + + public String getDivisionName() { + return divisionName; + } + + public void setDivisionName(String divisionName) { + this.divisionName = divisionName; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java new file mode 100644 index 0000000000..fc0c75dea3 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/dto/SimpleSource.java @@ -0,0 +1,24 @@ +package org.baeldung.dto; + +public class SimpleSource { + + private String name; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/Division.java b/mapstruct/src/main/java/org/baeldung/entity/Division.java new file mode 100644 index 0000000000..04f1ab2c23 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/Division.java @@ -0,0 +1,33 @@ +package org.baeldung.entity; + +public class Division { + + public Division() { + } + + public Division(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/Employee.java b/mapstruct/src/main/java/org/baeldung/entity/Employee.java new file mode 100644 index 0000000000..55599a17f9 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/Employee.java @@ -0,0 +1,33 @@ +package org.baeldung.entity; + +public class Employee { + + private int id; + private String name; + private Division division; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Division getDivision() { + return division; + } + + public void setDivision(Division division) { + this.division = division; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java new file mode 100644 index 0000000000..901257c11b --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/entity/SimpleDestination.java @@ -0,0 +1,24 @@ +package org.baeldung.entity; + +public class SimpleDestination { + + private String name; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java new file mode 100644 index 0000000000..28faffec45 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/EmployeeMapper.java @@ -0,0 +1,27 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.EmployeeDTO; +import org.baeldung.entity.Employee; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +@Mapper +public interface EmployeeMapper { + + @Mappings({ + @Mapping(target="divisionId",source="entity.division.id"), + @Mapping(target="divisionName",source="entity.division.name"), + @Mapping(target="employeeId",source="entity.id"), + @Mapping(target="employeeName",source="entity.name") + }) + EmployeeDTO employeeToEmployeeDTO(Employee entity); + + @Mappings({ + @Mapping(target="id",source="dto.employeeId"), + @Mapping(target="name",source="dto.employeeName"), + @Mapping(target="division",expression="java(new org.baeldung.entity.Division(dto.getDivisionId(),dto.getDivisionName()))") + }) + Employee employeeDTOtoEmployee(EmployeeDTO dto); + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java new file mode 100644 index 0000000000..f3210288d2 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationMapper.java @@ -0,0 +1,13 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.mapstruct.Mapper; + +@Mapper +public interface SimpleSourceDestinationMapper { + + SimpleDestination sourceToDestination(SimpleSource source); + SimpleSource destinationToSource(SimpleDestination destination); + +} diff --git a/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java new file mode 100644 index 0000000000..2077eabf51 --- /dev/null +++ b/mapstruct/src/main/java/org/baeldung/mapper/SimpleSourceDestinationSpringMapper.java @@ -0,0 +1,13 @@ +package org.baeldung.mapper; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.mapstruct.Mapper; + +@Mapper(componentModel="spring") +public interface SimpleSourceDestinationSpringMapper { + + SimpleDestination sourceToDestination(SimpleSource source); + SimpleSource destinationToSource(SimpleDestination destination); + +} diff --git a/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java new file mode 100644 index 0000000000..0433013f2e --- /dev/null +++ b/mapstruct/src/test/java/org/baeldung/mapper/EmployeeMapperTest.java @@ -0,0 +1,48 @@ +package org.baeldung.mapper; + +import static org.junit.Assert.*; + +import org.baeldung.dto.EmployeeDTO; +import org.baeldung.entity.Division; +import org.baeldung.entity.Employee; +import org.junit.Test; +import org.mapstruct.factory.Mappers; + +public class EmployeeMapperTest { + + @Test + public void givenEmployeeDTOtoEmployee_whenMaps_thenCorrect(){ + EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); + + EmployeeDTO dto = new EmployeeDTO(); + dto.setDivisionId(1); + dto.setDivisionName("IT Division"); + dto.setEmployeeId(1); + dto.setEmployeeName("John"); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + + assertEquals(dto.getDivisionId(), entity.getDivision().getId()); + assertEquals(dto.getDivisionName(), entity.getDivision().getName()); + assertEquals(dto.getEmployeeId(),entity.getId()); + assertEquals(dto.getEmployeeName(),entity.getName()); + } + + @Test + public void givenEmployeetoEmployeeDTO_whenMaps_thenCorrect(){ + EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); + + Employee entity = new Employee(); + entity.setDivision(new Division(1,"IT Division")); + entity.setId(1); + entity.setName("John"); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + + assertEquals(dto.getDivisionId(), entity.getDivision().getId()); + assertEquals(dto.getDivisionName(), entity.getDivision().getName()); + assertEquals(dto.getEmployeeId(),entity.getId()); + assertEquals(dto.getEmployeeName(),entity.getName()); + } + +} diff --git a/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java new file mode 100644 index 0000000000..a7e3b05dc6 --- /dev/null +++ b/mapstruct/src/test/java/org/baeldung/mapper/SimpleSourceDestinationMapperTest.java @@ -0,0 +1,44 @@ +package org.baeldung.mapper; + +import static org.junit.Assert.*; + +import org.baeldung.dto.SimpleSource; +import org.baeldung.entity.SimpleDestination; +import org.junit.Test; +import org.mapstruct.factory.Mappers; + +public class SimpleSourceDestinationMapperTest { + + @Test + public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() { + SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers + .getMapper(SimpleSourceDestinationMapper.class); + + SimpleSource simpleSource = new SimpleSource(); + simpleSource.setName("SourceName"); + simpleSource.setDescription("SourceDescription"); + + SimpleDestination destination = + simpleSourceDestinationMapper.sourceToDestination(simpleSource); + + assertEquals(simpleSource.getName(), destination.getName()); + assertEquals(simpleSource.getDescription(), destination.getDescription()); + } + + @Test + public void givenSimpleDestinationToSourceDestination_whenMaps_thenCorrect() { + SimpleSourceDestinationMapper simpleSourceDestinationMapper = Mappers + .getMapper(SimpleSourceDestinationMapper.class); + + SimpleDestination destination = new SimpleDestination(); + destination.setName("DestinationName"); + destination.setDescription("DestinationDescription"); + + SimpleSource source = + simpleSourceDestinationMapper.destinationToSource(destination); + + assertEquals(destination.getName(), source.getName()); + assertEquals(destination.getDescription(), source.getDescription()); + } + +} diff --git a/pom.xml b/pom.xml index 992ce44633..b493b0c48e 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ apache-cxf apache-fop autovalue-tutorial + cdi core-java core-java-8 couchbase-sdk-intro @@ -82,7 +83,7 @@ spring-quartz spring-spel spring-rest - spring-rest-angular-pagination + spring-rest-angular spring-rest-docs spring-cloud-config spring-cloud-eureka diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 25a45d9bae..c70d9d75fc 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -130,6 +130,13 @@ test + + org.assertj + assertj-core + 3.5.1 + test + + org.hamcrest hamcrest-core diff --git a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java index 2946ab0aa1..8503f75c8f 100644 --- a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java +++ b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java @@ -1,11 +1,11 @@ package org.baeldung.async; -import java.util.concurrent.Future; - import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; +import java.util.concurrent.Future; + @Component public class AsyncComponent { @@ -19,7 +19,7 @@ public class AsyncComponent { System.out.println("Execute method asynchronously " + Thread.currentThread().getName()); try { Thread.sleep(5000); - return new AsyncResult("hello world !!!!"); + return new AsyncResult<>("hello world !!!!"); } catch (final InterruptedException e) { } diff --git a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java index 80cb060c7e..8fde925fd8 100644 --- a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java +++ b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java @@ -1,5 +1,5 @@ package org.baeldung.profiles; public interface DatasourceConfig { - public void setup(); + void setup(); } diff --git a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java new file mode 100644 index 0000000000..d4334437f7 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java @@ -0,0 +1,33 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +@Scope(value = "prototype") +public class AllStrategiesExampleBean implements InitializingBean { + + private static final Logger LOG = Logger.getLogger(AllStrategiesExampleBean.class); + + public AllStrategiesExampleBean() { + LOG.info("Constructor"); + } + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info("InitializingBean"); + } + + @PostConstruct + public void postConstruct() { + LOG.info("PostConstruct"); + } + + public void init() { + LOG.info("init-method"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java new file mode 100644 index 0000000000..cea6b026d6 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InitMethodExampleBean.java @@ -0,0 +1,23 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.util.Arrays; + +@Component +@Scope(value = "prototype") +public class InitMethodExampleBean { + + private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class); + + @Autowired + private Environment environment; + + public void init() { + LOG.info(Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java new file mode 100644 index 0000000000..33b14864f3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InitializingBeanExampleBean.java @@ -0,0 +1,25 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.util.Arrays; + +@Component +@Scope(value = "prototype") +public class InitializingBeanExampleBean implements InitializingBean { + + private static final Logger LOG = Logger.getLogger(InitializingBeanExampleBean.class); + + @Autowired + private Environment environment; + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info(Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java new file mode 100644 index 0000000000..0b9c6f0c7d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/InvalidInitExampleBean.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Scope("prototype") +public class InvalidInitExampleBean { + + @Autowired + private Environment environment; + + public InvalidInitExampleBean() { + environment.getActiveProfiles(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java new file mode 100644 index 0000000000..2a7b3e26c7 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/LogicInConstructorExampleBean.java @@ -0,0 +1,25 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.util.Arrays; + +@Component +@Scope(value = "prototype") +public class LogicInConstructorExampleBean { + + private static final Logger LOG = Logger.getLogger(LogicInConstructorExampleBean.class); + + private final Environment environment; + + @Autowired + public LogicInConstructorExampleBean(Environment environment) { + this.environment = environment; + + LOG.info(Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java new file mode 100644 index 0000000000..4cabaad4df --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/PostConstructExampleBean.java @@ -0,0 +1,25 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.Arrays; + +@Component +@Scope(value = "prototype") +public class PostConstructExampleBean { + + private static final Logger LOG = Logger.getLogger(PostConstructExampleBean.class); + + @Autowired + private Environment environment; + + @PostConstruct + public void init() { + LOG.info(Arrays.asList(environment.getDefaultProfiles())); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java new file mode 100644 index 0000000000..12854e1be5 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/SpringStartupConfig.java @@ -0,0 +1,9 @@ +package org.baeldung.startup; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("org.baeldung.startup") +public class SpringStartupConfig { +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java new file mode 100644 index 0000000000..32a63f0c1a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/StartupApplicationListenerExample.java @@ -0,0 +1,20 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class StartupApplicationListenerExample implements ApplicationListener { + + private static final Logger LOG = Logger.getLogger(StartupApplicationListenerExample.class); + + public static int counter; + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} diff --git a/spring-all/src/main/resources/startupConfig.xml b/spring-all/src/main/resources/startupConfig.xml new file mode 100644 index 0000000000..8226665a90 --- /dev/null +++ b/spring-all/src/main/resources/startupConfig.xml @@ -0,0 +1,16 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java new file mode 100644 index 0000000000..523a27c2c4 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java @@ -0,0 +1,44 @@ +package org.baeldung.startup; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringStartupTest { + + @Autowired + private ApplicationContext ctx; + + @Test(expected = BeanCreationException.class) + public void whenInstantiating_shouldThrowBCE() throws Exception { + ctx.getBean(InvalidInitExampleBean.class); + } + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(PostConstructExampleBean.class); + } + + @Test + public void whenConstructorInjection_shouldLogEnv() throws Exception { + ctx.getBean(LogicInConstructorExampleBean.class); + } + + @Test + public void whenInitializingBean_shouldLogEnv() throws Exception { + ctx.getBean(InitializingBeanExampleBean.class); + } + + @Test + public void whenApplicationListener_shouldRunOnce() throws Exception { + Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java new file mode 100644 index 0000000000..19a35bb92b --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java @@ -0,0 +1,26 @@ +package org.baeldung.startup; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:startupConfig.xml") +public class SpringStartupXMLConfigTest { + + @Autowired + private ApplicationContext ctx; + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(InitMethodExampleBean.class); + } + + @Test + public void whenAllStrategies_shouldLogOrder() throws Exception { + ctx.getBean(AllStrategiesExampleBean.class); + } +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2c5304dbf3..66197feacd 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -112,7 +112,24 @@ maven-war-plugin - + + pl.project13.maven + git-commit-id-plugin + 2.2.1 + + + get-the-git-infos + + revision + + + + + true + + + + diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java new file mode 100644 index 0000000000..95abbf894c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.git; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.ClassPathResource; + +@SpringBootApplication(scanBasePackages = { "com.baeldung.git"}) +public class CommitIdApplication { + public static void main(String[] args) { + SpringApplication.run(CommitIdApplication.class, args); + } + + @Bean + public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { + PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); + c.setLocation(new ClassPathResource("git.properties")); + c.setIgnoreResourceNotFound(true); + c.setIgnoreUnresolvablePlaceholders(true); + return c; + } +} + + + diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java new file mode 100644 index 0000000000..226ba44dd5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -0,0 +1,23 @@ +package com.baeldung.git; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CommitInfoController { + + @Value("${git.commit.message.short}") + private String commitMessage; + + @Value("${git.branch}") + private String branch; + + @Value("${git.commit.id}") + private String commitId; + + @RequestMapping("/commitId") + public GitInfoDto getCommitId() { + return new GitInfoDto(commitMessage, branch, commitId); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java b/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java new file mode 100644 index 0000000000..b8b58f55e8 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/GitInfoDto.java @@ -0,0 +1,25 @@ +package com.baeldung.git; + +public class GitInfoDto { + private String commitMessage; + private String branch; + private String commitId; + + public GitInfoDto(String commitMessage, String branch, String commitId) { + this.commitMessage = commitMessage; + this.branch = branch; + this.commitId = commitId; + } + + public String getCommitMessage() { + return commitMessage; + } + + public String getBranch() { + return branch; + } + + public String getCommitId() { + return commitId; + } +} diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 78bcf4cc05..d30045d1dc 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -26,4 +26,6 @@ info.app.version=1.0.0 ## Spring Security Configurations security.user.name=admin1 security.user.password=secret1 -management.security.role=SUPERUSER \ No newline at end of file +management.security.role=SUPERUSER + +logging.level.org.springframework=INFO \ No newline at end of file diff --git a/spring-boot/src/main/resources/logback.xml b/spring-boot/src/main/resources/logback.xml new file mode 100644 index 0000000000..78913ee76f --- /dev/null +++ b/spring-boot/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java new file mode 100644 index 0000000000..e16791881e --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -0,0 +1,44 @@ +package com.baeldung.git; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = CommitIdApplication.class) +public class CommitIdTest { + + private static final Logger LOG = LoggerFactory.getLogger(CommitIdTest.class); + + @Value("${git.commit.message.short:UNKNOWN}") + private String commitMessage; + + @Value("${git.branch:UNKNOWN}") + private String branch; + + @Value("${git.commit.id:UNKNOWN}") + private String commitId; + + @Test + public void whenInjecting_shouldDisplay() throws Exception { + + LOG.info(commitId); + LOG.info(commitMessage); + LOG.info(branch); + + assertThat(commitMessage) + .isNotEqualTo("UNKNOWN"); + + assertThat(branch) + .isNotEqualTo("UNKNOWN"); + + assertThat(commitId) + .isNotEqualTo("UNKNOWN"); + } +} \ No newline at end of file diff --git a/spring-cloud-config/docker/Dockerfile b/spring-cloud-config/docker/Dockerfile new file mode 100644 index 0000000000..bdb37abf80 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile @@ -0,0 +1,4 @@ +FROM alpine:edge +MAINTAINER baeldung.com +RUN apk add --no-cache openjdk8 +COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/ diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud-config/docker/Dockerfile.client new file mode 100644 index 0000000000..5fbc0b98c0 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.client @@ -0,0 +1,6 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +RUN apk --no-cache add netcat-openbsd +COPY files/config-client.jar /opt/spring-cloud/lib/ +COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/ +RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud-config/docker/Dockerfile.server new file mode 100644 index 0000000000..4f7bd751e8 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.server @@ -0,0 +1,9 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +COPY files/config-server.jar /opt/spring-cloud/lib/ +ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \ + {"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}' +ENTRYPOINT ["/usr/bin/java"] +CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"] +VOLUME /var/lib/spring-cloud/config-repo +EXPOSE 8888 diff --git a/spring-cloud-config/docker/config-client-entrypoint.sh b/spring-cloud-config/docker/config-client-entrypoint.sh new file mode 100644 index 0000000000..12352119fa --- /dev/null +++ b/spring-cloud-config/docker/config-client-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +while ! nc -z config-server 8888 ; do + echo "Waiting for upcoming Config Server" + sleep 2 +done + +java -jar /opt/spring-cloud/lib/config-client.jar diff --git a/spring-cloud-config/docker/docker-compose.scale.yml b/spring-cloud-config/docker/docker-compose.scale.yml new file mode 100644 index 0000000000..f74153bea3 --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.scale.yml @@ -0,0 +1,41 @@ +version: '2' +services: + config-server: + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-cloud-config/docker/docker-compose.yml b/spring-cloud-config/docker/docker-compose.yml new file mode 100644 index 0000000000..74c71b651c --- /dev/null +++ b/spring-cloud-config/docker/docker-compose.yml @@ -0,0 +1,43 @@ +version: '2' +services: + config-server: + container_name: config-server + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + container_name: config-client + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080:8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index 91388b107b..80cb915e52 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -3,80 +3,71 @@ package com.baeldung.hibernate.fetching.model; import java.io.Serializable; import java.sql.Date; -public class OrderDetail implements Serializable { - - private static final long serialVersionUID = 1L; - private Long orderId; - private Date orderDate; - private String orderDesc; - private User user; - - public OrderDetail() { - - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - this.orderDate = orderDate; - this.orderDesc = orderDesc; - } - - public Date getOrderDate() { - return orderDate; - } - - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - - public String getOrderDesc() { - return orderDesc; - } - - public void setOrderDesc(String orderDesc) { - this.orderDesc = orderDesc; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } +public class OrderDetail implements Serializable{ + private static final long serialVersionUID = 1L; + private Long orderId; + private Date orderDate; + private String orderDesc; + private User user; + + public OrderDetail(){ + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + this.orderDate = orderDate; + this.orderDesc = orderDesc; + } + + public Date getOrderDate() { + return orderDate; + } + public void setOrderDate(Date orderDate) { + this.orderDate = orderDate; + } + public String getOrderDesc() { + return orderDesc; + } + public void setOrderDesc(String orderDesc) { + this.orderDesc = orderDesc; + } + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + public Long getOrderId() { + return orderId; + } + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } + + diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java index 158855f93e..fa995319fd 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java @@ -17,12 +17,11 @@ public class User implements Serializable { } public User(final Long userId, final String userName, final String firstName, final String lastName) { - super(); - this.userId = userId; - this.userName = userName; - this.firstName = firstName; - this.lastName = lastName; - + super(); + this.userId = userId; + this.userName = userName; + this.firstName = firstName; + this.lastName = lastName; } @Override diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index 65ecea2fa4..27af8c9b8b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -1,24 +1,27 @@ package com.baeldung.hibernate.fetching.util; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - - final String configFileName = "lazy".equals(fetchMethod) ? - "fetchingLazy.cfg.xml" : - "fetching.cfg.xml"; - - return new Configuration() - .configure(configFileName) - .buildSessionFactory().openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + //two config files are there + //one with lazy loading enabled + //another lazy = false + SessionFactory sf = null; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + final Session session = sf.openSession(); + return session; + } public static Session getHibernateSession() { return new Configuration() diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 90fd302968..c55f65cdbf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -18,93 +18,94 @@ import com.baeldung.hibernate.fetching.model.User; public class FetchingAppView { - public FetchingAppView() { + public FetchingAppView(){ + + } + + //lazily loaded + public Set lazyLoaded(){ + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From User").list(); + User userLazyLoaded = new User(); + userLazyLoaded = users.get(3); + //since data is lazyloaded so data won't be initialized + Set orderDetailSet = userLazyLoaded.getOrderDetail(); + return (orderDetailSet); + } + + //eagerly loaded + public Set eagerLoaded(){ + final Session sessionEager = HibernateUtil.getHibernateSession(); + //data should be loaded in the following line + //also note the queries generated + List users =sessionEager.createQuery("From User").list(); + User userEagerLoaded = new User(); + userEagerLoaded = users.get(3); + Set orderDetailSet = userEagerLoaded.getOrderDetail(); + return orderDetailSet; + } + + + //creates test data + //call this method to create the data in the database + public void createTestData() { - } + final Session session = HibernateUtil.getHibernateSession(); + Transaction tx = null; + tx = session.beginTransaction(); + final User user1 = new User(); + final User user2 = new User(); + final User user3 = new User(); + + user1.setFirstName("Priyam"); + user1.setLastName("Banerjee"); + user1.setUserName("priyambanerjee"); + session.save(user1); + + user2.setFirstName("Navneeta"); + user2.setLastName("Mukherjee"); + user2.setUserName("nmukh"); + session.save(user2); + + user3.setFirstName("Molly"); + user3.setLastName("Banerjee"); + user3.setUserName("mollyb"); + session.save(user3); - public boolean lazyLoaded() { - final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From User").list(); - User userLazyLoaded = users.get(3); - //since data is lazyloaded so data won't be initialized - Set orderDetailSet = userLazyLoaded.getOrderDetail(); + final OrderDetail order1 = new OrderDetail(); + final OrderDetail order2 = new OrderDetail(); + final OrderDetail order3 = new OrderDetail(); + final OrderDetail order4 = new OrderDetail(); + final OrderDetail order5 = new OrderDetail(); - return (Hibernate.isInitialized(orderDetailSet)); - } + order1.setOrderDesc("First Order"); + order1.setOrderDate(new Date(2014, 10, 12)); + order1.setUser(user1); + + order2.setOrderDesc("Second Order"); + order2.setOrderDate(new Date(2016, 10, 25)); + order2.setUser(user1); + + order3.setOrderDesc("Third Order"); + order3.setOrderDate(new Date(2015, 2, 17)); + order3.setUser(user2); + + order4.setOrderDesc("Fourth Order"); + order4.setOrderDate(new Date(2014, 10, 1)); + order4.setUser(user2); + + order5.setOrderDesc("Fifth Order"); + order5.setOrderDate(new Date(2014, 9, 11)); + order5.setUser(user3); + + session.saveOrUpdate(order1); + session.saveOrUpdate(order2); + session.saveOrUpdate(order3); + session.saveOrUpdate(order4); + session.saveOrUpdate(order5); - public boolean eagerLoaded() { - final Session sessionEager = HibernateUtil.getHibernateSession(); - //data should be loaded in the following line - //also note the queries generated - List users = sessionEager.createQuery("From User").list(); - User userEagerLoaded = users.get(3); - Set orderDetailSet = userEagerLoaded.getOrderDetail(); + tx.commit(); + session.close(); - return (Hibernate.isInitialized(orderDetailSet)); - } - - - //creates test data - //call this method to create the data in the database - public void createTestData() { - - final Session session = HibernateUtil.getHibernateSession(); - Transaction tx = session.beginTransaction(); - - final User user1 = new User(); - final User user2 = new User(); - final User user3 = new User(); - - user1.setFirstName("Priyam"); - user1.setLastName("Banerjee"); - user1.setUserName("priyambanerjee"); - session.save(user1); - - user2.setFirstName("Navneeta"); - user2.setLastName("Mukherjee"); - user2.setUserName("nmukh"); - session.save(user2); - - user3.setFirstName("Molly"); - user3.setLastName("Banerjee"); - user3.setUserName("mollyb"); - session.save(user3); - - final OrderDetail order1 = new OrderDetail(); - final OrderDetail order2 = new OrderDetail(); - final OrderDetail order3 = new OrderDetail(); - final OrderDetail order4 = new OrderDetail(); - final OrderDetail order5 = new OrderDetail(); - - order1.setOrderDesc("First Order"); - order1.setOrderDate(new Date(2014, 10, 12)); - order1.setUser(user1); - - order2.setOrderDesc("Second Order"); - order2.setOrderDate(new Date(2016, 10, 25)); - order2.setUser(user1); - - order3.setOrderDesc("Third Order"); - order3.setOrderDate(new Date(2015, 2, 17)); - order3.setUser(user2); - - order4.setOrderDesc("Fourth Order"); - order4.setOrderDate(new Date(2014, 10, 1)); - order4.setUser(user2); - - order5.setOrderDesc("Fifth Order"); - order5.setOrderDate(new Date(2014, 9, 11)); - order5.setUser(user3); - - - session.saveOrUpdate(order1); - session.saveOrUpdate(order2); - session.saveOrUpdate(order3); - session.saveOrUpdate(order4); - session.saveOrUpdate(order5); - - // session.saveOrUpdate(user1); - tx.commit(); - session.close(); - } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index 94ee8a3c79..fb3d0f92fc 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -1,24 +1,43 @@ package com.baeldung.hibernate.fetching; import static org.junit.Assert.*; +import java.util.Set; +import org.hibernate.Hibernate; +import org.junit.Before; import org.junit.Test; +import com.baeldung.hibernate.fetching.model.OrderDetail; + import com.baeldung.hibernate.fetching.view.FetchingAppView; public class HibernateFetchingTest { + + //this loads sample data in the database + @Before + public void addFecthingTestData(){ + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + //testLazyFetching() tests the lazy loading + //Since it lazily loaded so orderDetalSetLazy won't + //be initialized @Test public void testLazyFetching() { FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - assertFalse(fav.lazyLoaded()); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); } - + + //testEagerFetching() tests the eager loading + //Since it eagerly loaded so orderDetalSetLazy would + //be initialized @Test public void testEagerFetching() { FetchingAppView fav = new FetchingAppView(); - assertTrue(fav.eagerLoaded()); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); } - } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java deleted file mode 100644 index df70780a87..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/mock/MockStudentData.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.mock; - -import java.util.ArrayList; -import java.util.List; - -import org.baeldung.web.vo.Student; - -public class MockStudentData { - - private static List studentList = new ArrayList<>(); - - static { - studentList.add(new Student("1", "Bryan", "Male", 20)); - studentList.add(new Student("2", "Ben", "Male", 22)); - studentList.add(new Student("3", "Lisa", "Female", 24)); - studentList.add(new Student("4", "Sarah", "Female", 26)); - studentList.add(new Student("5", "Jay", "Male", 20)); - studentList.add(new Student("6", "John", "Male", 22)); - studentList.add(new Student("7", "Jordan", "Male", 24)); - studentList.add(new Student("8", "Rob", "Male", 26)); - studentList.add(new Student("9", "Will", "Male", 20)); - studentList.add(new Student("10", "Shawn", "Male", 22)); - studentList.add(new Student("11", "Taylor", "Female", 24)); - studentList.add(new Student("12", "Venus", "Female", 26)); - studentList.add(new Student("13", "Vince", "Male", 20)); - studentList.add(new Student("14", "Carol", "Female", 22)); - studentList.add(new Student("15", "Joana", "Female", 24)); - studentList.add(new Student("16", "Dion", "Male", 26)); - studentList.add(new Student("17", "Evans", "Male", 20)); - studentList.add(new Student("18", "Bart", "Male", 22)); - studentList.add(new Student("19", "Jenny", "Female", 24)); - studentList.add(new Student("20", "Kristine", "Female", 26)); - } - - public static List getMockDataStudents(){ - return studentList; - } - -} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java deleted file mode 100644 index b655d401a5..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web.rest; - -import org.baeldung.web.service.StudentService; -import org.baeldung.web.vo.Student; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import static org.springframework.http.MediaType.APPLICATION_JSON; - -@RestController -public class StudentDirectoryRestController { - - @Autowired - private StudentService service; - - @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json") - public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size){ - - Page resultPage = service.findPaginated(page, size); - - return resultPage; - } - -} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java deleted file mode 100644 index 5c4487254a..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentService.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.web.service; - -import org.baeldung.web.vo.Student; - -public interface StudentService extends IOperations{ - -} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java deleted file mode 100644 index 3b6dda6fb1..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.service; - -import java.util.List; - -import org.baeldung.mock.MockStudentData; -import org.baeldung.web.exception.MyResourceNotFoundException; -import org.baeldung.web.vo.Student; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Service; - -@Service -public class StudentServiceImpl implements StudentService { - - private List mockDataStudent = MockStudentData.getMockDataStudents(); - - @Override - public Page findPaginated(int page, int size){ - Page studentPage = getPage(page, size); - return studentPage; - } - - private Page getPage(int page, int size) { - page = page != 0?page - 1:page; - int from = Math.max(0, page * size); - int to = Math.min(mockDataStudent.size(), (page + 1) * size); - if(from > to){ - throw new MyResourceNotFoundException("page number is higher than total pages."); - } - return new PageImpl(mockDataStudent.subList(from, to), - new PageRequest(page,size), - mockDataStudent.size()); - } - -} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java b/spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java deleted file mode 100644 index 11c503815d..0000000000 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/vo/Student.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.baeldung.web.vo; - -import java.io.Serializable; - -public class Student implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public Student() { - } - - public Student(String studentId, String name, String gender, Integer age) { - super(); - this.studentId = studentId; - this.name = name; - this.gender = gender; - this.age = age; - } - - private String studentId; - private String name; - private String gender; - private Integer age; - - public String getStudentId() { - return studentId; - } - - public void setStudentId(String studentId) { - this.studentId = studentId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/spring-rest-angular-pagination/src/main/resources/application.properties b/spring-rest-angular-pagination/src/main/resources/application.properties deleted file mode 100644 index e42588cee0..0000000000 --- a/spring-rest-angular-pagination/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.contextPath=/ \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/webapp/index.html b/spring-rest-angular-pagination/src/main/webapp/index.html deleted file mode 100644 index 56a1273588..0000000000 --- a/spring-rest-angular-pagination/src/main/webapp/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - -
-
-
- - \ No newline at end of file diff --git a/spring-rest-angular-pagination/pom.xml b/spring-rest-angular/pom.xml similarity index 87% rename from spring-rest-angular-pagination/pom.xml rename to spring-rest-angular/pom.xml index 7a0f3e7b31..331c9a644c 100644 --- a/spring-rest-angular-pagination/pom.xml +++ b/spring-rest-angular/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - angular-spring-rest-sample - angular-spring-rest-sample + spring-rest-angular + spring-rest-angular com.baeldung 1.0 war @@ -13,9 +13,6 @@ spring-boot-starter-parent 1.3.3.RELEASE - - 1.12.2.RELEASE - org.springframework.boot @@ -30,6 +27,15 @@ org.springframework.data spring-data-commons + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + org.springframework spring-test diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java new file mode 100644 index 0000000000..b1aafb583a --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java @@ -0,0 +1,8 @@ +package org.baeldung.web.dao; + +import org.baeldung.web.entity.Student; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentRepository extends JpaRepository { + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java new file mode 100644 index 0000000000..0a0b60d87d --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java @@ -0,0 +1,69 @@ +package org.baeldung.web.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Student implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public Student() { + } + + public Student(long id, String name, String gender, Integer age) { + super(); + this.id = id; + this.name = name; + this.gender = gender; + this.age = age; + } + + @Id + private long id; + @Column(nullable = false) + private String name; + @Column(nullable = false) + private String gender; + @Column(nullable = false) + private Integer age; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + +} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java similarity index 77% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java rename to spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java index 3105d1cb11..740caec59e 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java @@ -3,11 +3,11 @@ package org.baeldung.web.exception; public class MyResourceNotFoundException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 4088649120307193208L; + * + */ + private static final long serialVersionUID = 4088649120307193208L; - public MyResourceNotFoundException() { + public MyResourceNotFoundException() { super(); } @@ -23,5 +23,4 @@ public class MyResourceNotFoundException extends RuntimeException { super(cause); } - } diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java similarity index 88% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java rename to spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java index b3b0dad98a..d6fe719311 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java @@ -4,16 +4,15 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; import org.springframework.web.filter.ShallowEtagHeaderFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@Import(PersistenceConfig.class) public class Application extends WebMvcConfigurerAdapter { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } @@ -22,5 +21,5 @@ public class Application extends WebMvcConfigurerAdapter { public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { return new ShallowEtagHeaderFilter(); } - + } diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java new file mode 100644 index 0000000000..df1240f270 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java @@ -0,0 +1,33 @@ +package org.baeldung.web.main; + +import javax.sql.DataSource; + +import org.springframework.boot.orm.jpa.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@EnableJpaRepositories("org.baeldung.web.dao") +@ComponentScan(basePackages = { "org.baeldung.web" }) +@EntityScan("org.baeldung.web.entity") +@Configuration +public class PersistenceConfig { + + @Bean + public JdbcTemplate getJdbcTemplate() { + return new JdbcTemplate(dataSource()); + } + + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).addScript("db/sql/data.sql").build(); + return db; + } + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java new file mode 100644 index 0000000000..dc295a3d97 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -0,0 +1,29 @@ +package org.baeldung.web.rest; + +import org.baeldung.web.entity.Student; +import org.baeldung.web.exception.MyResourceNotFoundException; +import org.baeldung.web.service.StudentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class StudentDirectoryRestController { + + @Autowired + private StudentService service; + + @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json") + public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) { + + Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + return resultPage; + } + +} diff --git a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java similarity index 64% rename from spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java rename to spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java index 0b408106ce..2176c0bb70 100644 --- a/spring-rest-angular-pagination/src/main/java/org/baeldung/web/service/IOperations.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - Page findPaginated(int page, int size); + public Page findPaginated(final int page, final int size); } diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java new file mode 100644 index 0000000000..1b194f76e2 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java @@ -0,0 +1,7 @@ +package org.baeldung.web.service; + +import org.baeldung.web.entity.Student; + +public interface StudentService extends IOperations { + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java new file mode 100644 index 0000000000..c7bcdc5bd5 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -0,0 +1,21 @@ +package org.baeldung.web.service; + +import org.baeldung.web.dao.StudentRepository; +import org.baeldung.web.entity.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +public class StudentServiceImpl implements StudentService { + + @Autowired + private StudentRepository dao; + + @Override + public Page findPaginated(int page, int size) { + return dao.findAll(new PageRequest(page, size)); + } + +} diff --git a/spring-rest-angular/src/main/resources/application.properties b/spring-rest-angular/src/main/resources/application.properties new file mode 100644 index 0000000000..e24db89c8f --- /dev/null +++ b/spring-rest-angular/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.contextPath=/ +spring.h2.console.enabled=true +logging.level.org.hibernate.SQL=info +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-rest-angular/src/main/resources/db/sql/data.sql b/spring-rest-angular/src/main/resources/db/sql/data.sql new file mode 100644 index 0000000000..418381a681 --- /dev/null +++ b/spring-rest-angular/src/main/resources/db/sql/data.sql @@ -0,0 +1,47 @@ +CREATE TABLE student ( + id INTEGER PRIMARY KEY, + name VARCHAR(30), + gender VARCHAR(10), + age INTEGER +); + +INSERT INTO student (id,name,gender,age) +VALUES (1,'Bryan', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (2, 'Ben', 'Male', 22); +INSERT INTO student (id,name,gender,age) +VALUES (3,'Lisa', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (4,'Sarah', 'Female',20); +INSERT INTO student (id,name,gender,age) +VALUES (5,'Jay', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (6,'John', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (7,'Jordan', 'Male',24); +INSERT INTO student (id,name,gender,age) +VALUES (8,'Rob', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (9,'Will', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (10,'Shawn', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (11,'Taylor', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (12,'Venus', 'Female',26); +INSERT INTO student (id,name,gender,age) +VALUES (13,'Vince', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (14,'Carol', 'Female',22); +INSERT INTO student (id,name,gender,age) +VALUES (15,'Joana', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (16,'Dion', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (17,'Evans', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (18,'Bart', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (19,'Jenny', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (20,'Kristine', 'Female',26); \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml similarity index 99% rename from spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml rename to spring-rest-angular/src/main/webapp/WEB-INF/web.xml index ff65bd6b96..6adf31503f 100644 --- a/spring-rest-angular-pagination/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml @@ -3,7 +3,7 @@ xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> - + index.html diff --git a/spring-rest-angular/src/main/webapp/index.html b/spring-rest-angular/src/main/webapp/index.html new file mode 100644 index 0000000000..49e0d6393d --- /dev/null +++ b/spring-rest-angular/src/main/webapp/index.html @@ -0,0 +1,17 @@ + + + + + + + + + +
+
+
+ + \ No newline at end of file diff --git a/spring-rest-angular-pagination/src/main/webapp/view/app.js b/spring-rest-angular/src/main/webapp/view/app.js similarity index 95% rename from spring-rest-angular-pagination/src/main/webapp/view/app.js rename to spring-rest-angular/src/main/webapp/view/app.js index 715b667cc9..a41026d2c3 100644 --- a/spring-rest-angular-pagination/src/main/webapp/view/app.js +++ b/spring-rest-angular/src/main/webapp/view/app.js @@ -19,7 +19,7 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude enableColumnMenus:false, useExternalPagination: true, columnDefs: [ - { name: 'studentId' }, + { name: 'id' }, { name: 'name' }, { name: 'gender' }, { name: 'age' } @@ -42,6 +42,7 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude app.service('StudentService',['$http', function ($http) { function getStudents(pageNumber,size) { + pageNumber = pageNumber > 0?pageNumber - 1:0; return $http({ method: 'GET', url: 'student/get?page='+pageNumber+'&size='+size diff --git a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java similarity index 55% rename from spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java rename to spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java index 19fe77a1fd..1199f15ab3 100644 --- a/spring-rest-angular-pagination/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java @@ -9,9 +9,10 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; +import static io.restassured.RestAssured.*; +import static org.hamcrest.core.IsCollectionContaining.*; +import static org.hamcrest.core.Is.*; +import static org.hamcrest.core.IsEqual.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @@ -23,58 +24,42 @@ public class StudentServiceTest { @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "1", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("content.name", hasItems("Bryan", "Ben")); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "1", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("size", equalTo(2)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "1", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("numberOfElements", equalTo(2)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "1", "size", "2").get(ENDPOINT) - .then() - .statusCode(200); + given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); } @Test public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { - given().params("page", "1000", "size", "2").get(ENDPOINT) - .then() - .statusCode(500); + given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageNotValid_thenExpect500() { - given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT) - .then() - .statusCode(500); + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); } @Test - public void givenRequestForStudents_whenPageIsFive_expectFiveItems() { - given().params("page", "1", "size", "5").get(ENDPOINT) - .then() - .body("content.studentId.max()", equalTo("5")); + public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { + given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "1", "size", "2").get(ENDPOINT) - .then() - .assertThat().body("first", equalTo(true)); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java new file mode 100644 index 0000000000..8aa9162edc --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java @@ -0,0 +1,51 @@ +package org.baeldung.web.interceptor; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +public class LoggerInterceptorTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + * + * @throws Exception + */ + @Test + public void testInterceptors() throws Exception { + mockMvc.perform(get("/graph.html")).andExpect(status().isOk()); + } + +}