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/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/cdi/pom.xml b/cdi/pom.xml new file mode 100644 index 0000000000..2a9d32188b --- /dev/null +++ b/cdi/pom.xml @@ -0,0 +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.springframework + spring-test + ${spring.version} + test + + + + org.aspectj + aspectjweaver + 1.8.9 + + + + org.jboss.weld.se + weld-se-core + 2.3.5.Final + + + \ 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 new file mode 100644 index 0000000000..4065450b09 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java @@ -0,0 +1,12 @@ +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; + +@InterceptorBinding +@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 new file mode 100644 index 0000000000..46ab9b33c8 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java @@ -0,0 +1,19 @@ +package com.baeldung.interceptor; + +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; +import java.lang.reflect.Method; + +@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; + Object result = ctx.proceed(); + calledAfter = true; + return result; + } +} diff --git a/cdi/src/main/java/com/baeldung/service/SuperService.java b/cdi/src/main/java/com/baeldung/service/SuperService.java new file mode 100644 index 0000000000..e1e57a4e0d --- /dev/null +++ b/cdi/src/main/java/com/baeldung/service/SuperService.java @@ -0,0 +1,10 @@ +package com.baeldung.service; + +import com.baeldung.interceptor.Audited; + +public class SuperService { + @Audited + public String deliverService(String 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 new file mode 100644 index 0000000000..8c2ff2600b --- /dev/null +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.aspect; + +import org.aspectj.lang.JoinPoint; +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 { + String methodName = jp.getSignature().getName(); + accumulator.add("Call to "+methodName); + Object obj = jp.proceed(); + 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 new file mode 100644 index 0000000000..6cfc8f8743 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import com.baeldung.spring.aspect.SpringTestAspect; +import com.baeldung.spring.service.SpringSuperService; +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; + +@Configuration +@EnableAspectJAutoProxy +public class AppConfig { + @Bean + public SpringSuperService springSuperService() { + return new SpringSuperService(); + } + + @Bean + public SpringTestAspect springTestAspect(){ + return new SpringTestAspect(); + } + + @Bean + 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 new file mode 100644 index 0000000000..72dbd1c006 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.service; + +public class SpringSuperService { + public String getInfoFromService(String code){ + return code; + } +} diff --git a/cdi/src/main/resources/META-INF/beans.xml b/cdi/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..d41b35e7d9 --- /dev/null +++ b/cdi/src/main/resources/META-INF/beans.xml @@ -0,0 +1,8 @@ + + + com.baeldung.interceptor.AuditedInterceptor + + \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java new file mode 100644 index 0000000000..d1b851c94f --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -0,0 +1,42 @@ +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; +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; + +public class TestInterceptor { + Weld weld; + WeldContainer container; + @Before + public void init(){ + weld = new Weld(); + container = weld.initialize(); + } + + @After + public void shutdown(){ + weld.shutdown(); + } + + @Test + public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() { + 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 new file mode 100644 index 0000000000..b5aedd4b76 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java @@ -0,0 +1,38 @@ +package com.baeldung.test; + +import com.baeldung.spring.configuration.AppConfig; +import com.baeldung.spring.service.SpringSuperService; +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; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {AppConfig.class}) +public class TestSpringInterceptor { + @Autowired + SpringSuperService springSuperService; + + @Autowired + private List accumulator; + + @Test + 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")); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java new file mode 100644 index 0000000000..05aa14c5ae --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -0,0 +1,22 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; +import java.util.stream.Collectors; + +public class CountingTask extends RecursiveTask { + + private final TreeNode node; + + public CountingTask(TreeNode node) { + this.node = node; + } + + @Override + protected Integer compute() { + return node.value + node.children.stream() + .map(childNode -> new CountingTask(childNode).fork()) + .collect(Collectors.summingInt(ForkJoinTask::join)); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java new file mode 100644 index 0000000000..4775fde930 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java @@ -0,0 +1,29 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import com.google.common.util.concurrent.MoreExecutors; + +/** + * This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging. + * Without the exiting executor service, the task would hang indefinitely. + * This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests. + */ +public class ExitingExecutorServiceExample { + + public static void main(String... args) { + + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5); + ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS); + + executorService.submit(() -> { + while (true) { + } + }); + + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java new file mode 100644 index 0000000000..9b43152074 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java @@ -0,0 +1,18 @@ +package com.baeldung.threadpool; + +import java.util.Set; + +import com.google.common.collect.Sets; + +public class TreeNode { + + int value; + + Set children; + + public TreeNode(int value, TreeNode... children) { + this.value = value; + this.children = Sets.newHashSet(children); + } + +} 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..806bca5461 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -0,0 +1,190 @@ +package com.baeldung.completablefuture; + +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +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); + + } + + @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()); + + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java new file mode 100644 index 0000000000..df336f4a93 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java @@ -0,0 +1,146 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CoreThreadPoolTest { + + @Test(timeout = 1000) + public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(1); + + Executor executor = Executors.newSingleThreadExecutor(); + executor.execute(() -> { + System.out.println("Hello World"); + lock.countDown(); + }); + + lock.await(1000, TimeUnit.MILLISECONDS); + } + + @Test + public void whenUsingExecutorServiceAndFuture_thenCanWaitOnFutureResult() throws InterruptedException, ExecutionException { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + Future future = executorService.submit(() -> "Hello World"); + String result = future.get(); + + assertEquals("Hello World", result); + + } + + @Test + public void whenUsingFixedThreadPool_thenCoreAndMaximumThreadSizeAreTheSame() { + + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + + assertEquals(2, executor.getPoolSize()); + assertEquals(1, executor.getQueue().size()); + + } + + @Test + public void whenUsingCachedThreadPool_thenPoolSizeGrowsUnbounded() { + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + + assertEquals(3, executor.getPoolSize()); + assertEquals(0, executor.getQueue().size()); + + } + + @Test(timeout = 1000) + public void whenUsingSingleThreadPool_thenTasksExecuteSequentially() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(2); + AtomicInteger counter = new AtomicInteger(); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + executor.submit(() -> { + counter.set(1); + lock.countDown(); + }); + executor.submit(() -> { + counter.compareAndSet(1, 2); + lock.countDown(); + }); + + lock.await(1000, TimeUnit.MILLISECONDS); + assertEquals(2, counter.get()); + + } + + @Test(timeout = 1000) + public void whenSchedulingTask_thenTaskExecutesWithinGivenPeriod() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(1); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); + executor.schedule(() -> { + System.out.println("Hello World"); + lock.countDown(); + }, 500, TimeUnit.MILLISECONDS); + + lock.await(1000, TimeUnit.MILLISECONDS); + + } + + @Test(timeout = 1000) + public void whenSchedulingTaskWithFixedPeriod_thenTaskExecutesMultipleTimes() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(3); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); + ScheduledFuture> future = executor.scheduleAtFixedRate(() -> { + System.out.println("Hello World"); + lock.countDown(); + }, 500, 100, TimeUnit.MILLISECONDS); + + lock.await(); + future.cancel(true); + + } + + @Test + public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() { + + TreeNode tree = new TreeNode(5, + new TreeNode(3), new TreeNode(2, + new TreeNode(2), new TreeNode(8))); + + ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + int sum = forkJoinPool.invoke(new CountingTask(tree)); + + assertEquals(20, sum); + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java new file mode 100644 index 0000000000..92e0f9a8cb --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java @@ -0,0 +1,56 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class GuavaThreadPoolTest { + + @Test + public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() { + + Executor executor = MoreExecutors.directExecutor(); + + AtomicBoolean executed = new AtomicBoolean(); + + executor.execute(() -> { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + executed.set(true); + }); + + assertTrue(executed.get()); + } + + @Test + public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException { + + ExecutorService executorService = Executors.newCachedThreadPool(); + ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); + + ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello"); + ListenableFuture future2 = listeningExecutorService.submit(() -> "World"); + + String greeting = Futures.allAsList(future1, future2).get() + .stream() + .collect(Collectors.joining(" ")); + assertEquals("Hello World", greeting); + + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java new file mode 100644 index 0000000000..ad1f2dc70c --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java @@ -0,0 +1,44 @@ +package org.baeldung.java.arrays; + +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Test; + +public class ArraysJoinAndSplitJUnitTest { + + private final String[] sauces = {"Marinara", "Olive Oil"}; + private final String[] cheeses = {"Mozzarella", "Feta", "Parmesan"}; + private final String[] vegetables = {"Olives", "Spinach", "Green Peppers"}; + + private final String[] customers = {"Jay", "Harry", "Ronnie", "Gary", "Ross"}; + + @Test + public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() { + String[] toppings = new String[sauces.length + cheeses.length + vegetables.length]; + + System.arraycopy(sauces, 0, toppings, 0, sauces.length); + int AddedSoFar = sauces.length; + + System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length); + AddedSoFar += cheeses.length; + + System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length); + + Assert.assertArrayEquals(toppings, + new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta", + "Parmesan", "Olives", "Spinach", "Green Peppers"}); + } + + + @Test + public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() { + int ordersHalved = (customers.length / 2) + (customers.length % 2); + + String[] driverOne = Arrays.copyOf(customers, ordersHalved); + String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length); + + Assert.assertArrayEquals(driverOne, new String[]{"Jay", "Harry", "Ronnie"}); + Assert.assertArrayEquals(driverTwo, new String[]{"Gary", "Ross"}); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java new file mode 100644 index 0000000000..c288cf499d --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java @@ -0,0 +1,62 @@ +package org.baeldung.java.collections; + +import java.util.ArrayList; +import java.util.Collections; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class CollectionsJoinAndSplitJUnitTest { + + private ArrayList sauces = new ArrayList<>(); + private ArrayList cheeses = new ArrayList<>(); + private ArrayList vegetables = new ArrayList<>(); + + private ArrayList> ingredients = new ArrayList<>(); + + @Before + public void init() { + sauces.add("Olive Oil"); + sauces.add("Marinara"); + + cheeses.add("Mozzarella"); + cheeses.add("Feta"); + cheeses.add("Parmesan"); + + vegetables.add("Olives"); + vegetables.add("Spinach"); + vegetables.add("Green Peppers"); + + ingredients.add(sauces); + ingredients.add(cheeses); + ingredients.add(vegetables); + } + + @Test + public void givenThreeArrayLists_whenJoiningIntoOneArrayList_shouldSucceed() { + ArrayList> toppings = new ArrayList<>(); + + toppings.add(sauces); + toppings.add(cheeses); + toppings.add(vegetables); + + Assert.assertTrue(toppings.size() == 3); + Assert.assertTrue(toppings.contains(sauces)); + Assert.assertTrue(toppings.contains(cheeses)); + Assert.assertTrue(toppings.contains(vegetables)); + } + + @Test + public void givenOneArrayList_whenSplittingIntoTwoArrayLists_shouldSucceed() { + + ArrayList> removedToppings = new ArrayList<>(); + removedToppings.add(ingredients.remove(ingredients.indexOf(vegetables))); + + Assert.assertTrue(removedToppings.contains(vegetables)); + Assert.assertTrue(removedToppings.size() == 1); + Assert.assertTrue(ingredients.size() == 2); + Assert.assertTrue(ingredients.contains(sauces)); + Assert.assertTrue(ingredients.contains(cheeses)); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index 7a4c7366eb..3c574f1e5c 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -1,5 +1,8 @@ package org.baeldung.java.io; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; @@ -187,10 +190,24 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + + final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader)); + + final String finalString = IOUtils.toString(targetStream); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } + // tests - Reader to InputStream with encoding @Test - public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException { + public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset() throws IOException { final Reader initialReader = new StringReader("With Java"); final char[] charBuffer = new char[8 * 1024]; @@ -225,4 +242,17 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); + + String finalString = IOUtils.toString(targetStream, Charsets.UTF_8); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } + } diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..5fd4d5023f Binary files /dev/null and b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar differ diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..eb91947648 --- /dev/null +++ b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-async/.springBeans b/couchbase-sdk-async/.springBeans new file mode 100644 index 0000000000..ff32b84d3b --- /dev/null +++ b/couchbase-sdk-async/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/couchbase-sdk-async/mvnw b/couchbase-sdk-async/mvnw new file mode 100755 index 0000000000..a1ba1bf554 --- /dev/null +++ b/couchbase-sdk-async/mvnw @@ -0,0 +1,233 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" diff --git a/couchbase-sdk-async/mvnw.cmd b/couchbase-sdk-async/mvnw.cmd new file mode 100644 index 0000000000..2b934e89dd --- /dev/null +++ b/couchbase-sdk-async/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% \ No newline at end of file diff --git a/couchbase-sdk-async/pom.xml b/couchbase-sdk-async/pom.xml new file mode 100644 index 0000000000..9062ef8e15 --- /dev/null +++ b/couchbase-sdk-async/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + com.baeldung + couchbase-sdk-async + 0.1-SNAPSHOT + jar + couchbase-sdk-async + Couchbase SDK Asynchronous Operations + + + + + com.couchbase.client + java-client + ${couchbase.client.version} + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-context-support + ${spring-framework.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + compile + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + + org.springframework + spring-test + ${spring-framework.version} + test + + + junit + junit + ${junit.version} + test + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + + + + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + + + + 1.7 + UTF-8 + 2.2.6 + 4.2.4.RELEASE + 1.1.3 + 1.7.12 + 4.11 + 3.4 + + + diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java new file mode 100644 index 0000000000..bf248c3999 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java @@ -0,0 +1,89 @@ +package com.baeldung.couchbase.person; + +import com.baeldung.couchbase.service.CouchbaseEntity; + +public class Person implements CouchbaseEntity { + + private String id; + private String type; + private String name; + private String homeTown; + + Person() {} + + public Person(Builder b) { + this.id = b.id; + this.type = b.type; + this.name = b.name; + this.homeTown = b.homeTown; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getHomeTown() { + return homeTown; + } + + public void setHomeTown(String homeTown) { + this.homeTown = homeTown; + } + + public static class Builder { + private String id; + private String type; + private String name; + private String homeTown; + + public static Builder newInstance() { + return new Builder(); + } + + public Person build() { + return new Person(this); + } + + public Builder id(String id) { + this.id = id; + return this; + } + + public Builder type(String type) { + this.type = type; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder homeTown(String homeTown) { + this.homeTown = homeTown; + return this; + } + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java new file mode 100644 index 0000000000..d5302bd6db --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.person; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +import com.baeldung.couchbase.service.AbstractCrudService; +import com.baeldung.couchbase.service.BucketService; + +@Service +public class PersonCrudService extends AbstractCrudService { + + @Autowired + public PersonCrudService( + @Qualifier("TutorialBucketService") BucketService bucketService, + PersonDocumentConverter converter) { + super(bucketService, converter); + } + + @PostConstruct + private void init() { + loadBucket(); + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java new file mode 100644 index 0000000000..cfb20a2bfb --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java @@ -0,0 +1,31 @@ +package com.baeldung.couchbase.person; + +import org.springframework.stereotype.Service; + +import com.baeldung.couchbase.service.JsonDocumentConverter; +import com.couchbase.client.java.document.JsonDocument; +import com.couchbase.client.java.document.json.JsonObject; + +@Service +public class PersonDocumentConverter implements JsonDocumentConverter { + + @Override + public JsonDocument toDocument(Person p) { + JsonObject content = JsonObject.empty() + .put("type", "Person") + .put("name", p.getName()) + .put("homeTown", p.getHomeTown()); + return JsonDocument.create(p.getId(), content); + } + + @Override + public Person fromDocument(JsonDocument doc) { + JsonObject content = doc.content(); + Person p = new Person(); + p.setId(doc.id()); + p.setType("Person"); + p.setName(content.getString("name")); + p.setHomeTown(content.getString("homeTown")); + return p; + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java new file mode 100644 index 0000000000..53af1c4041 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java @@ -0,0 +1,29 @@ +package com.baeldung.couchbase.person; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.couchbase.client.core.CouchbaseException; + +@Service +public class RegistrationService { + + @Autowired + private PersonCrudService crud; + + public void registerNewPerson(String name, String homeTown) { + Person person = new Person(); + person.setName(name); + person.setHomeTown(homeTown); + crud.create(person); + } + + public Person findRegistrant(String id) { + try{ + return crud.read(id); + } + catch(CouchbaseException e) { + return crud.readFromReplica(id); + } + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java new file mode 100644 index 0000000000..08acf5deed --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java @@ -0,0 +1,27 @@ +package com.baeldung.couchbase.service; + +import com.couchbase.client.java.Bucket; + +public abstract class AbstractBucketService implements BucketService { + + private ClusterService clusterService; + + private Bucket bucket; + + protected void openBucket() { + bucket = clusterService.openBucket(getBucketName(), getBucketPassword()); + } + + protected abstract String getBucketName(); + + protected abstract String getBucketPassword(); + + public AbstractBucketService(ClusterService clusterService) { + this.clusterService = clusterService; + } + + @Override + public Bucket getBucket() { + return bucket; + } + } diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java new file mode 100644 index 0000000000..ce95074015 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java @@ -0,0 +1,174 @@ +package com.baeldung.couchbase.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.couchbase.client.core.BackpressureException; +import com.couchbase.client.core.time.Delay; +import com.couchbase.client.java.AsyncBucket; +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.ReplicaMode; +import com.couchbase.client.java.document.JsonDocument; +import com.couchbase.client.java.util.retry.RetryBuilder; + +import rx.Observable; +import rx.functions.Action1; +import rx.functions.Func1; + +public abstract class AbstractCrudService implements CrudService { + + private static final Logger logger = LoggerFactory.getLogger(AbstractCrudService.class); + + private BucketService bucketService; + private Bucket bucket; + private JsonDocumentConverter converter; + + public AbstractCrudService(BucketService bucketService, JsonDocumentConverter converter) { + this.bucketService = bucketService; + this.converter = converter; + } + + protected void loadBucket() { + bucket = bucketService.getBucket(); + } + + @Override + public void create(T t) { + if(t.getId() == null) { + t.setId(UUID.randomUUID().toString()); + } + JsonDocument doc = converter.toDocument(t); + bucket.insert(doc); + } + + @Override + public T read(String id) { + JsonDocument doc = bucket.get(id); + return (doc == null ? null : converter.fromDocument(doc)); + } + + @Override + public T readFromReplica(String id) { + List docs = bucket.getFromReplica(id, ReplicaMode.FIRST); + return (docs.isEmpty() ? null : converter.fromDocument(docs.get(0))); + } + + @Override + public void update(T t) { + JsonDocument doc = converter.toDocument(t); + bucket.upsert(doc); + } + + @Override + public void delete(String id) { + bucket.remove(id); + } + + @Override + public List readBulk(Iterable ids) { + final AsyncBucket asyncBucket = bucket.async(); + Observable asyncOperation = Observable + .from(ids) + .flatMap(new Func1>() { + public Observable call(String key) { + return asyncBucket.get(key); + } + }); + + final List items = new ArrayList(); + try { + asyncOperation.toBlocking() + .forEach(new Action1() { + public void call(JsonDocument doc) { + T item = converter.fromDocument(doc); + items.add(item); + } + }); + } catch (Exception e) { + logger.error("Error during bulk get", e); + } + + return items; + } + + @Override + public void createBulk(Iterable items) { + final AsyncBucket asyncBucket = bucket.async(); + Observable + .from(items) + .flatMap(new Func1>() { + @SuppressWarnings("unchecked") + @Override + public Observable call(final T t) { + if(t.getId() == null) { + t.setId(UUID.randomUUID().toString()); + } + JsonDocument doc = converter.toDocument(t); + return asyncBucket.insert(doc) + .retryWhen(RetryBuilder + .anyOf(BackpressureException.class) + .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) + .max(10) + .build()); + } + }) + .last() + .toBlocking() + .single(); + } + + @Override + public void updateBulk(Iterable items) { + final AsyncBucket asyncBucket = bucket.async(); + Observable + .from(items) + .flatMap(new Func1>() { + @SuppressWarnings("unchecked") + @Override + public Observable call(final T t) { + JsonDocument doc = converter.toDocument(t); + return asyncBucket.upsert(doc) + .retryWhen(RetryBuilder + .anyOf(BackpressureException.class) + .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) + .max(10) + .build()); + } + }) + .last() + .toBlocking() + .single(); + } + + @Override + public void deleteBulk(Iterable ids) { + final AsyncBucket asyncBucket = bucket.async(); + Observable + .from(ids) + .flatMap(new Func1>() { + @SuppressWarnings("unchecked") + @Override + public Observable call(String key) { + return asyncBucket.remove(key) + .retryWhen(RetryBuilder + .anyOf(BackpressureException.class) + .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) + .max(10) + .build()); + } + }) + .last() + .toBlocking() + .single(); + } + + @Override + public boolean exists(String id) { + return bucket.exists(id); + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java new file mode 100644 index 0000000000..df9156d87d --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java @@ -0,0 +1,8 @@ +package com.baeldung.couchbase.service; + +import com.couchbase.client.java.Bucket; + +public interface BucketService { + + Bucket getBucket(); +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java new file mode 100644 index 0000000000..437ec00ff4 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java @@ -0,0 +1,8 @@ +package com.baeldung.couchbase.service; + +import com.couchbase.client.java.Bucket; + +public interface ClusterService { + + Bucket openBucket(String name, String password); +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java new file mode 100644 index 0000000000..c8ff56269d --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java @@ -0,0 +1,36 @@ +package com.baeldung.couchbase.service; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.annotation.PostConstruct; + +import org.springframework.stereotype.Service; + +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; + +@Service +public class ClusterServiceImpl implements ClusterService { + + private Cluster cluster; + private Map buckets = new ConcurrentHashMap<>(); + + @PostConstruct + private void init() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); + cluster = CouchbaseCluster.create(env, "localhost"); + } + + @Override + synchronized public Bucket openBucket(String name, String password) { + if(!buckets.containsKey(name)) { + Bucket bucket = cluster.openBucket(name, password); + buckets.put(name, bucket); + } + return buckets.get(name); + } +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java new file mode 100644 index 0000000000..4d2500197b --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java @@ -0,0 +1,9 @@ +package com.baeldung.couchbase.service; + +public interface CouchbaseEntity { + + String getId(); + + void setId(String id); + +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java new file mode 100644 index 0000000000..e0f0831abb --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.service; + +import java.util.List; + +public interface CrudService { + + void create(T t); + + T read(String id); + + T readFromReplica(String id); + + void update(T t); + + void delete(String id); + + List readBulk(Iterable ids); + + void createBulk(Iterable items); + + void updateBulk(Iterable items); + + void deleteBulk(Iterable ids); + + boolean exists(String id); +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java new file mode 100644 index 0000000000..87331d2a17 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java @@ -0,0 +1,10 @@ +package com.baeldung.couchbase.service; + +import com.couchbase.client.java.document.JsonDocument; + +public interface JsonDocumentConverter { + + JsonDocument toDocument(T t); + + T fromDocument(JsonDocument doc); +} diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java new file mode 100644 index 0000000000..2e40321272 --- /dev/null +++ b/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java @@ -0,0 +1,32 @@ +package com.baeldung.couchbase.service; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +@Qualifier("TutorialBucketService") +public class TutorialBucketService extends AbstractBucketService { + + @PostConstruct + void init() { + openBucket(); + } + + @Autowired + public TutorialBucketService(ClusterService clusterService) { + super(clusterService); + } + + @Override + protected String getBucketName() { + return "baeldung-tutorial"; + } + + @Override + protected String getBucketPassword() { + return ""; + } +} diff --git a/couchbase-sdk-async/src/main/resources/application.properties b/couchbase-sdk-async/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/couchbase-sdk-async/src/main/resources/logback.xml b/couchbase-sdk-async/src/main/resources/logback.xml new file mode 100644 index 0000000000..efcc6fb4c7 --- /dev/null +++ b/couchbase-sdk-async/src/main/resources/logback.xml @@ -0,0 +1,17 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + \ No newline at end of file diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java new file mode 100644 index 0000000000..d1cc807f7a --- /dev/null +++ b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.couchbase; + +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public abstract class IntegrationTest { +} diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java new file mode 100644 index 0000000000..d593aac52d --- /dev/null +++ b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.couchbase; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages={"com.baeldung.couchbase"}) +public class IntegrationTestConfig { +} diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java new file mode 100644 index 0000000000..3da282492c --- /dev/null +++ b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java @@ -0,0 +1,220 @@ +package com.baeldung.couchbase.person; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; + +import com.baeldung.couchbase.IntegrationTest; +import com.baeldung.couchbase.service.BucketService; +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.document.JsonDocument; + +public class PersonCrudServiceTest extends IntegrationTest { + + @Autowired + private PersonCrudService personService; + + @Autowired + @Qualifier("TutorialBucketService") + private BucketService bucketService; + + @Autowired + private PersonDocumentConverter converter; + + private Bucket bucket; + + @PostConstruct + private void init() { + bucket = bucketService.getBucket(); + } + + @Test + public final void givenRandomPerson_whenCreate_thenPersonPersisted() { + //create person + Person person = randomPerson(); + personService.create(person); + + //check results + assertNotNull(person.getId()); + assertNotNull(bucket.get(person.getId())); + + //cleanup + bucket.remove(person.getId()); + } + + @Test + public final void givenId_whenRead_thenReturnsPerson() { + //create and insert person document + String id = insertRandomPersonDocument().id(); + + //read person and check results + assertNotNull(personService.read(id)); + + //cleanup + bucket.remove(id); + } + + @Test + public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { + //create and insert person document + JsonDocument doc = insertRandomPersonDocument(); + + //update person + Person expected = converter.fromDocument(doc); + String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); + expected.setHomeTown(updatedHomeTown); + personService.update(expected); + + //check results + JsonDocument actual = bucket.get(expected.getId()); + assertNotNull(actual); + assertNotNull(actual.content()); + assertEquals(expected.getHomeTown(), actual.content().getString("homeTown")); + + //cleanup + bucket.remove(expected.getId()); + } + + @Test + public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { + //create and insert person document + String id = insertRandomPersonDocument().id(); + + //delete person and check results + personService.delete(id); + assertNull(bucket.get(id)); + } + + @Test + public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() { + List ids = new ArrayList<>(); + + //add some person documents + for(int i=0; i<5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + //perform bulk read + List persons = personService.readBulk(ids); + + //check results + for(Person person : persons) { + assertTrue(ids.contains(person.getId())); + } + + //cleanup + for(String id : ids) { + bucket.remove(id); + } + } + + @Test + public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() { + + //create some persons + List persons = new ArrayList<>(); + for(int i=0; i<5; i++) { + persons.add(randomPerson()); + } + + //perform bulk insert + personService.createBulk(persons); + + //check results + for(Person person : persons) { + assertNotNull(bucket.get(person.getId())); + } + + //cleanup + for(Person person : persons) { + bucket.remove(person.getId()); + } + } + + @Test + public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() { + + List ids = new ArrayList<>(); + + //add some person documents + for(int i=0; i<5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + //load persons from Couchbase + List persons = new ArrayList<>(); + for(String id : ids) { + persons.add(converter.fromDocument(bucket.get(id))); + } + + //modify persons + for(Person person : persons) { + person.setHomeTown(RandomStringUtils.randomAlphabetic(10)); + } + + //perform bulk update + personService.updateBulk(persons); + + //check results + for(Person person : persons) { + JsonDocument doc = bucket.get(person.getId()); + assertEquals(person.getName(), doc.content().getString("name")); + assertEquals(person.getHomeTown(), doc.content().getString("homeTown")); + } + + //cleanup + for(String id : ids) { + bucket.remove(id); + } + } + + @Test + public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() { + + List ids = new ArrayList<>(); + + //add some person documents + for(int i=0; i<5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + //perform bulk delete + personService.deleteBulk(ids); + + //check results + for(String id : ids) { + assertNull(bucket.get(id)); + } + + } + + private JsonDocument insertRandomPersonDocument() { + Person expected = randomPersonWithId(); + JsonDocument doc = converter.toDocument(expected); + return bucket.insert(doc); + } + + private Person randomPerson() { + return Person.Builder.newInstance() + .name(RandomStringUtils.randomAlphabetic(10)) + .homeTown(RandomStringUtils.randomAlphabetic(10)) + .build(); + } + + private Person randomPersonWithId() { + return Person.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .name(RandomStringUtils.randomAlphabetic(10)) + .homeTown(RandomStringUtils.randomAlphabetic(10)) + .build(); + } +} diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java new file mode 100644 index 0000000000..7795f41c93 --- /dev/null +++ b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java @@ -0,0 +1,34 @@ +package com.baeldung.couchbase.service; + +import static 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.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +import com.baeldung.couchbase.IntegrationTest; +import com.baeldung.couchbase.IntegrationTestConfig; +import com.couchbase.client.java.Bucket; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class ClusterServiceTest extends IntegrationTest { + + @Autowired + private ClusterService couchbaseService; + + private Bucket defaultBucket; + + @Test + public void whenOpenBucket_thenBucketIsNotNull() throws Exception { + defaultBucket = couchbaseService.openBucket("default", ""); + assertNotNull(defaultBucket); + assertFalse(defaultBucket.isClosed()); + defaultBucket.close(); + } +} diff --git a/dozer-tutorial/pom.xml b/dozer-tutorial/pom.xml deleted file mode 100644 index 9447a3ff54..0000000000 --- a/dozer-tutorial/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - 4.0.0 - com.baeldung - dozer-tutorial - 1.0 - Dozer - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 7 - 7 - - - - - - - org.slf4j - slf4j-api - 1.7.5 - - - - org.slf4j - jcl-over-slf4j - 1.7.5 - - - - org.apache.commons - commons-lang3 - 3.2.1 - - - - commons-beanutils - commons-beanutils - 1.9.1 - - - - net.sf.dozer - dozer - 5.5.1 - - - junit - junit - 4.3 - test - - - - diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Dest2.java b/dozer-tutorial/src/main/java/com/baeldung/dozer/Dest2.java deleted file mode 100644 index aa969b38d6..0000000000 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Dest2.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.dozer; - -public class Dest2 { - private int id; - private int points; - - public Dest2() { - - } - - public Dest2(int id, int points) { - super(); - this.id = id; - this.points = points; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - @Override - public String toString() { - return "Dest2 [id=" + id + ", points=" + points + "]"; - } - -} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/MyCustomConvertor.java b/dozer-tutorial/src/main/java/com/baeldung/dozer/MyCustomConvertor.java deleted file mode 100644 index ae0ed0ba87..0000000000 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/MyCustomConvertor.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.dozer; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.dozer.CustomConverter; -import org.dozer.MappingException; - -public class MyCustomConvertor implements CustomConverter { - - @Override - public Object convert(Object dest, Object source, Class> arg2, - Class> arg3) { - if (source == null) { - return null; - } - if (source instanceof Personne3) { - Personne3 person = (Personne3) source; - Date date = new Date(person.getDtob()); - DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - String isoDate = format.format(date); - return new Person3(person.getName(), isoDate); - - } else if (source instanceof Person3) { - Person3 person = (Person3) source; - DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - Date date = null; - try { - date = format.parse(person.getDtob()); - - } catch (ParseException e) { - throw new MappingException("Converter MyCustomConvertor " - + "used incorrectly:" + e.getMessage()); - } - long timestamp = date.getTime(); - return new Personne3(person.getName(), timestamp); - - } else { - throw new MappingException("Converter MyCustomConvertor " - + "used incorrectly. Arguments passed in were:" + dest - + " and " + source); - - } - } - -} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person2.java b/dozer-tutorial/src/main/java/com/baeldung/dozer/Person2.java deleted file mode 100644 index 1920f2868c..0000000000 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person2.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.dozer; - -public class Person2 { - private String name; - private String nickname; - private int age; - - public Person2() { - - } - - public Person2(String name, String nickname, int age) { - super(); - this.name = name; - this.nickname = nickname; - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getNickname() { - return nickname; - } - - public void setNickname(String nickname) { - this.nickname = nickname; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne2.java b/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne2.java deleted file mode 100644 index 1cd3f7cdfd..0000000000 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne2.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.dozer; - -import org.dozer.Mapping; - -public class Personne2 { - private String nom; - private String surnom; - private int age; - - public Personne2() { - - } - - public Personne2(String nom, String surnom, int age) { - super(); - this.nom = nom; - this.surnom = surnom; - this.age = age; - } - - @Mapping("name") - public String getNom() { - return nom; - } - - @Mapping("nickname") - public String getSurnom() { - return surnom; - } - - public void setNom(String nom) { - this.nom = nom; - } - - public void setSurnom(String surnom) { - this.surnom = surnom; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Source2.java b/dozer-tutorial/src/main/java/com/baeldung/dozer/Source2.java deleted file mode 100644 index ca7e5baaea..0000000000 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Source2.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.dozer; - -public class Source2 { - private String id; - private double points; - - public Source2() { - - } - - public Source2(String id, double points) { - super(); - this.id = id; - this.points = points; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public double getPoints() { - return points; - } - - public void setPoints(double points) { - this.points = points; - } - - @Override - public String toString() { - return "Source2 [id=" + id + ", points=" + points + "]"; - } - -} diff --git a/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java b/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java deleted file mode 100644 index 2b173a045b..0000000000 --- a/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.baeldung.dozer; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.dozer.DozerBeanMapper; -import org.dozer.loader.api.BeanMappingBuilder; -import org.junit.Before; -import org.junit.Test; - -public class DozerTest { - - private DozerBeanMapper mapper = new DozerBeanMapper(); - - @Before - public void before() throws Exception { - mapper = new DozerBeanMapper(); - } - - private BeanMappingBuilder builder = new BeanMappingBuilder() { - - @Override - protected void configure() { - mapping(Person.class, Personne.class).fields("name", "nom").fields( - "nickname", "surnom"); - - } - }; - private BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() { - - @Override - protected void configure() { - mapping(Person.class, Personne.class).fields("name", "nom") - .fields("nickname", "surnom").exclude("age"); - - } - }; - - @Test - public void givenApiMapper_whenMaps_thenCorrect() { - Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", - 70); - mapper.addMapping(builder); - Person englishAppPerson = mapper.map(frenchAppPerson, Person.class); - assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); - assertEquals(englishAppPerson.getNickname(), - frenchAppPerson.getSurnom()); - assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); - } - - @Test - public void givenApiMapper_whenMapsOnlySpecifiedFields_thenCorrect() { - Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70); - mapper.addMapping(builderMinusAge); - Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); - assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); - assertEquals(frenchAppPerson.getSurnom(), - englishAppPerson.getNickname()); - assertEquals(frenchAppPerson.getAge(), 0); - } - - @Test - public void givenApiMapper_whenMapsBidirectionally_thenCorrect() { - Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70); - mapper.addMapping(builder); - Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); - assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); - assertEquals(frenchAppPerson.getSurnom(), - englishAppPerson.getNickname()); - assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); - } - - @Test - public void givenSourceObjectAndDestClass_whenMapsSameNameFieldsCorrectly_thenCorrect() { - Source source = new Source("Baeldung", 10); - Dest dest = mapper.map(source, Dest.class); - assertEquals(dest.getName(), "Baeldung"); - assertEquals(dest.getAge(), 10); - } - - @Test - public void givenSourceObjectAndDestObject_whenMapsSameNameFieldsCorrectly_thenCorrect() { - Source source = new Source("Baeldung", 10); - Dest dest = new Dest(); - mapper.map(source, dest); - assertEquals(dest.getName(), "Baeldung"); - assertEquals(dest.getAge(), 10); - } - - @Test - public void givenSourceAndDestWithDifferentFieldTypes_whenMapsAndAutoConverts_thenCorrect() { - Source2 source = new Source2("320", 15.2); - Dest2 dest = mapper.map(source, Dest2.class); - assertEquals(dest.getId(), 320); - assertEquals(dest.getPoints(), 15); - } - - @Test - public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMaps_thenCorrect() { - List mappingFiles = new ArrayList<>(); - mappingFiles.add("dozer_mapping.xml"); - Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", - 70); - mapper.setMappingFiles(mappingFiles); - Person englishAppPerson = mapper.map(frenchAppPerson, Person.class); - assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); - assertEquals(englishAppPerson.getNickname(), - frenchAppPerson.getSurnom()); - assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); - } - - @Test - public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMapsBidirectionally_thenCorrect() { - List mappingFiles = new ArrayList<>(); - mappingFiles.add("dozer_mapping.xml"); - Person englishAppPerson = new Person("Dwayne Johnson", "The Rock", 44); - mapper.setMappingFiles(mappingFiles); - Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); - assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); - assertEquals(frenchAppPerson.getSurnom(), - englishAppPerson.getNickname()); - assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); - } - -// @Test -// public void givenMappingFileOutsideClasspath_whenMaps_thenCorrect() { -// List mappingFiles = new ArrayList<>(); -// mappingFiles.add("file:E:\\dozer_mapping.xml"); -// Person englishAppPerson = new Person("Marshall Bruce Mathers III", -// "Eminem", 43); -// mapper.setMappingFiles(mappingFiles); -// Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); -// assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); -// assertEquals(frenchAppPerson.getSurnom(), -// englishAppPerson.getNickname()); -// assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); -// } - - @Test - public void givenSrcAndDest_whenMapsOnlySpecifiedFields_thenCorrect() { - List mappingFiles = new ArrayList<>(); - mappingFiles.add("dozer_mapping2.xml"); - Person englishAppPerson = new Person("Shawn Corey Carter", "Jay Z", 46); - mapper.setMappingFiles(mappingFiles); - Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); - assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); - assertEquals(frenchAppPerson.getSurnom(), - englishAppPerson.getNickname()); - assertEquals(frenchAppPerson.getAge(), 0); - } - - @Test - public void givenAnnotatedSrcFields_whenMapsToRightDestField_thenCorrect() { - Person2 englishAppPerson = new Person2("Jean-Claude Van Damme", "JCVD", - 55); - Personne2 frenchAppPerson = mapper.map(englishAppPerson, - Personne2.class); - assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); - assertEquals(frenchAppPerson.getSurnom(), - englishAppPerson.getNickname()); - assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); - } - - @Test - public void givenAnnotatedSrcFields_whenMapsToRightDestFieldBidirectionally_thenCorrect() { - Personne2 frenchAppPerson = new Personne2("Jason Statham", - "transporter", 49); - Person2 englishAppPerson = mapper.map(frenchAppPerson, Person2.class); - assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); - assertEquals(englishAppPerson.getNickname(), - frenchAppPerson.getSurnom()); - assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); - } - - @Test - public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvert_thenCorrect() { - String dateTime = "2007-06-26T21:22:39Z"; - long timestamp = new Long("1182882159000"); - Person3 person = new Person3("Rich", dateTime); - mapper.setMappingFiles(Arrays - .asList(new String[] { "dozer_custom_convertor.xml" })); - Personne3 person0 = mapper.map(person, Personne3.class); - assertEquals(timestamp, person0.getDtob()); - } - - @Test - public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvertBidirectionally_thenCorrect() { - String dateTime = "2007-06-26T21:22:39Z"; - long timestamp = new Long("1182882159000"); - Personne3 person = new Personne3("Rich", timestamp); - mapper.setMappingFiles(Arrays - .asList(new String[] { "dozer_custom_convertor.xml" })); - Person3 person0 = mapper.map(person, Person3.class); - assertEquals(dateTime, person0.getDtob()); - } - -} diff --git a/dozer/pom.xml b/dozer/pom.xml new file mode 100644 index 0000000000..35ac2394a6 --- /dev/null +++ b/dozer/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + + com.baeldung + dozer + 1.0 + + dozer + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 7 + 7 + + + + + + + + org.slf4j + slf4j-api + 1.7.5 + + + + org.slf4j + jcl-over-slf4j + 1.7.5 + + + + org.apache.commons + commons-lang3 + 3.2.1 + + + + net.sf.dozer + dozer + 5.5.1 + + + junit + junit + 4.3 + test + + + + + diff --git a/dozer/src/main/java/com/baeldung/dozer/Dest.java b/dozer/src/main/java/com/baeldung/dozer/Dest.java new file mode 100644 index 0000000000..ddffcc29a1 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Dest.java @@ -0,0 +1,33 @@ +package com.baeldung.dozer; + +public class Dest { + private String name; + private int age; + + public Dest() { + + } + + public Dest(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Dest2.java b/dozer/src/main/java/com/baeldung/dozer/Dest2.java new file mode 100644 index 0000000000..bd89af6b2e --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Dest2.java @@ -0,0 +1,38 @@ +package com.baeldung.dozer; + +public class Dest2 { + private int id; + private int points; + + public Dest2() { + + } + + public Dest2(int id, int points) { + super(); + this.id = id; + this.points = points; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getPoints() { + return points; + } + + public void setPoints(int points) { + this.points = points; + } + + @Override + public String toString() { + return "Dest2 [id=" + id + ", points=" + points + "]"; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/MyCustomConvertor.java b/dozer/src/main/java/com/baeldung/dozer/MyCustomConvertor.java new file mode 100644 index 0000000000..3ae095dc51 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/MyCustomConvertor.java @@ -0,0 +1,44 @@ +package com.baeldung.dozer; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.dozer.CustomConverter; +import org.dozer.MappingException; + +public class MyCustomConvertor implements CustomConverter { + + @Override + public Object convert(Object dest, Object source, Class> arg2, Class> arg3) { + if (source == null) { + return null; + } + if (source instanceof Personne3) { + Personne3 person = (Personne3) source; + Date date = new Date(person.getDtob()); + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + String isoDate = format.format(date); + return new Person3(person.getName(), isoDate); + + } else if (source instanceof Person3) { + Person3 person = (Person3) source; + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + Date date = null; + try { + date = format.parse(person.getDtob()); + + } catch (ParseException e) { + throw new MappingException("Converter MyCustomConvertor " + "used incorrectly:" + e.getMessage()); + } + long timestamp = date.getTime(); + return new Personne3(person.getName(), timestamp); + + } else { + throw new MappingException("Converter MyCustomConvertor " + "used incorrectly. Arguments passed in were:" + dest + " and " + source); + + } + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Person.java b/dozer/src/main/java/com/baeldung/dozer/Person.java new file mode 100644 index 0000000000..030c6e9de7 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.dozer; + +public class Person { + private String name; + private String nickname; + private int age; + + public Person() { + + } + + public Person(String name, String nickname, int age) { + super(); + this.name = name; + this.nickname = nickname; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Person2.java b/dozer/src/main/java/com/baeldung/dozer/Person2.java new file mode 100644 index 0000000000..741dfd2fd1 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Person2.java @@ -0,0 +1,43 @@ +package com.baeldung.dozer; + +public class Person2 { + private String name; + private String nickname; + private int age; + + public Person2() { + + } + + public Person2(String name, String nickname, int age) { + super(); + this.name = name; + this.nickname = nickname; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Person3.java b/dozer/src/main/java/com/baeldung/dozer/Person3.java new file mode 100644 index 0000000000..a2a37bed53 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Person3.java @@ -0,0 +1,38 @@ +package com.baeldung.dozer; + +public class Person3 { + private String name; + private String dtob; + + public Person3() { + + } + + public Person3(String name, String dtob) { + super(); + this.name = name; + this.dtob = dtob; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDtob() { + return dtob; + } + + public void setDtob(String dtob) { + this.dtob = dtob; + } + + @Override + public String toString() { + return "Person3 [name=" + name + ", dtob=" + dtob + "]"; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Personne.java b/dozer/src/main/java/com/baeldung/dozer/Personne.java new file mode 100644 index 0000000000..ff301db416 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Personne.java @@ -0,0 +1,43 @@ +package com.baeldung.dozer; + +public class Personne { + private String nom; + private String surnom; + private int age; + + public Personne() { + + } + + public Personne(String nom, String surnom, int age) { + super(); + this.nom = nom; + this.surnom = surnom; + this.age = age; + } + + public String getNom() { + return nom; + } + + public void setNom(String nom) { + this.nom = nom; + } + + public String getSurnom() { + return surnom; + } + + public void setSurnom(String surnom) { + this.surnom = surnom; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Personne2.java b/dozer/src/main/java/com/baeldung/dozer/Personne2.java new file mode 100644 index 0000000000..825c45fb81 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Personne2.java @@ -0,0 +1,47 @@ +package com.baeldung.dozer; + +import org.dozer.Mapping; + +public class Personne2 { + private String nom; + private String surnom; + private int age; + + public Personne2() { + + } + + public Personne2(String nom, String surnom, int age) { + super(); + this.nom = nom; + this.surnom = surnom; + this.age = age; + } + + @Mapping("name") + public String getNom() { + return nom; + } + + @Mapping("nickname") + public String getSurnom() { + return surnom; + } + + public void setNom(String nom) { + this.nom = nom; + } + + public void setSurnom(String surnom) { + this.surnom = surnom; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Personne3.java b/dozer/src/main/java/com/baeldung/dozer/Personne3.java new file mode 100644 index 0000000000..c55f8da20d --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Personne3.java @@ -0,0 +1,38 @@ +package com.baeldung.dozer; + +public class Personne3 { + private String name; + private long dtob; + + public Personne3() { + + } + + public Personne3(String name, long dtob) { + super(); + this.name = name; + this.dtob = dtob; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getDtob() { + return dtob; + } + + public void setDtob(long dtob) { + this.dtob = dtob; + } + + @Override + public String toString() { + return "Personne3 [name=" + name + ", dtob=" + dtob + "]"; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Source.java b/dozer/src/main/java/com/baeldung/dozer/Source.java new file mode 100644 index 0000000000..d715a5cc16 --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Source.java @@ -0,0 +1,32 @@ +package com.baeldung.dozer; + +public class Source { + private String name; + private int age; + + public Source() { + } + + public Source(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/dozer/src/main/java/com/baeldung/dozer/Source2.java b/dozer/src/main/java/com/baeldung/dozer/Source2.java new file mode 100644 index 0000000000..e722f206ca --- /dev/null +++ b/dozer/src/main/java/com/baeldung/dozer/Source2.java @@ -0,0 +1,38 @@ +package com.baeldung.dozer; + +public class Source2 { + private String id; + private double points; + + public Source2() { + + } + + public Source2(String id, double points) { + super(); + this.id = id; + this.points = points; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public double getPoints() { + return points; + } + + public void setPoints(double points) { + this.points = points; + } + + @Override + public String toString() { + return "Source2 [id=" + id + ", points=" + points + "]"; + } + +} diff --git a/dozer/src/test/java/com/baeldung/dozer/DozerTest.java b/dozer/src/test/java/com/baeldung/dozer/DozerTest.java new file mode 100644 index 0000000000..107aab078d --- /dev/null +++ b/dozer/src/test/java/com/baeldung/dozer/DozerTest.java @@ -0,0 +1,199 @@ +package com.baeldung.dozer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; + +import org.dozer.DozerBeanMapper; +import org.dozer.loader.api.BeanMappingBuilder; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +public class DozerTest { + private final long GMT_DIFFERENCE = 46800000; + + DozerBeanMapper mapper; + + @Before + public void before() throws Exception { + mapper = new DozerBeanMapper(); + } + + BeanMappingBuilder builder = new BeanMappingBuilder() { + + @Override + protected void configure() { + mapping(Person.class, Personne.class).fields("name", "nom").fields("nickname", "surnom"); + + } + }; + BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() { + + @Override + protected void configure() { + mapping(Person.class, Personne.class).fields("name", "nom").fields("nickname", "surnom").exclude("age"); + + } + }; + + @Test + public void givenApiMapper_whenMaps_thenCorrect() { + mapper.addMapping(builder); + + Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", 70); + Person englishAppPerson = mapper.map(frenchAppPerson, Person.class); + + assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); + assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom()); + assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); + } + + @Test + public void givenApiMapper_whenMapsOnlySpecifiedFields_thenCorrect() { + mapper.addMapping(builderMinusAge); + + Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70); + Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); + + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), 0); + } + + @Test + public void givenApiMapper_whenMapsBidirectionally_thenCorrect() { + mapper.addMapping(builder); + + Person englishAppPerson = new Person("Sylvester Stallone", "Rambo", 70); + Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); + + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); + } + + @Test + public void givenSourceObjectAndDestClass_whenMapsSameNameFieldsCorrectly_thenCorrect() { + Source source = new Source("Baeldung", 10); + Dest dest = mapper.map(source, Dest.class); + assertEquals(dest.getName(), "Baeldung"); + assertEquals(dest.getAge(), 10); + } + + @Test + public void givenSourceObjectAndDestObject_whenMapsSameNameFieldsCorrectly_thenCorrect() { + Source source = new Source("Baeldung", 10); + Dest dest = new Dest(); + mapper.map(source, dest); + assertEquals(dest.getName(), "Baeldung"); + assertEquals(dest.getAge(), 10); + } + + @Test + public void givenSourceAndDestWithDifferentFieldTypes_whenMapsAndAutoConverts_thenCorrect() { + Source2 source = new Source2("320", 15.2); + Dest2 dest = mapper.map(source, Dest2.class); + assertEquals(dest.getId(), 320); + assertEquals(dest.getPoints(), 15); + } + + @Test + public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMaps_thenCorrect() { + configureMapper("dozer_mapping.xml"); + + Personne frenchAppPerson = new Personne("Sylvester Stallone", "Rambo", 70); + Person englishAppPerson = mapper.map(frenchAppPerson, Person.class); + + assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); + assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom()); + assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); + } + + @Test + public void givenSrcAndDestWithDifferentFieldNamesWithCustomMapper_whenMapsBidirectionally_thenCorrect() { + configureMapper("dozer_mapping.xml"); + + Person englishAppPerson = new Person("Dwayne Johnson", "The Rock", 44); + Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); + + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); + } + + @Ignore("place dozer_mapping.xml at a location of your choice and copy/paste the path after file: in configureMapper method") + @Test + public void givenMappingFileOutsideClasspath_whenMaps_thenCorrect() { + configureMapper("file:e:/dozer_mapping.xml"); + + Person englishAppPerson = new Person("Marshall Bruce Mathers III", "Eminem", 43); + Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); + + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); + } + + @Test + public void givenSrcAndDest_whenMapsOnlySpecifiedFields_thenCorrect() { + configureMapper("dozer_mapping2.xml"); + + Person englishAppPerson = new Person("Shawn Corey Carter", "Jay Z", 46); + Personne frenchAppPerson = mapper.map(englishAppPerson, Personne.class); + + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), 0); + } + + @Test + public void givenAnnotatedSrcFields_whenMapsToRightDestField_thenCorrect() { + Person2 englishAppPerson = new Person2("Jean-Claude Van Damme", "JCVD", 55); + Personne2 frenchAppPerson = mapper.map(englishAppPerson, Personne2.class); + assertEquals(frenchAppPerson.getNom(), englishAppPerson.getName()); + assertEquals(frenchAppPerson.getSurnom(), englishAppPerson.getNickname()); + assertEquals(frenchAppPerson.getAge(), englishAppPerson.getAge()); + } + + @Test + public void givenAnnotatedSrcFields_whenMapsToRightDestFieldBidirectionally_thenCorrect() { + Personne2 frenchAppPerson = new Personne2("Jason Statham", "transporter", 49); + Person2 englishAppPerson = mapper.map(frenchAppPerson, Person2.class); + assertEquals(englishAppPerson.getName(), frenchAppPerson.getNom()); + assertEquals(englishAppPerson.getNickname(), frenchAppPerson.getSurnom()); + assertEquals(englishAppPerson.getAge(), frenchAppPerson.getAge()); + } + + @Test + public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvert_thenCorrect() { + configureMapper("dozer_custom_convertor.xml"); + + String dateTime = "2007-06-26T21:22:39Z"; + long timestamp = new Long("1182882159000"); + + Person3 person = new Person3("Rich", dateTime); + Personne3 person0 = mapper.map(person, Personne3.class); + + long timestampToTest = person0.getDtob(); + assertTrue(timestampToTest == timestamp || timestampToTest >= timestamp - GMT_DIFFERENCE || timestampToTest <= timestamp + GMT_DIFFERENCE); + } + + @Test + public void givenSrcAndDestWithDifferentFieldTypes_whenAbleToCustomConvertBidirectionally_thenCorrect() { + long timestamp = new Long("1182882159000"); + Personne3 person = new Personne3("Rich", timestamp); + configureMapper("dozer_custom_convertor.xml"); + + Person3 person0 = mapper.map(person, Person3.class); + String timestampTest = person0.getDtob(); + + assertTrue(timestampTest.charAt(10) == 'T' && timestampTest.charAt(19) == 'Z'); + } + + public void configureMapper(String... mappingFileUrls) { + mapper.setMappingFiles(Arrays.asList(mappingFileUrls)); + } + +} diff --git a/dozer-tutorial/src/test/resources/dozer_custom_convertor.xml b/dozer/src/test/resources/dozer_custom_convertor.xml similarity index 100% rename from dozer-tutorial/src/test/resources/dozer_custom_convertor.xml rename to dozer/src/test/resources/dozer_custom_convertor.xml diff --git a/dozer-tutorial/src/test/resources/dozer_mapping.xml b/dozer/src/test/resources/dozer_mapping.xml similarity index 100% rename from dozer-tutorial/src/test/resources/dozer_mapping.xml rename to dozer/src/test/resources/dozer_mapping.xml diff --git a/dozer-tutorial/src/test/resources/dozer_mapping2.xml b/dozer/src/test/resources/dozer_mapping2.xml similarity index 100% rename from dozer-tutorial/src/test/resources/dozer_mapping2.xml rename to dozer/src/test/resources/dozer_mapping2.xml diff --git a/gson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/gson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/gson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java new file mode 100644 index 0000000000..5bbf776705 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java @@ -0,0 +1,49 @@ +package org.baeldung.gson.entities; + +import java.util.Date; +import java.util.List; + +public class ActorGson { + + private String imdbId; + private Date dateOfBirth; + private List filmography; + + public ActorGson(String imdbId, Date dateOfBirth, List filmography) { + super(); + this.imdbId = imdbId; + this.dateOfBirth = dateOfBirth; + this.filmography = filmography; + } + + @Override + public String toString() { + return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + } + + public String getImdbId() { + return imdbId; + } + + public void setImdbId(String imdbId) { + this.imdbId = imdbId; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public List getFilmography() { + return filmography; + } + + public void setFilmography(List filmography) { + this.filmography = filmography; + } + + +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/entities/Movie.java b/gson/src/main/java/org/baeldung/gson/entities/Movie.java new file mode 100644 index 0000000000..ee688f228d --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Movie.java @@ -0,0 +1,48 @@ +package org.baeldung.gson.entities; + +import java.util.List; + +public class Movie { + + private String imdbId; + private String director; + private List actors; + + public Movie(String imdbID, String director, List actors) { + super(); + this.imdbId = imdbID; + this.director = director; + this.actors = actors; + } + + @Override + public String toString() { + return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]"; + } + + public String getImdbID() { + return imdbId; + } + + public void setImdbID(String imdbID) { + this.imdbId = imdbID; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public List getActors() { + return actors; + } + + public void setActors(List actors) { + this.actors = actors; + } + + +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/entities/MovieWithNullValue.java b/gson/src/main/java/org/baeldung/gson/entities/MovieWithNullValue.java new file mode 100644 index 0000000000..fe62d51ffb --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/MovieWithNullValue.java @@ -0,0 +1,46 @@ +package org.baeldung.gson.entities; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class MovieWithNullValue { + + @Expose + private String imdbId; + private String director; + + @Expose + private List actors; + + public MovieWithNullValue(String imdbID, String director, List actors) { + super(); + this.imdbId = imdbID; + this.director = director; + this.actors = actors; + } + + public String getImdbID() { + return imdbId; + } + + public void setImdbID(String imdbID) { + this.imdbId = imdbID; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public List getActors() { + return actors; + } + + public void setActors(List actors) { + this.actors = actors; + } +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java new file mode 100644 index 0000000000..70a03500d5 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java @@ -0,0 +1,40 @@ +package org.baeldung.gson.serialization; + +import com.google.gson.*; +import org.baeldung.gson.entities.ActorGson; + +import java.lang.reflect.Type; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; + +public class ActorGsonDeserializer implements JsonDeserializer { + + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + @Override + public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + + JsonObject jsonObject = json.getAsJsonObject(); + + JsonElement jsonImdbId = jsonObject.get("imdbId"); + JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); + JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); + + ArrayList filmList = new ArrayList(); + if (jsonFilmography != null) { + for (int i = 0; i < jsonFilmography.size(); i++) { + filmList.add(jsonFilmography.get(i).getAsString()); + } + } + + ActorGson actorGson = null; + try { + actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return actorGson; + } +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonSerializer.java b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonSerializer.java new file mode 100644 index 0000000000..8f2cd10f5a --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonSerializer.java @@ -0,0 +1,33 @@ +package org.baeldung.gson.serialization; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import org.baeldung.gson.entities.ActorGson; + +import java.lang.reflect.Type; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.stream.Collectors; + +public class ActorGsonSerializer implements JsonSerializer { + + private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + @Override + public JsonElement serialize(ActorGson actor, Type type, JsonSerializationContext jsonSerializationContext) { + + JsonObject actorJsonObj = new JsonObject(); + actorJsonObj.addProperty("IMDB Code", actor.getImdbId()); + actorJsonObj.addProperty("Date Of Birth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); + actorJsonObj.addProperty("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); + actorJsonObj.addProperty("filmography", actor.getFilmography() != null ? convertFilmography(actor.getFilmography()) : null); + + return actorJsonObj; + } + + private String convertFilmography(List filmography) { + return filmography.stream().collect(Collectors.joining("-")); + } +} \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java new file mode 100644 index 0000000000..d87f0f4bd9 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java @@ -0,0 +1,38 @@ +package org.baeldung.gson.deserialization; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.baeldung.gson.entities.ActorGson; +import org.baeldung.gson.entities.Movie; +import org.baeldung.gson.serialization.ActorGsonDeserializer; +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; + +public class GsonDeserializeTest { + + @Test + public void whenSimpleDeserialize_thenCorrect() throws ParseException { + + String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + + Movie outputMovie = new Gson().fromJson(jsonInput, Movie.class); + + String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + Assert.assertEquals(outputMovie.toString(), expectedOutput); + } + + @Test + public void whenCustomDeserialize_thenCorrect() throws ParseException { + + String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + + Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create(); + + Movie outputMovie = gson.fromJson(jsonInput, Movie.class); + + String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + Assert.assertEquals(outputMovie.toString(), expectedOutput); + } +} diff --git a/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java b/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java new file mode 100644 index 0000000000..7d5502b72f --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serialization/GsonSerializeTest.java @@ -0,0 +1,48 @@ +package org.baeldung.gson.serialization; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParser; +import org.baeldung.gson.entities.ActorGson; +import org.baeldung.gson.entities.Movie; +import org.baeldung.gson.entities.MovieWithNullValue; +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; + +public class GsonSerializeTest { + + @Test + public void whenSimpleSerialize_thenCorrect() throws ParseException { + + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); + + String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + Assert.assertEquals(new Gson().toJson(movie), expectedOutput); + } + + @Test + public void whenCustomSerialize_thenCorrect() throws ParseException { + Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().serializeNulls().disableHtmlEscaping().registerTypeAdapter(ActorGson.class, new ActorGsonSerializer()).create(); + + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); + + String expectedOutput = new GsonBuilder() + .setPrettyPrinting() + .serializeNulls() + .disableHtmlEscaping() + .create() + .toJson(new JsonParser() + .parse("{\"imdbId\":null,\"actors\":[{\"IMDB Code\":\"nm2199632\",\"Date Of Birth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); + Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput); + } +} diff --git a/guava/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/guava/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/guava/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/guava/.settings/.jsdtscope b/guava/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/guava/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/guava/.settings/org.eclipse.jdt.core.prefs b/guava/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/guava/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/guava/.settings/org.eclipse.jdt.ui.prefs b/guava/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/guava/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/guava/.settings/org.eclipse.m2e.core.prefs b/guava/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/guava/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/guava/.settings/org.eclipse.m2e.wtp.prefs b/guava/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/guava/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/guava/.settings/org.eclipse.wst.common.component b/guava/.settings/org.eclipse.wst.common.component deleted file mode 100644 index e98377cb0f..0000000000 --- a/guava/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/guava/.settings/org.eclipse.wst.common.project.facet.core.xml b/guava/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f4ef8aa0a5..0000000000 --- a/guava/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/guava/.settings/org.eclipse.wst.jsdt.ui.superType.container b/guava/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/guava/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/guava/.settings/org.eclipse.wst.jsdt.ui.superType.name b/guava/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/guava/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/guava/.settings/org.eclipse.wst.validation.prefs b/guava/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index cacf5451ae..0000000000 --- a/guava/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,14 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300 -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/guava/.settings/org.eclipse.wst.ws.service.policy.prefs b/guava/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/guava/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java index 602205ff9f..1d19423f7e 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java @@ -11,91 +11,91 @@ import com.google.common.base.Function; public class GuavaMapFromSet extends AbstractMap { - private class SingleEntry implements Entry { - private K key; + private class SingleEntry implements Entry { + private K key; - public SingleEntry( K key) { - this.key = key; - } + public SingleEntry(K key) { + this.key = key; + } - @Override - public K getKey() { - return this.key; - } + @Override + public K getKey() { + return this.key; + } - @Override - public V getValue() { - V value = GuavaMapFromSet.this.cache.get(this.key); - if (value == null) { - value = GuavaMapFromSet.this.function.apply(this.key); - GuavaMapFromSet.this.cache.put(this.key, value); - } - return value; - } + @Override + public V getValue() { + V value = GuavaMapFromSet.this.cache.get(this.key); + if (value == null) { + value = GuavaMapFromSet.this.function.apply(this.key); + GuavaMapFromSet.this.cache.put(this.key, value); + } + return value; + } - @Override - public V setValue( V value) { - throw new UnsupportedOperationException(); - } - } + @Override + public V setValue(V value) { + throw new UnsupportedOperationException(); + } + } - private class MyEntrySet extends AbstractSet> { + private class MyEntrySet extends AbstractSet> { - public class EntryIterator implements Iterator> { - private Iterator inner; + public class EntryIterator implements Iterator> { + private Iterator inner; - public EntryIterator() { - this.inner = MyEntrySet.this.keys.iterator(); - } + public EntryIterator() { + this.inner = MyEntrySet.this.keys.iterator(); + } - @Override - public boolean hasNext() { - return this.inner.hasNext(); - } + @Override + public boolean hasNext() { + return this.inner.hasNext(); + } - @Override - public Map.Entry next() { - K key = this.inner.next(); - return new SingleEntry(key); - } + @Override + public Map.Entry next() { + K key = this.inner.next(); + return new SingleEntry(key); + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } - private Set keys; + private Set keys; - public MyEntrySet( Set keys) { - this.keys = keys; - } + public MyEntrySet(Set keys) { + this.keys = keys; + } - @Override - public Iterator> iterator() { - return new EntryIterator(); - } + @Override + public Iterator> iterator() { + return new EntryIterator(); + } - @Override - public int size() { - return this.keys.size(); - } + @Override + public int size() { + return this.keys.size(); + } - } + } - private WeakHashMap cache; - private Set> entries; - private Function super K, ? extends V> function; + private WeakHashMap cache; + private Set> entries; + private Function super K, ? extends V> function; - public GuavaMapFromSet( Set keys, Function super K, ? extends V> function) { - this.function = function; - this.cache = new WeakHashMap(); - this.entries = new MyEntrySet(keys); - } + public GuavaMapFromSet(Set keys, Function super K, ? extends V> function) { + this.function = function; + this.cache = new WeakHashMap(); + this.entries = new MyEntrySet(keys); + } - @Override - public Set> entrySet() { - return this.entries; - } + @Override + public Set> entrySet() { + return this.entries; + } } diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java index 9abb5d14a9..7dc4550c09 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java @@ -13,54 +13,52 @@ import com.google.common.base.Function; public class GuavaMapFromSetTests { - @Test - public void givenStringSet_whenMapsToElementLength_thenCorrect() { - Function function = new Function() { + @Test + public void givenStringSet_whenMapsToElementLength_thenCorrect() { + Function function = new Function() { + @Override + public String apply(Integer from) { + return Integer.toBinaryString(from); + } + }; + Set set = new TreeSet<>(Arrays.asList(32, 64, 128)); + Map map = new GuavaMapFromSet(set, function); + assertTrue(map.get(32).equals("100000") + && map.get(64).equals("1000000") + && map.get(128).equals("10000000")); + } - @Override - public String apply(Integer from) { - return Integer.toBinaryString(from.intValue()); - } - }; - Set set = (Set) new TreeSet(Arrays.asList( - 32, 64, 128)); - Map map = new GuavaMapFromSet(set, - function); - assertTrue(map.get(32).equals("100000") - && map.get(64).equals("1000000") - && map.get(128).equals("10000000")); - } + @Test + public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() { + Function function = new Function() { - @Test - public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() { - Function function = new Function() { + @Override + public Integer apply(String from) { + return from.length(); + } + }; + Set set = new TreeSet<>(Arrays.asList( + "four", "three", "twelve")); + Map map = new GuavaMapFromSet(set, + function); + assertTrue(map.get("four") == 4 && map.get("three") == 5 + && map.get("twelve") == 6); + } - @Override - public Integer apply(String from) { - return from.length(); - } - }; - Set set = (Set) new TreeSet(Arrays.asList( - "four", "three", "twelve")); - Map map = new GuavaMapFromSet(set, - function); - assertTrue(map.get("four") == 4 && map.get("three") == 5 - && map.get("twelve") == 6); - } - @Test - public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() { - Function function = new Function() { + @Test + public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() { + Function function = new Function() { - @Override - public Integer apply(String from) { - return from.length(); - } - }; - Set set = (Set) new TreeSet(Arrays.asList( - "four", "three", "twelve")); - Map map = new GuavaMapFromSet(set, - function); - set.add("one"); - assertTrue(map.get("one") == 3 && map.size()==4); - } + @Override + public Integer apply(String from) { + return from.length(); + } + }; + Set set = new TreeSet<>(Arrays.asList( + "four", "three", "twelve")); + Map map = new GuavaMapFromSet(set, + function); + set.add("one"); + assertTrue(map.get("one") == 3 && map.size() == 4); + } } diff --git a/httpclient/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/httpclient/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/httpclient/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/httpclient/.settings/.jsdtscope b/httpclient/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/httpclient/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/httpclient/.settings/org.eclipse.jdt.core.prefs b/httpclient/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/httpclient/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/httpclient/.settings/org.eclipse.m2e.core.prefs b/httpclient/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/httpclient/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/httpclient/.settings/org.eclipse.m2e.wtp.prefs b/httpclient/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/httpclient/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/httpclient/.settings/org.eclipse.wst.common.component b/httpclient/.settings/org.eclipse.wst.common.component deleted file mode 100644 index e98377cb0f..0000000000 --- a/httpclient/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/httpclient/.settings/org.eclipse.wst.common.project.facet.core.xml b/httpclient/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f4ef8aa0a5..0000000000 --- a/httpclient/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.container b/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.name b/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/httpclient/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/httpclient/.settings/org.eclipse.wst.validation.prefs b/httpclient/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index cacf5451ae..0000000000 --- a/httpclient/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,14 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300 -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/httpclient/.settings/org.eclipse.wst.ws.service.policy.prefs b/httpclient/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/httpclient/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 381adfbcd5..7867bbb955 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -12,16 +12,16 @@ org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE - + 1.8 - 1.4.10 + 1.5.4 0.20.7 @@ -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/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/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java index b66ed4507f..e85f3d7199 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -1,23 +1,22 @@ package com.baeldung.hystrix; -import com.netflix.hystrix.*; -import com.netflix.hystrix.collapser.RequestCollapserFactory; +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.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.concurrent.ExecutionException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class HystrixTimeoutTest { private HystrixCommand.Setter config; - private HystrixCommandProperties.Setter commandProperties ; + private HystrixCommandProperties.Setter commandProperties; @Rule @@ -27,8 +26,8 @@ public class HystrixTimeoutTest { public void setup() { commandProperties = HystrixCommandProperties.Setter(); config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); } @Test @@ -118,12 +117,12 @@ public class HystrixTimeoutTest { equalTo("Success")); } - public String invokeRemoteService(long timeout) throws InterruptedException{ + public String invokeRemoteService(long timeout) throws InterruptedException { String response = null; - try{ + try { response = new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(timeout)).execute(); - }catch(HystrixRuntimeException ex){ + } 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..8f443fc5a4 --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -0,0 +1,32 @@ +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_whenExistingClientCalled_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + assertThat(hystrixController.index(), equalTo("Success")); + } + + +} diff --git a/jackson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/jackson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/jackson/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/jackson/.settings/.jsdtscope b/jackson/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/jackson/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/jackson/.settings/org.eclipse.jdt.core.prefs b/jackson/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/jackson/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/jackson/.settings/org.eclipse.jdt.ui.prefs b/jackson/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/jackson/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/jackson/.settings/org.eclipse.m2e.core.prefs b/jackson/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/jackson/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/jackson/.settings/org.eclipse.m2e.wtp.prefs b/jackson/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/jackson/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/jackson/.settings/org.eclipse.wst.common.component b/jackson/.settings/org.eclipse.wst.common.component deleted file mode 100644 index e98377cb0f..0000000000 --- a/jackson/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/jackson/.settings/org.eclipse.wst.common.project.facet.core.xml b/jackson/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f4ef8aa0a5..0000000000 --- a/jackson/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/jackson/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/jackson/.settings/org.eclipse.wst.validation.prefs b/jackson/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index cacf5451ae..0000000000 --- a/jackson/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,14 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300 -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/jackson/.settings/org.eclipse.wst.ws.service.policy.prefs b/jackson/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/jackson/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java new file mode 100644 index 0000000000..68cd6117d6 --- /dev/null +++ b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java @@ -0,0 +1,52 @@ +package org.baeldung.jackson.entities; + +import java.util.Date; +import java.util.List; + +public class ActorJackson { + + private String imdbId; + private Date dateOfBirth; + private List filmography; + + public ActorJackson() { + super(); + } + + public ActorJackson(String imdbId, Date dateOfBirth, List filmography) { + super(); + this.imdbId = imdbId; + this.dateOfBirth = dateOfBirth; + this.filmography = filmography; + } + + @Override + public String toString() { + return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + } + + public String getImdbId() { + return imdbId; + } + + public void setImdbId(String imdbId) { + this.imdbId = imdbId; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public List getFilmography() { + return filmography; + } + + public void setFilmography(List filmography) { + this.filmography = filmography; + } + +} diff --git a/jackson/src/main/java/org/baeldung/jackson/entities/Movie.java b/jackson/src/main/java/org/baeldung/jackson/entities/Movie.java new file mode 100644 index 0000000000..68b7464563 --- /dev/null +++ b/jackson/src/main/java/org/baeldung/jackson/entities/Movie.java @@ -0,0 +1,50 @@ +package org.baeldung.jackson.entities; + +import java.util.List; + +public class Movie { + + private String imdbId; + private String director; + private List actors; + + public Movie(String imdbId, String director, List actors) { + super(); + this.imdbId = imdbId; + this.director = director; + this.actors = actors; + } + + public Movie() { + super(); + } + + @Override + public String toString() { + return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]"; + } + + public String getImdbId() { + return imdbId; + } + + public void setImdbId(String imdbId) { + this.imdbId = imdbId; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public List getActors() { + return actors; + } + + public void setActors(List actors) { + this.actors = actors; + } +} \ No newline at end of file diff --git a/jackson/src/main/java/org/baeldung/jackson/entities/MovieWithNullValue.java b/jackson/src/main/java/org/baeldung/jackson/entities/MovieWithNullValue.java new file mode 100644 index 0000000000..23f5de2858 --- /dev/null +++ b/jackson/src/main/java/org/baeldung/jackson/entities/MovieWithNullValue.java @@ -0,0 +1,46 @@ +package org.baeldung.jackson.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.List; + +public class MovieWithNullValue { + + private String imdbId; + + @JsonIgnore + private String director; + + private List actors; + + public MovieWithNullValue(String imdbID, String director, List actors) { + super(); + this.imdbId = imdbID; + this.director = director; + this.actors = actors; + } + + public String getImdbID() { + return imdbId; + } + + public void setImdbID(String imdbID) { + this.imdbId = imdbID; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public List getActors() { + return actors; + } + + public void setActors(List actors) { + this.actors = actors; + } +} \ No newline at end of file diff --git a/jackson/src/main/java/org/baeldung/jackson/serialization/ActorJacksonSerializer.java b/jackson/src/main/java/org/baeldung/jackson/serialization/ActorJacksonSerializer.java new file mode 100644 index 0000000000..c33cf59482 --- /dev/null +++ b/jackson/src/main/java/org/baeldung/jackson/serialization/ActorJacksonSerializer.java @@ -0,0 +1,31 @@ +package org.baeldung.jackson.serialization; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.stream.Collectors; + +import org.baeldung.jackson.entities.ActorJackson; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +public class ActorJacksonSerializer extends StdSerializer { + + private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + public ActorJacksonSerializer(Class t) { + super(t); + } + + @Override + public void serialize(ActorJackson actor, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + + jsonGenerator.writeStartObject(); + jsonGenerator.writeStringField("imdbId", actor.getImdbId()); + jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); + jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); + jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-"))); + jsonGenerator.writeEndObject(); + } +} \ No newline at end of file diff --git a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java new file mode 100644 index 0000000000..71d5ad3d81 --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java @@ -0,0 +1,40 @@ +package org.baeldung.jackson.deserialization; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.baeldung.jackson.entities.Movie; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +public class JacksonDeserializeTest { + + @Test + public void whenSimpleDeserialize_thenCorrect() throws IOException { + + String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + ObjectMapper mapper = new ObjectMapper(); + Movie movie = mapper.readValue(jsonInput, Movie.class); + + String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + Assert.assertEquals(movie.toString(), expectedOutput); + } + + @Test + public void whenCustomDeserialize_thenCorrect() throws IOException { + + String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + + ObjectMapper mapper = new ObjectMapper(); + final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + mapper.setDateFormat(df); + + Movie movie = mapper.readValue(jsonInput, Movie.class); + + String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + Assert.assertEquals(movie.toString(), expectedOutput); + } + +} diff --git a/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java new file mode 100644 index 0000000000..6c8aa90fae --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java @@ -0,0 +1,60 @@ +package org.baeldung.jackson.serialization; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; + +import org.baeldung.jackson.entities.ActorJackson; +import org.baeldung.jackson.entities.Movie; +import org.baeldung.jackson.entities.MovieWithNullValue; +import org.baeldung.jackson.serialization.ActorJacksonSerializer; +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.module.SimpleModule; + +public class JacksonSerializeTest { + + @Test + public void whenSimpleSerialize_thenCorrect() throws JsonProcessingException, ParseException { + + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); + + ObjectMapper mapper = new ObjectMapper(); + String jsonResult = mapper.writeValueAsString(movie); + + String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401439600000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + Assert.assertEquals(jsonResult, expectedOutput); + } + + @Test + public void whenCustomSerialize_thenCorrect() throws ParseException, IOException { + + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + + ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); + + SimpleModule module = new SimpleModule(); + module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); + ObjectMapper mapper = new ObjectMapper(); + + String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + + Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); + String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + + Assert.assertEquals(jsonResult, expectedOutput); + } +} diff --git a/jsf/pom.xml b/jsf/pom.xml index b80bcfb416..6a4b358252 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -27,7 +27,7 @@ javax.el - el-api + javax.el-api ${javax.el.version} @@ -126,8 +126,8 @@ 4.2.5.RELEASE - 2.1.7 - 2.2 + 2.2.13 + 3.0.0 1.7.13 diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index a13f0890b5..16d9f80d89 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -1,13 +1,17 @@ package com.baeldung.springintegration.controllers; -import java.util.Random; import javax.annotation.PostConstruct; +import javax.el.ELContextEvent; +import javax.el.ELContextListener; +import javax.el.LambdaExpression; import javax.faces.application.Application; import javax.faces.application.FacesMessage; +import javax.el.LambdaExpression; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; -import javax.faces.component.html.HtmlInputText; import javax.faces.context.FacesContext; +import java.util.Collection; +import java.util.Random; @ManagedBean(name = "ELBean") @ViewScoped @@ -16,22 +20,37 @@ public class ELSampleBean { private String firstName; private String lastName; private String pageDescription = "This page demos JSF EL Basics"; + public static final String constantField = "THIS_IS_NOT_CHANGING_ANYTIME_SOON"; private int pageCounter; private Random randomIntGen = new Random(); @PostConstruct public void init() { pageCounter = randomIntGen.nextInt(); + FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { + @Override + public void contextCreated(ELContextEvent evt) { + evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); + } + }); } public void save() { } + + public static String constantField() { + return constantField; + } public void saveFirstName(String firstName) { this.firstName = firstName; } + public Long multiplyValue(LambdaExpression expr) { + Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + return theResult; + } public void saveByELEvaluation() { firstName = (String) evaluateEL("#{firstName.value}", String.class); diff --git a/jsf/src/main/webapp/el3_intro.xhtml b/jsf/src/main/webapp/el3_intro.xhtml new file mode 100644 index 0000000000..3f1f407a08 --- /dev/null +++ b/jsf/src/main/webapp/el3_intro.xhtml @@ -0,0 +1,35 @@ + + + + + Baeldung | Expression Language 3.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/json/src/main/webapp/index.html b/json/src/main/webapp/index.html new file mode 100644 index 0000000000..5c41c8a173 --- /dev/null +++ b/json/src/main/webapp/index.html @@ -0,0 +1,27 @@ + + + + Introduction to JSONForms + + + + + + + + + + + + Introduction to JSONForms + + + Bound data: {{data}} + + + + + + + + diff --git a/json/src/main/webapp/js/app.js b/json/src/main/webapp/js/app.js new file mode 100644 index 0000000000..484637bef4 --- /dev/null +++ b/json/src/main/webapp/js/app.js @@ -0,0 +1,15 @@ +'use strict'; + +var app = angular.module('jsonforms-intro', ['jsonforms']); +app.controller('MyController', ['$scope', 'Schema', 'UISchema', function($scope, Schema, UISchema) { + + $scope.schema = Schema; + + $scope.uiSchema = UISchema; + + $scope.data = { + "id": 1, + "name": "Lampshade", + "price": 1.85 + }; +}]); diff --git a/json/src/main/webapp/js/schema.js b/json/src/main/webapp/js/schema.js new file mode 100644 index 0000000000..34025868b9 --- /dev/null +++ b/json/src/main/webapp/js/schema.js @@ -0,0 +1,27 @@ +'use strict'; + +var app = angular.module('jsonforms-intro'); +app.value('Schema', + { + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Product", + "description": "A product from the catalog", + "type": "object", + "properties": { + "id": { + "description": "The unique identifier for a product", + "type": "integer" + }, + "name": { + "description": "Name of the product", + "type": "string" + }, + "price": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + }, + "required": ["id", "name", "price"] + } +); diff --git a/json/src/main/webapp/js/ui-schema.js b/json/src/main/webapp/js/ui-schema.js new file mode 100644 index 0000000000..aea5ac79c0 --- /dev/null +++ b/json/src/main/webapp/js/ui-schema.js @@ -0,0 +1,22 @@ +'use strict'; + +var app = angular.module('jsonforms-intro'); +app.value('UISchema', + { + "type": "HorizontalLayout", + "elements": [ + { + "type": "Control", + "scope": { "$ref": "#/properties/id" } + }, + { + "type": "Control", + "scope": { "$ref": "#/properties/name" } + }, + { + "type": "Control", + "scope": { "$ref": "#/properties/price" } + }, + ] + } +); diff --git a/json/src/main/webapp/package.json b/json/src/main/webapp/package.json new file mode 100644 index 0000000000..2f2d6c9ffa --- /dev/null +++ b/json/src/main/webapp/package.json @@ -0,0 +1,11 @@ +{ + "name": "jsonforms-intro", + "description": "Introduction to JSONForms", + "version": "0.0.1", + "license": "MIT", + "dependencies": { + "typings": "0.6.5", + "jsonforms": "0.0.19", + "bootstrap": "3.3.6" + } +} \ No newline at end of file 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/mocks/jmockit/README.md b/mocks/jmockit/README.md index d04a07fdc5..db78b2a3ac 100644 --- a/mocks/jmockit/README.md +++ b/mocks/jmockit/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [JMockit 101](http://www.baeldung.com/jmockit-101) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) +- [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics) diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java new file mode 100644 index 0000000000..4d25f466a6 --- /dev/null +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java @@ -0,0 +1,20 @@ +package org.baeldung.mocks.jmockit; + +public class AdvancedCollaborator { + int i; + private int privateField = 5; + public AdvancedCollaborator(){} + public AdvancedCollaborator(String string) throws Exception{ + i = string.length(); + } + public String methodThatCallsPrivateMethod(int i){ + return privateMethod() + i; + } + public int methodThatReturnsThePrivateField(){ + return privateField; + } + private String privateMethod(){ + return "default:"; + } + class InnerAdvancedCollaborator{} +} diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorTest.java b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorTest.java new file mode 100644 index 0000000000..aaabe44f66 --- /dev/null +++ b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorTest.java @@ -0,0 +1,110 @@ +package org.baeldung.mocks.jmockit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; + +import org.baeldung.mocks.jmockit.AdvancedCollaborator.InnerAdvancedCollaborator; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Deencapsulation; +import mockit.Expectations; +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.Tested; +import mockit.integration.junit4.JMockit; + +@RunWith(JMockit.class) +public class AdvancedCollaboratorTest & Comparable>> { + + @Tested + private AdvancedCollaborator mock; + + @Mocked + private MultiMock multiMock; + + @Test + public void testToMockUpPrivateMethod() { + new MockUp() { + @Mock + private String privateMethod() { + return "mocked: "; + } + }; + String res = mock.methodThatCallsPrivateMethod(1); + assertEquals("mocked: 1", res); + } + + @Test + public void testToMockUpDifficultConstructor() throws Exception { + new MockUp() { + @Mock + public void $init(Invocation invocation, String string) { + ((AdvancedCollaborator) invocation.getInvokedInstance()).i = 1; + } + }; + AdvancedCollaborator coll = new AdvancedCollaborator(null); + assertEquals(1, coll.i); + } + + @Test + public void testToCallPrivateMethodsDirectly() { + Object value = Deencapsulation.invoke(mock, "privateMethod"); + assertEquals("default:", value); + } + + @Test + public void testToSetPrivateFieldDirectly() { + Deencapsulation.setField(mock, "privateField", 10); + assertEquals(10, mock.methodThatReturnsThePrivateField()); + } + + @Test + public void testToGetPrivateFieldDirectly() { + int value = Deencapsulation.getField(mock, "privateField"); + assertEquals(5, value); + } + + @Test + public void testToCreateNewInstanceDirectly() { + AdvancedCollaborator coll = Deencapsulation.newInstance(AdvancedCollaborator.class, "foo"); + assertEquals(3, coll.i); + } + + @Test + public void testToCreateNewInnerClassInstanceDirectly() { + InnerAdvancedCollaborator innerCollaborator = Deencapsulation.newInnerInstance(InnerAdvancedCollaborator.class, mock); + assertNotNull(innerCollaborator); + } + + @Test + @SuppressWarnings("unchecked") + public void testMultipleInterfacesWholeTest() { + new Expectations() { + { + multiMock.get(5); result = "foo"; + multiMock.compareTo((List) any); result = 0; + } + }; + assertEquals("foo", multiMock.get(5)); + assertEquals(0, multiMock.compareTo(new ArrayList<>())); + } + + @Test + @SuppressWarnings("unchecked") + public & Comparable>> void testMultipleInterfacesOneMethod(@Mocked M mock) { + new Expectations() { + { + mock.get(5); result = "foo"; + mock.compareTo((List) any); + result = 0; } + }; + assertEquals("foo", mock.get(5)); + assertEquals(0, mock.compareTo(new ArrayList<>())); + } +} diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingTest.java b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingTest.java new file mode 100644 index 0000000000..729cb30cd2 --- /dev/null +++ b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingTest.java @@ -0,0 +1,57 @@ +package org.baeldung.mocks.jmockit; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Expectations; +import mockit.Injectable; +import mockit.Mocked; +import mockit.Tested; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; + +@RunWith(JMockit.class) +public class ReusingTest { + + @Injectable + private Collaborator collaborator; + + @Mocked + private Model model; + + @Tested + private Performer performer; + + @Before + public void setup(){ + new Expectations(){{ + model.getInfo(); result = "foo"; minTimes = 0; + collaborator.collaborate("foo"); result = true; minTimes = 0; + }}; + } + + @Test + public void testWithSetup() { + performer.perform(model); + verifyTrueCalls(1); + } + + protected void verifyTrueCalls(int calls){ + new Verifications(){{ + collaborator.receive(true); times = calls; + }}; + } + + final class TrueCallsVerification extends Verifications{ + public TrueCallsVerification(int calls){ + collaborator.receive(true); times = calls; + } + } + + @Test + public void testWithFinalClass() { + performer.perform(model); + new TrueCallsVerification(1); + } +} diff --git a/mutation-testing/pom.xml b/mutation-testing/pom.xml index 83012ab8fe..cdee59fcb4 100644 --- a/mutation-testing/pom.xml +++ b/mutation-testing/pom.xml @@ -1,38 +1,77 @@ - 4.0.0 - com.baeldung - mutation-testing - 0.1-SNAPSHOT - mutation-testing - - - org.pitest - pitest-parent - 1.1.10 - pom - - - junit - junit - 4.9 - - - - - - org.pitest - pitest-maven - 1.1.10 - - - com.baeldung.testing.mutation.* - - - com.baeldung.mutation.test.* - - - - - - \ No newline at end of file + 4.0.0 + com.baeldung + mutation-testing + 0.1-SNAPSHOT + mutation-testing + + + org.pitest + pitest-parent + 1.1.10 + pom + + + junit + junit + 4.9 + + + + + + org.pitest + pitest-maven + 1.1.10 + + + com.baeldung.testing.mutation.* + + + com.baeldung.mutation.test.* + + + + + org.jacoco + jacoco-maven-plugin + 0.7.7.201606060606 + + + + prepare-agent + + + + report + prepare-package + + report + + + + jacoco-check + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + 0.50 + + + + + + + + + + + diff --git a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java b/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java index 1410135883..3add6290f6 100644 --- a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java +++ b/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java @@ -8,21 +8,26 @@ import org.junit.Test; import com.baeldung.testing.mutation.Palindrome; public class TestPalindrome { + @Test + public void whenEmptyString_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } @Test - public void acceptsPalindrome() { + public void whenPalindrom_thanAccept() { Palindrome palindromeTester = new Palindrome(); assertTrue(palindromeTester.isPalindrome("noon")); } @Test - public void rejectsNonPalindrome(){ + public void whenNotPalindrom_thanReject(){ Palindrome palindromeTester = new Palindrome(); assertFalse(palindromeTester.isPalindrome("box")); } @Test - public void rejectsNearPalindrome(){ + public void whenNearPalindrom_thanReject(){ Palindrome palindromeTester = new Palindrome(); assertFalse(palindromeTester.isPalindrome("neon")); } diff --git a/orika/pom.xml b/orika/pom.xml new file mode 100644 index 0000000000..c335b0dc22 --- /dev/null +++ b/orika/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + com.baeldung + orika + 1.0 + + + 1.7.5 + 1.7.5 + 1.4.6 + 4.3 + + + Orika + + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + + org.slf4j + jcl-over-slf4j + ${jcl-over-slf4j.version} + + + + ma.glasnost.orika + orika-core + ${orika-core.version} + + + + junit + junit + ${junit.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 7 + 7 + + + + + + diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Dest.java b/orika/src/main/java/com/baeldung/orika/Dest.java similarity index 74% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Dest.java rename to orika/src/main/java/com/baeldung/orika/Dest.java index 26ba7e3ac4..4f050230ce 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Dest.java +++ b/orika/src/main/java/com/baeldung/orika/Dest.java @@ -1,6 +1,11 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Dest { + @Override + public String toString() { + return "Dest [name=" + name + ", age=" + age + "]"; + } + private String name; private int age; @@ -9,7 +14,6 @@ public class Dest { } public Dest(String name, int age) { - super(); this.name = name; this.age = age; } diff --git a/orika/src/main/java/com/baeldung/orika/Name.java b/orika/src/main/java/com/baeldung/orika/Name.java new file mode 100644 index 0000000000..fcf0214548 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Name.java @@ -0,0 +1,28 @@ +package com.baeldung.orika; + +public class Name { + private String firstName; + private String lastName; + + public Name(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person.java b/orika/src/main/java/com/baeldung/orika/Person.java similarity index 78% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Person.java rename to orika/src/main/java/com/baeldung/orika/Person.java index 7367541951..90ae8dee5e 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person.java +++ b/orika/src/main/java/com/baeldung/orika/Person.java @@ -1,6 +1,12 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Person { + @Override + public String toString() { + return "Person [name=" + name + ", nickname=" + nickname + ", age=" + + age + "]"; + } + private String name; private String nickname; private int age; @@ -10,7 +16,6 @@ public class Person { } public Person(String name, String nickname, int age) { - super(); this.name = name; this.nickname = nickname; this.age = age; diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person3.java b/orika/src/main/java/com/baeldung/orika/Person3.java similarity index 92% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Person3.java rename to orika/src/main/java/com/baeldung/orika/Person3.java index ae1e610aa2..8661edfc10 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Person3.java +++ b/orika/src/main/java/com/baeldung/orika/Person3.java @@ -1,4 +1,4 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Person3 { private String name; @@ -9,7 +9,6 @@ public class Person3 { } public Person3(String name, String dtob) { - super(); this.name = name; this.dtob = dtob; } diff --git a/orika/src/main/java/com/baeldung/orika/PersonContainer.java b/orika/src/main/java/com/baeldung/orika/PersonContainer.java new file mode 100644 index 0000000000..aaec136bb9 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonContainer.java @@ -0,0 +1,18 @@ +package com.baeldung.orika; + +public class PersonContainer { + private Name name; + + public PersonContainer(Name name) { + this.name = name; + } + + public Name getName() { + return name; + } + + public void setName(Name name) { + this.name = name; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonCustomMapper.java b/orika/src/main/java/com/baeldung/orika/PersonCustomMapper.java new file mode 100644 index 0000000000..d839eea30e --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonCustomMapper.java @@ -0,0 +1,36 @@ +package com.baeldung.orika; + +import ma.glasnost.orika.CustomMapper; +import ma.glasnost.orika.MappingContext; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +class PersonCustomMapper extends CustomMapper { + + @Override + public void mapAtoB(Personne3 a, Person3 b, MappingContext context) { + Date date = new Date(a.getDtob()); + DateFormat format = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss'Z'"); + String isoDate = format.format(date); + b.setDtob(isoDate); + } + + @Override + public void mapBtoA(Person3 b, Personne3 a, MappingContext context) { + DateFormat format = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss'Z'"); + Date date = null; + try { + date = format.parse(b.getDtob()); + + } catch (ParseException e) { + e.printStackTrace(); + } + long timestamp = date.getTime(); + a.setDtob(timestamp); + } +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonListContainer.java b/orika/src/main/java/com/baeldung/orika/PersonListContainer.java new file mode 100644 index 0000000000..97ae15eb48 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonListContainer.java @@ -0,0 +1,20 @@ +package com.baeldung.orika; + +import java.util.List; + +public class PersonListContainer { + private List names; + + public PersonListContainer(List names) { + this.names = names; + } + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonNameArray.java b/orika/src/main/java/com/baeldung/orika/PersonNameArray.java new file mode 100644 index 0000000000..f2e98be537 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonNameArray.java @@ -0,0 +1,18 @@ +package com.baeldung.orika; + +public class PersonNameArray { + private String[] nameArray; + + public PersonNameArray(String[] nameArray) { + this.nameArray = nameArray; + } + + public String[] getNameArray() { + return nameArray; + } + + public void setNameArray(String[] nameArray) { + this.nameArray = nameArray; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonNameList.java b/orika/src/main/java/com/baeldung/orika/PersonNameList.java new file mode 100644 index 0000000000..70798ebd35 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonNameList.java @@ -0,0 +1,20 @@ +package com.baeldung.orika; + +import java.util.List; + +public class PersonNameList { + private List nameList; + + public PersonNameList(List nameList) { + this.nameList = nameList; + } + + public List getNameList() { + return nameList; + } + + public void setNameList(List nameList) { + this.nameList = nameList; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonNameMap.java b/orika/src/main/java/com/baeldung/orika/PersonNameMap.java new file mode 100644 index 0000000000..8126cdfc3a --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonNameMap.java @@ -0,0 +1,20 @@ +package com.baeldung.orika; + +import java.util.Map; + +public class PersonNameMap { + private Map nameMap; + + public PersonNameMap(Map nameMap) { + this.nameMap = nameMap; + } + + public Map getNameMap() { + return nameMap; + } + + public void setNameMap(Map nameList) { + this.nameMap = nameList; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/PersonNameParts.java b/orika/src/main/java/com/baeldung/orika/PersonNameParts.java new file mode 100644 index 0000000000..7cfdcdd75b --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/PersonNameParts.java @@ -0,0 +1,28 @@ +package com.baeldung.orika; + +public class PersonNameParts { + private String firstName; + private String lastName; + + public PersonNameParts(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne.java b/orika/src/main/java/com/baeldung/orika/Personne.java similarity index 77% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Personne.java rename to orika/src/main/java/com/baeldung/orika/Personne.java index f6ff22c96b..47789dd323 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne.java +++ b/orika/src/main/java/com/baeldung/orika/Personne.java @@ -1,16 +1,11 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Personne { private String nom; private String surnom; private int age; - public Personne() { - - } - public Personne(String nom, String surnom, int age) { - super(); this.nom = nom; this.surnom = surnom; this.age = age; @@ -40,4 +35,10 @@ public class Personne { this.age = age; } + @Override + public String toString() { + return "Personne [nom=" + nom + ", surnom=" + surnom + ", age=" + age + + "]"; + } + } diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne3.java b/orika/src/main/java/com/baeldung/orika/Personne3.java similarity index 92% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Personne3.java rename to orika/src/main/java/com/baeldung/orika/Personne3.java index 04af1fe2d1..35323c612a 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Personne3.java +++ b/orika/src/main/java/com/baeldung/orika/Personne3.java @@ -1,4 +1,4 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Personne3 { private String name; @@ -9,7 +9,6 @@ public class Personne3 { } public Personne3(String name, long dtob) { - super(); this.name = name; this.dtob = dtob; } diff --git a/dozer-tutorial/src/main/java/com/baeldung/dozer/Source.java b/orika/src/main/java/com/baeldung/orika/Source.java similarity index 74% rename from dozer-tutorial/src/main/java/com/baeldung/dozer/Source.java rename to orika/src/main/java/com/baeldung/orika/Source.java index 88b3c7a349..a973bab388 100644 --- a/dozer-tutorial/src/main/java/com/baeldung/dozer/Source.java +++ b/orika/src/main/java/com/baeldung/orika/Source.java @@ -1,6 +1,11 @@ -package com.baeldung.dozer; +package com.baeldung.orika; public class Source { + @Override + public String toString() { + return "Source [name=" + name + ", age=" + age + "]"; + } + private String name; private int age; @@ -8,7 +13,6 @@ public class Source { } public Source(String name, int age) { - super(); this.name = name; this.age = age; } diff --git a/orika/src/test/java/com/baeldung/orika/OrikaTest.java b/orika/src/test/java/com/baeldung/orika/OrikaTest.java new file mode 100644 index 0000000000..18dfcfa44e --- /dev/null +++ b/orika/src/test/java/com/baeldung/orika/OrikaTest.java @@ -0,0 +1,367 @@ +package com.baeldung.orika; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import ma.glasnost.orika.BoundMapperFacade; +import ma.glasnost.orika.CustomMapper; +import ma.glasnost.orika.MapperFacade; +import ma.glasnost.orika.MapperFactory; +import ma.glasnost.orika.MappingContext; +import ma.glasnost.orika.impl.DefaultMapperFactory; + +import org.junit.Before; +import org.junit.Test; + +public class OrikaTest { + MapperFactory mapperFactory; + CustomMapper customMapper; + // constant to help us cover time zone differences + private final long GMT_DIFFERENCE = 46800000; + + @Before + public void before() { + mapperFactory = new DefaultMapperFactory.Builder().build(); + customMapper = new PersonCustomMapper(); + } + + @Test + public void givenSrcAndDest_whenMaps_thenCorrect() { + mapperFactory.classMap(Source.class, Dest.class); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source("Baeldung", 10); + Dest dest = mapper.map(src, Dest.class); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsReverse_thenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).byDefault(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Dest src = new Dest("Baeldung", 10); + Source dest = mapper.map(src, Source.class); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsByObject_thenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).byDefault(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source("Baeldung", 10); + Dest dest = new Dest(); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsUsingBoundMapper_thenCorrect() { + BoundMapperFacade boundMapper = mapperFactory + .getMapperFacade(Source.class, Dest.class); + Source src = new Source("baeldung", 10); + Dest dest = boundMapper.map(src); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsUsingBoundMapperInReverse_thenCorrect() { + BoundMapperFacade boundMapper = mapperFactory + .getMapperFacade(Source.class, Dest.class); + Dest src = new Dest("baeldung", 10); + Source dest = boundMapper.mapReverse(src); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsUsingBoundMapperByObject_thenCorrect() { + BoundMapperFacade boundMapper = mapperFactory + .getMapperFacade(Source.class, Dest.class); + Source src = new Source("baeldung", 10); + Dest dest = new Dest(); + boundMapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDest_whenMapsUsingBoundMapperByObjectInReverse_thenCorrect() { + BoundMapperFacade boundMapper = mapperFactory + .getMapperFacade(Source.class, Dest.class); + Dest src = new Dest("baeldung", 10); + Source dest = new Source(); + boundMapper.mapReverse(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcAndDestWithDifferentFieldNames_whenMaps_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class) + .field("nom", "name").field("surnom", "nickname") + .field("age", "age").register(); + + MapperFacade mapper = mapperFactory.getMapperFacade(); + + Personne frenchPerson = new Personne("Claire", "cla", 25); + Person englishPerson = mapper.map(frenchPerson, Person.class); + + assertEquals(englishPerson.getName(), frenchPerson.getNom()); + assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom()); + assertEquals(englishPerson.getAge(), frenchPerson.getAge()); + + } + + @Test + public void givenBothDifferentAndSameFieldNames_whenFailsToMapSameNameFieldAutomatically_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class) + .field("nom", "name").field("surnom", "nickname").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Personne frenchPerson = new Personne("Claire", "cla", 25); + + Person englishPerson = mapper.map(frenchPerson, Person.class); + assertFalse(englishPerson.getAge() == frenchPerson.getAge()); + + } + + @Test + public void givenBothDifferentAndSameFieldNames_whenMapsSameNameFieldByDefault_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class) + .field("nom", "name").field("surnom", "nickname").byDefault() + .register(); + + MapperFacade mapper = mapperFactory.getMapperFacade(); + Personne frenchPerson = new Personne("Claire", "cla", 25); + + Person englishPerson = mapper.map(frenchPerson, Person.class); + assertEquals(englishPerson.getName(), frenchPerson.getNom()); + assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom()); + assertEquals(englishPerson.getAge(), frenchPerson.getAge()); + + } + + @Test + public void givenUnidirectionalMappingSetup_whenMapsUnidirectionally_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class) + .fieldAToB("nom", "name").fieldAToB("surnom", "nickname") + .fieldAToB("age", "age").register(); + ; + MapperFacade mapper = mapperFactory.getMapperFacade(); + Personne frenchPerson = new Personne("Claire", "cla", 25); + + Person englishPerson = mapper.map(frenchPerson, Person.class); + assertEquals(englishPerson.getName(), frenchPerson.getNom()); + assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom()); + assertEquals(englishPerson.getAge(), frenchPerson.getAge()); + + } + + + @Test + public void givenSrcAndDest_whenCanExcludeField_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class).exclude("nom") + .field("surnom", "nickname").field("age", "age").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + + Personne frenchPerson = new Personne("Claire", "cla", 25); + Person englishPerson = mapper.map(frenchPerson, Person.class); + + assertEquals(null, englishPerson.getName()); + assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom()); + assertEquals(englishPerson.getAge(), frenchPerson.getAge()); + } + + @Test + public void givenSpecificConstructorToUse_whenMaps_thenCorrect() { + mapperFactory.classMap(Personne.class, Person.class).constructorB() + .field("nom", "name").field("surnom", "nickname") + .field("age", "age").register(); + ; + MapperFacade mapper = mapperFactory.getMapperFacade(); + Personne frenchPerson = new Personne("Claire", "cla", 25); + + Person englishPerson = mapper.map(frenchPerson, Person.class); + assertEquals(englishPerson.getName(), frenchPerson.getNom()); + assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom()); + assertEquals(englishPerson.getAge(), frenchPerson.getAge()); + + } + + @Test + public void givenSrcWithListAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() { + mapperFactory.classMap(PersonNameList.class, PersonNameParts.class) + .field("nameList[0]", "firstName") + .field("nameList[1]", "lastName").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + List nameList = Arrays.asList(new String[]{"Sylvester", + "Stallone"}); + PersonNameList src = new PersonNameList(nameList); + PersonNameParts dest = mapper.map(src, PersonNameParts.class); + assertEquals(dest.getFirstName(), "Sylvester"); + assertEquals(dest.getLastName(), "Stallone"); + } + + @Test + public void givenSrcWithArrayAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() { + mapperFactory.classMap(PersonNameArray.class, PersonNameParts.class) + .field("nameArray[0]", "firstName") + .field("nameArray[1]", "lastName").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + String[] nameArray = new String[]{"Vin", "Diesel"}; + PersonNameArray src = new PersonNameArray(nameArray); + PersonNameParts dest = mapper.map(src, PersonNameParts.class); + assertEquals(dest.getFirstName(), "Vin"); + assertEquals(dest.getLastName(), "Diesel"); + } + + @Test + public void givenSrcWithMapAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() { + mapperFactory.classMap(PersonNameMap.class, PersonNameParts.class) + .field("nameMap['first']", "firstName") + .field("nameMap[\"last\"]", "lastName").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Map nameMap = new HashMap<>(); + nameMap.put("first", "Leornado"); + nameMap.put("last", "DiCaprio"); + PersonNameMap src = new PersonNameMap(nameMap); + PersonNameParts dest = mapper.map(src, PersonNameParts.class); + assertEquals(dest.getFirstName(), "Leornado"); + assertEquals(dest.getLastName(), "DiCaprio"); + } + + @Test + public void givenSrcWithNestedFields_whenMaps_thenCorrect() { + mapperFactory.classMap(PersonContainer.class, PersonNameParts.class) + .field("name.firstName", "firstName") + .field("name.lastName", "lastName").register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + PersonContainer src = new PersonContainer(new Name("Nick", "Canon")); + PersonNameParts dest = mapper.map(src, PersonNameParts.class); + assertEquals(dest.getFirstName(), "Nick"); + assertEquals(dest.getLastName(), "Canon"); + } + + @Test + public void givenSrcWithNullField_whenMapsThenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).byDefault(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source(null, 10); + Dest dest = mapper.map(src, Dest.class); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenSrcWithNullAndGlobalConfigForNoNull_whenFailsToMap_ThenCorrect() { + MapperFactory mapperFactory = new DefaultMapperFactory.Builder() + .mapNulls(false).build(); + mapperFactory.classMap(Source.class, Dest.class); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source(null, 10); + Dest dest = new Dest("Clinton", 55); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), "Clinton"); + } + + @Test + public void givenSrcWithNullAndLocalConfigForNoNull_whenFailsToMap_ThenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).field("age", "age") + .mapNulls(false).field("name", "name").byDefault().register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source(null, 10); + Dest dest = new Dest("Clinton", 55); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), "Clinton"); + } + + @Test + public void givenDestWithNullReverseMappedToSource_whenMapsByDefault_thenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).byDefault(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Dest src = new Dest(null, 10); + Source dest = new Source("Vin", 44); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), src.getName()); + } + + @Test + public void givenDestWithNullReverseMappedToSourceAndLocalConfigForNoNull_whenFailsToMap_thenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).field("age", "age") + .mapNullsInReverse(false).field("name", "name").byDefault() + .register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Dest src = new Dest(null, 10); + Source dest = new Source("Vin", 44); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), "Vin"); + } + + @Test + public void givenSrcWithNullAndFieldLevelConfigForNoNull_whenFailsToMap_ThenCorrect() { + mapperFactory.classMap(Source.class, Dest.class).field("age", "age") + .fieldMap("name", "name").mapNulls(false).add().byDefault() + .register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + Source src = new Source(null, 10); + Dest dest = new Dest("Clinton", 55); + mapper.map(src, dest); + assertEquals(dest.getAge(), src.getAge()); + assertEquals(dest.getName(), "Clinton"); + } + + @Test + public void givenSrcAndDest_whenCustomMapperWorks_thenCorrect() { + mapperFactory.classMap(Personne3.class, Person3.class) + .customize(customMapper).register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + long timestamp = new Long("1182882159000"); + Personne3 personne3 = new Personne3("Leornardo", timestamp); + Person3 person3 = mapper.map(personne3, Person3.class); + + String timestampTest = person3.getDtob(); + // since different timezones will resolve the timestamp to a different + // datetime string, it suffices to check only for format rather than + // specific date + assertTrue(timestampTest.charAt(10) == 'T' + && timestampTest.charAt(19) == 'Z'); + } + + @Test + public void givenSrcAndDest_whenCustomMapperWorksBidirectionally_thenCorrect() { + mapperFactory.classMap(Personne3.class, Person3.class) + .customize(customMapper).register(); + MapperFacade mapper = mapperFactory.getMapperFacade(); + + String dateTime = "2007-06-26T21:22:39Z"; + long timestamp = new Long("1182882159000"); + Person3 person3 = new Person3("Leornardo", dateTime); + Personne3 personne3 = mapper.map(person3, Personne3.class); + long timestampToTest = personne3.getDtob(); + /* + * since different timezones will resolve the datetime to a different + * unix timestamp, we must provide a range of tolerance + */ + assertTrue(timestampToTest == timestamp + || timestampToTest >= timestamp - GMT_DIFFERENCE + || timestampToTest <= timestamp + GMT_DIFFERENCE); + + } + +} diff --git a/pom.xml b/pom.xml index 419916de86..3f4489fc4c 100644 --- a/pom.xml +++ b/pom.xml @@ -16,6 +16,7 @@ assertj apache-cxf apache-fop + autovalue-tutorial core-java core-java-8 couchbase-sdk-intro @@ -52,6 +53,7 @@ log4j spring-all + spring-akka spring-apache-camel spring-autowire spring-batch @@ -80,7 +82,9 @@ spring-quartz spring-spel spring-rest + spring-rest-angular spring-rest-docs + spring-cloud-config spring-security-basic-auth spring-security-custom-permission @@ -95,6 +99,7 @@ spring-security-rest-custom spring-security-rest-digest-auth spring-security-rest-full + spring-security-x509 spring-thymeleaf spring-zuul jsf @@ -106,6 +111,8 @@ mutation-testing spring-mvc-velocity xstream + dozer + orika diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml new file mode 100644 index 0000000000..6299448ec8 --- /dev/null +++ b/spring-akka/pom.xml @@ -0,0 +1,80 @@ + + 4.0.0 + com.baeldung + spring-akka + 0.1-SNAPSHOT + + spring-akka + + + + + org.springframework + spring-context + + + + com.typesafe.akka + akka-actor_2.11 + ${akka.version} + + + + org.springframework + spring-test + test + + + + junit + junit + ${junit.version} + test + + + + + + + + + + org.springframework + spring-framework-bom + ${spring.version} + pom + import + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + + 4.3.2.RELEASE + 2.4.8 + 4.12 + + 3.5.1 + + + \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/akka/AppConfiguration.java b/spring-akka/src/main/java/org/baeldung/akka/AppConfiguration.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/akka/AppConfiguration.java rename to spring-akka/src/main/java/org/baeldung/akka/AppConfiguration.java diff --git a/spring-all/src/main/java/org/baeldung/akka/GreetingActor.java b/spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java similarity index 88% rename from spring-all/src/main/java/org/baeldung/akka/GreetingActor.java rename to spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java index 1a9386c769..6366c277a4 100644 --- a/spring-all/src/main/java/org/baeldung/akka/GreetingActor.java +++ b/spring-akka/src/main/java/org/baeldung/akka/GreetingActor.java @@ -1,13 +1,12 @@ package org.baeldung.akka; import akka.actor.UntypedActor; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; - @Component -@Scope(SCOPE_PROTOTYPE) +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class GreetingActor extends UntypedActor { private GreetingService greetingService; diff --git a/spring-all/src/main/java/org/baeldung/akka/GreetingService.java b/spring-akka/src/main/java/org/baeldung/akka/GreetingService.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/akka/GreetingService.java rename to spring-akka/src/main/java/org/baeldung/akka/GreetingService.java diff --git a/spring-all/src/main/java/org/baeldung/akka/SpringActorProducer.java b/spring-akka/src/main/java/org/baeldung/akka/SpringActorProducer.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/akka/SpringActorProducer.java rename to spring-akka/src/main/java/org/baeldung/akka/SpringActorProducer.java diff --git a/spring-all/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/akka/SpringExtension.java rename to spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java diff --git a/spring-all/src/test/java/org/baeldung/akka/SpringAkkaTest.java b/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java similarity index 100% rename from spring-all/src/test/java/org/baeldung/akka/SpringAkkaTest.java rename to spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index b7a8fcc79e..c70d9d75fc 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -87,14 +87,6 @@ runtime - - - - com.typesafe.akka - akka-actor_2.11 - 2.4.8 - - @@ -138,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/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java new file mode 100644 index 0000000000..443635fb70 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -0,0 +1,31 @@ +package org.baeldung.controller.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class StudentControllerConfig implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.register(WebConfig.class); + + root.setServletContext(sc); + + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); + + DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); + appServlet.setLoadOnStartup(1); + appServlet.addMapping("/test/*"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java new file mode 100644 index 0000000000..f55af69c88 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.controller.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" }) +public class WebConfig extends WebMvcConfigurerAdapter { + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/"); + bean.setSuffix(".jsp"); + return bean; + } +} \ No newline at end of file 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/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java new file mode 100644 index 0000000000..44f1767405 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java @@ -0,0 +1,86 @@ +package org.baeldung.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.baeldung.controller.config.WebConfig; +import org.baeldung.controller.student.Student; +import org.junit.Assert; +import org.junit.Before; +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.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.ModelAndView; + + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class ) +public class ControllerAnnotationTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + private Student selectedStudent; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + + selectedStudent = new Student(); + selectedStudent.setId(1); + selectedStudent.setName("Peter"); + } + + @Test + public void testTestController() throws Exception { + + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")) + .andReturn() + .getModelAndView(); + + // validate modal data + Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); + + // validate view name + Assert.assertSame(mv.getViewName(), "welcome"); + } + + @Test + public void testRestController() throws Exception { + + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)) + .andReturn().getResponse() + .getContentAsString(); + + ObjectMapper reader = new ObjectMapper(); + + Student studentDetails = reader.readValue(responseBody, Student.class); + + Assert.assertEquals(selectedStudent, studentDetails); + + } + + @Test + public void testRestAnnotatedController() throws Exception { + + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)) + .andReturn().getResponse() + .getContentAsString(); + + ObjectMapper reader = new ObjectMapper(); + + Student studentDetails = reader.readValue(responseBody, Student.class); + + Assert.assertEquals(selectedStudent, studentDetails); + } + +} 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 ada02a9965..66197feacd 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,156 +1,173 @@ - 4.0.0 - com.baeldung - spring-boot - 0.0.1-SNAPSHOT - war - Spring Boot Actuator - This is simple boot application for Spring boot actuator test + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-boot + 0.0.1-SNAPSHOT + war + Spring Boot Actuator + This is simple boot application for Spring boot actuator test - - - org.springframework.boot - spring-boot-starter-parent - 1.4.0.RC1 - - + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RC1 + + - - - org.baeldung.boot.DemoApplication - UTF-8 - 1.8 - - + + + org.baeldung.boot.DemoApplication + UTF-8 + 1.8 + 4.3.1.RELEASE + - - - org.springframework.boot - spring-boot-starter-web - + + + org.springframework.boot + spring-boot-starter-web + - - org.springframework.boot - spring-boot-starter-data-jpa - + + org.springframework.boot + spring-boot-starter-data-jpa + - - org.springframework.boot - spring-boot-starter-actuator - + + org.springframework.boot + spring-boot-starter-actuator + - - org.springframework.boot - spring-boot-starter-security - + + org.springframework.boot + spring-boot-starter-security + - - io.dropwizard.metrics - metrics-core - + + io.dropwizard.metrics + metrics-core + - - com.h2database - h2 - + + com.h2database + h2 + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter - - - com.jayway.jsonpath - json-path - test - - - org.springframework.boot - spring-boot-starter-mail - - - org.subethamail - subethasmtp - 3.1.7 - test - - + + org.springframework.boot + spring-boot-starter + + + com.jayway.jsonpath + json-path + test + + + org.springframework.boot + spring-boot-starter-mail + + + org.subethamail + subethasmtp + 3.1.7 + test + + - - spring-boot - - - src/main/resources - true - - + + spring-boot + + + src/main/resources + true + + - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + - org.springframework.boot - spring-boot-maven-plugin - - - - org.apache.maven.plugins - maven-compiler-plugin + pl.project13.maven + git-commit-id-plugin + 2.2.1 + + + get-the-git-infos + + revision + + + - 1.8 - 1.8 + true - - org.apache.maven.plugins - maven-war-plugin - - - + - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + 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/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 59955cc990..582d2d9e9c 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -1,8 +1,5 @@ package org.baeldung.main; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.baeldung.controller.servlet.HelloWorldServlet; @@ -17,6 +14,9 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + @RestController @EnableAutoConfiguration @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) @@ -55,28 +55,6 @@ public class SpringBootApplication { return bean; } - /* @Bean - public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() { - JettyEmbeddedServletContainerFactory jettyContainer = new JettyEmbeddedServletContainerFactory(); - jettyContainer.setPort(9000); - jettyContainer.setContextPath("/springbootapp"); - return jettyContainer; - } - - @Bean - public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() { - UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory(); - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(io.undertow.Undertow.Builde builder) { - builder.addHttpListener(8080, "0.0.0.0"); - } - - }); - return factory; - }*/ - @Bean @Autowired public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java new file mode 100644 index 0000000000..23d741b98c --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -0,0 +1,23 @@ +package org.baeldung.session.exception; + +import org.baeldung.boot.model.Foo; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; + +@EntityScan(basePackageClasses = Foo.class) +@SpringBootApplication +public class Application { + public static void main(String[] args) { + System.setProperty("spring.config.name", "exception"); + System.setProperty("spring.profiles.active", "exception"); + SpringApplication.run(Application.class, args); + } + + @Bean + public HibernateJpaSessionFactoryBean sessionFactory() { + return new HibernateJpaSessionFactoryBean(); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java new file mode 100644 index 0000000000..679d691b26 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.session.exception.repository; + +import org.baeldung.boot.model.Foo; + +public interface FooRepository { + + void save(Foo foo); + + Foo get(Integer id); +} diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java new file mode 100644 index 0000000000..83de888e5e --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -0,0 +1,25 @@ +package org.baeldung.session.exception.repository; + +import org.baeldung.boot.model.Foo; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Repository; + +@Profile("exception") +@Repository +public class FooRepositoryImpl implements FooRepository { + @Autowired + private SessionFactory sessionFactory; + + @Override + public void save(Foo foo) { + sessionFactory.getCurrentSession().saveOrUpdate(foo); + } + + @Override + public Foo get(Integer id) { + return sessionFactory.getCurrentSession().get(Foo.class, id); + } + +} \ No newline at end of file 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-boot/src/test/java/org/baeldung/boot/ApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java new file mode 100644 index 0000000000..7911465048 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java @@ -0,0 +1,17 @@ +package org.baeldung.boot; + +import org.baeldung.session.exception.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@TestPropertySource("classpath:exception.properties") +public class ApplicationTests { + @Test + public void contextLoads() { + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java index 41c5a545cc..7f9b2ba912 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java @@ -2,12 +2,12 @@ package org.baeldung.boot; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = DemoApplication.class) +@SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration public class DemoApplicationTests { diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java new file mode 100644 index 0000000000..4cb1b60cde --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java @@ -0,0 +1,32 @@ +package org.baeldung.boot.repository; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.model.Foo; +import org.baeldung.session.exception.repository.FooRepository; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@TestPropertySource("classpath:exception-hibernate.properties") +public class HibernateSessionTest extends ApplicationTests { + @Autowired + private FooRepository fooRepository; + + @Test + public void whenSavingWithCurrentSession_thenThrowNoException() { + Foo foo = new Foo("Exception Solved"); + fooRepository.save(foo); + foo = null; + foo = fooRepository.get(1); + + assertThat(foo, notNullValue()); + assertThat(foo.getId(), is(1)); + assertThat(foo.getName(), is("Exception Solved")); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java new file mode 100644 index 0000000000..5f5a49841a --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java @@ -0,0 +1,21 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.model.Foo; +import org.baeldung.session.exception.repository.FooRepository; +import org.hibernate.HibernateException; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class NoHibernateSessionTest extends ApplicationTests { + @Autowired + private FooRepository fooRepository; + + @Test(expected = HibernateException.class) + public void whenSavingWithoutCurrentSession_thenThrowException() { + Foo foo = new Foo("Exception Thrown"); + fooRepository.save(foo); + } +} diff --git a/spring-boot/src/test/resources/exception-hibernate.properties b/spring-boot/src/test/resources/exception-hibernate.properties new file mode 100644 index 0000000000..cde746acb9 --- /dev/null +++ b/spring-boot/src/test/resources/exception-hibernate.properties @@ -0,0 +1,2 @@ +spring.profiles.active=exception +spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext diff --git a/spring-boot/src/test/resources/exception.properties b/spring-boot/src/test/resources/exception.properties new file mode 100644 index 0000000000..c55e415a3a --- /dev/null +++ b/spring-boot/src/test/resources/exception.properties @@ -0,0 +1,6 @@ +# Security +security.user.name=admin +security.user.password=password + +spring.dao.exceptiontranslation.enabled=false +spring.profiles.active=exception \ No newline at end of file diff --git a/spring-cloud-config/client-config/config-client-development.properties b/spring-cloud-config/client-config/config-client-development.properties new file mode 100644 index 0000000000..6401d1be7f --- /dev/null +++ b/spring-cloud-config/client-config/config-client-development.properties @@ -0,0 +1,2 @@ +user.role=Developer +user.password=pass diff --git a/spring-cloud-config/client-config/config-client-production.properties b/spring-cloud-config/client-config/config-client-production.properties new file mode 100644 index 0000000000..cd2e14fcc3 --- /dev/null +++ b/spring-cloud-config/client-config/config-client-production.properties @@ -0,0 +1 @@ +user.role=User diff --git a/spring-cloud-config/client/pom.xml b/spring-cloud-config/client/pom.xml new file mode 100644 index 0000000000..0ef4b35581 --- /dev/null +++ b/spring-cloud-config/client/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + + com.baeldung.spring.cloud + spring-cloud-config + 0.0.1-SNAPSHOT + + client + jar + + client + Demo project for Spring Cloud Config Client + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.BUILD-SNAPSHOT + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + diff --git a/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java b/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java new file mode 100644 index 0000000000..1dd3bbdab0 --- /dev/null +++ b/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.config.client; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class ConfigClient { + @Value("${user.role}") + private String role; + + @Value("${user.password}") + private String password; + + public static void main(String[] args) { + SpringApplication.run(ConfigClient.class, args); + } + + @RequestMapping(value = "/whoami/{username}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE) + public String whoami(@PathVariable("username") String username) { + return String.format("Hello %s! You are a(n) %s and your password is '%s'.\n", username, role, password); + } +} diff --git a/spring-cloud-config/client/src/main/resources/bootstrap.properties b/spring-cloud-config/client/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..18982a93b5 --- /dev/null +++ b/spring-cloud-config/client/src/main/resources/bootstrap.properties @@ -0,0 +1,5 @@ +spring.application.name=config-client +spring.profiles.active=development +spring.cloud.config.uri=http://localhost:8888 +spring.cloud.config.username=root +spring.cloud.config.password=s3cr3t diff --git a/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java new file mode 100644 index 0000000000..058fd45f35 --- /dev/null +++ b/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.config.client; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = ConfigClient.class) +@WebAppConfiguration +public class ConfigClientLiveTest { + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud-config/pom.xml b/spring-cloud-config/pom.xml new file mode 100644 index 0000000000..8e0e4b8706 --- /dev/null +++ b/spring-cloud-config/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-config + 0.0.1-SNAPSHOT + pom + + + server + client + + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + + + + 1.3.5.RELEASE + 2.19.1 + + diff --git a/spring-cloud-config/server/pom.xml b/spring-cloud-config/server/pom.xml new file mode 100644 index 0000000000..c3f68854bb --- /dev/null +++ b/spring-cloud-config/server/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + + + com.baeldung.spring.cloud + spring-cloud-config + 0.0.1-SNAPSHOT + + server + + server + Demo project for Spring Cloud Config Server + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-config-server + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.BUILD-SNAPSHOT + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + diff --git a/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java b/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java new file mode 100644 index 0000000000..4dd34ae3ff --- /dev/null +++ b/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.config.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableConfigServer +@EnableWebSecurity +public class ConfigServer { + public static void main(String[] args) { + SpringApplication.run(ConfigServer.class, args); + } +} diff --git a/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud-config/server/src/main/resources/application.properties new file mode 100644 index 0000000000..2131f3b249 --- /dev/null +++ b/spring-cloud-config/server/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8888 +spring.cloud.config.server.git.uri=https://github.com/eugenp/tutorials/tree/master/spring-cloud-config/client-config +spring.cloud.config.server.git.clone-on-start=false +security.user.name=root +security.user.password=s3cr3t +encrypt.key-store.location=classpath:/config-server.jks +encrypt.key-store.password=my-s70r3-s3cr3t +encrypt.key-store.alias=config-server-key +encrypt.key-store.secret=my-k34-s3cr3t diff --git a/spring-cloud-config/server/src/main/resources/config-server.jks b/spring-cloud-config/server/src/main/resources/config-server.jks new file mode 100644 index 0000000000..f3dddb4a8f Binary files /dev/null and b/spring-cloud-config/server/src/main/resources/config-server.jks differ diff --git a/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java b/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java new file mode 100644 index 0000000000..306c120e43 --- /dev/null +++ b/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.config.server; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = ConfigServer.class) +@WebAppConfiguration +@Ignore +public class ConfigServerListTest { + @Test + public void contextLoads() { + } +} diff --git a/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java index 0bb249b814..8e87ed3028 100644 --- a/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java +++ b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java @@ -8,14 +8,14 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class BaeldungController { - - @RequestMapping(method={RequestMethod.GET},value={"/hello"}) - public String sayHello(HttpServletResponse response){ + + @RequestMapping(method = { RequestMethod.GET }, value = { "/hello" }) + public String sayHello(HttpServletResponse response) { return "hello"; } - - @RequestMapping(method={RequestMethod.POST},value={"/baeldung"}) - public String sayHelloPost(HttpServletResponse response){ + + @RequestMapping(method = { RequestMethod.POST }, value = { "/baeldung" }) + public String sayHelloPost(HttpServletResponse response) { return "hello"; } diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index d490b23aa2..60548dd6e3 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -4,16 +4,23 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; @SpringBootApplication -public class SpringDemoApplication extends SpringBootServletInitializer{ +public class SpringDemoApplication extends SpringBootServletInitializer { - public static void main(String[] args) { - SpringApplication.run(SpringDemoApplication.class, args); - } - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application){ + public static void main(String[] args) { + SpringApplication.run(SpringDemoApplication.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringDemoApplication.class); } + + @Bean + public RestTemplate getRestTemplate(){ + return new RestTemplate(); + } } diff --git a/spring-cucumber/src/main/java/com/baeldung/VersionController.java b/spring-cucumber/src/main/java/com/baeldung/VersionController.java index 7c72a78a05..f673f0e31f 100644 --- a/spring-cucumber/src/main/java/com/baeldung/VersionController.java +++ b/spring-cucumber/src/main/java/com/baeldung/VersionController.java @@ -6,9 +6,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class VersionController { - - @RequestMapping(method={RequestMethod.GET},value={"/version"}) - public String getVersion(){ - return "1.0"; - } + + @RequestMapping(method = { RequestMethod.GET }, value = { "/version" }) + public String getVersion() { + return "1.0"; + } } diff --git a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java b/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java index 3e950709b3..c31a35b271 100644 --- a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java @@ -4,8 +4,7 @@ import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; - @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources") -public class CucumberTest{ +public class CucumberTest { } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java b/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java index 1ea72868eb..ab8a9c55b2 100644 --- a/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java +++ b/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java @@ -7,28 +7,27 @@ import org.springframework.web.client.RequestCallback; import java.io.IOException; import java.util.Map; - -public class HeaderSettingRequestCallback implements RequestCallback{ - final Map requestHeaders; +public class HeaderSettingRequestCallback implements RequestCallback { + final Map requestHeaders; private String body; - public HeaderSettingRequestCallback(final Map headers){ + public HeaderSettingRequestCallback(final Map headers) { this.requestHeaders = headers; } - public void setBody(final String postBody ){ + public void setBody(final String postBody) { this.body = postBody; } @Override - public void doWithRequest(ClientHttpRequest request) throws IOException{ + public void doWithRequest(ClientHttpRequest request) throws IOException { final HttpHeaders clientHeaders = request.getHeaders(); - for( final Map.Entry entry : requestHeaders.entrySet() ){ - clientHeaders.add(entry.getKey(),entry.getValue()); + for (final Map.Entry entry : requestHeaders.entrySet()) { + clientHeaders.add(entry.getKey(), entry.getValue()); } - if( null != body ){ - request.getBody().write( body.getBytes() ); + if (null != body) { + request.getBody().write(body.getBytes()); } } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java b/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java index 428343d06a..edbc14f319 100644 --- a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java @@ -3,15 +3,14 @@ package com.baeldung; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; - -public class OtherDefs extends SpringIntegrationTest{ +public class OtherDefs extends SpringIntegrationTest { @When("^the client calls /baeldung$") - public void the_client_issues_POST_hello() throws Throwable{ + public void the_client_issues_POST_hello() throws Throwable { executePost("http://localhost:8080/baeldung"); } - + @Given("^the client calls /hello$") - public void the_client_issues_GET_hello() throws Throwable{ + public void the_client_issues_GET_hello() throws Throwable { executeGet("http://localhost:8080/hello"); } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java index 6890faf8b5..4c0125e9b4 100644 --- a/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java +++ b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java @@ -7,28 +7,27 @@ import java.io.StringWriter; import org.apache.commons.io.IOUtils; import org.springframework.http.client.ClientHttpResponse; - -public class ResponseResults{ +public class ResponseResults { private final ClientHttpResponse theResponse; private final String body; - protected ResponseResults(final ClientHttpResponse response) throws IOException{ + protected ResponseResults(final ClientHttpResponse response) throws IOException { this.theResponse = response; final InputStream bodyInputStream = response.getBody(); - if (null == bodyInputStream){ + if (null == bodyInputStream) { this.body = "{}"; - }else{ + } else { final StringWriter stringWriter = new StringWriter(); IOUtils.copy(bodyInputStream, stringWriter); this.body = stringWriter.toString(); } } - protected ClientHttpResponse getTheResponse(){ + protected ClientHttpResponse getTheResponse() { return theResponse; } - protected String getBody(){ + protected String getBody() { return body; } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index 5c85dc9400..34efff63fb 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -4,99 +4,88 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationContextLoader; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; - //@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class) @WebAppConfiguration @IntegrationTest public class SpringIntegrationTest { - protected static ResponseResults latestResponse = null; + protected static ResponseResults latestResponse = null; - protected RestTemplate restTemplate = null; + @Autowired + protected RestTemplate restTemplate; - protected void executeGet(String url) throws IOException{ - final Map headers = new HashMap<>(); - headers.put("Accept","application/json"); - final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); - final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); + protected void executeGet(String url) throws IOException { + final Map headers = new HashMap<>(); + headers.put("Accept", "application/json"); + final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); + final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); - if (restTemplate == null){ - restTemplate = new RestTemplate(); - } + restTemplate.setErrorHandler(errorHandler); + latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, new ResponseExtractor() { + @Override + public ResponseResults extractData(ClientHttpResponse response) throws IOException { + if (errorHandler.hadError) { + return (errorHandler.getResults()); + } else { + return (new ResponseResults(response)); + } + } + }); - restTemplate.setErrorHandler(errorHandler); - latestResponse = restTemplate.execute(url, - HttpMethod.GET, - requestCallback, - new ResponseExtractor(){ - @Override - public ResponseResults extractData(ClientHttpResponse response) throws IOException { - if (errorHandler.hadError){ - return (errorHandler.getResults()); - } else{ - return (new ResponseResults(response)); - } - } - }); + } - } - - protected void executePost(String url) throws IOException{ - final Map headers = new HashMap<>(); - headers.put("Accept","application/json"); - final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); - final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); + protected void executePost(String url) throws IOException { + final Map headers = new HashMap<>(); + headers.put("Accept", "application/json"); + final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); + final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); - if (restTemplate == null){ - restTemplate = new RestTemplate(); - } + if (restTemplate == null) { + restTemplate = new RestTemplate(); + } - restTemplate.setErrorHandler(errorHandler); - latestResponse = restTemplate.execute(url, - HttpMethod.POST, - requestCallback, - new ResponseExtractor(){ - @Override - public ResponseResults extractData(ClientHttpResponse response) throws IOException { - if (errorHandler.hadError){ - return (errorHandler.getResults()); - } else{ - return (new ResponseResults(response)); - } - } - }); + restTemplate.setErrorHandler(errorHandler); + latestResponse = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor() { + @Override + public ResponseResults extractData(ClientHttpResponse response) throws IOException { + if (errorHandler.hadError) { + return (errorHandler.getResults()); + } else { + return (new ResponseResults(response)); + } + } + }); - } + } - private class ResponseResultErrorHandler implements ResponseErrorHandler{ - private ResponseResults results = null; - private Boolean hadError = false; + private class ResponseResultErrorHandler implements ResponseErrorHandler { + private ResponseResults results = null; + private Boolean hadError = false; - private ResponseResults getResults(){ - return results; - } + private ResponseResults getResults() { + return results; + } - @Override - public boolean hasError(ClientHttpResponse response) throws IOException{ - hadError = response.getRawStatusCode() >= 400; - return hadError; - } + @Override + public boolean hasError(ClientHttpResponse response) throws IOException { + hadError = response.getRawStatusCode() >= 400; + return hadError; + } - @Override - public void handleError(ClientHttpResponse response) throws IOException { - results = new ResponseResults(response); - } - } + @Override + public void handleError(ClientHttpResponse response) throws IOException { + results = new ResponseResults(response); + } + } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java b/spring-cucumber/src/test/java/com/baeldung/StepDefs.java index 3ed25bb09b..865a1e13fa 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefs.java @@ -1,28 +1,29 @@ package com.baeldung; -import cucumber.api.java.en.And; -import cucumber.api.java.en.Then; -import cucumber.api.java.en.When; -import org.springframework.http.HttpStatus; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class StepDefs extends SpringIntegrationTest{ - - @When("^the client calls /version$") - public void the_client_issues_GET_version() throws Throwable{ +import org.springframework.http.HttpStatus; + +import cucumber.api.java.en.And; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; + +public class StepDefs extends SpringIntegrationTest { + + @When("^the client calls /version$") + public void the_client_issues_GET_version() throws Throwable { executeGet("http://localhost:8080/version"); } @Then("^the client receives status code of (\\d+)$") - public void the_client_receives_status_code_of(int statusCode) throws Throwable{ + public void the_client_receives_status_code_of(int statusCode) throws Throwable { final HttpStatus currentStatusCode = latestResponse.getTheResponse().getStatusCode(); - assertThat("status code is incorrect : "+ latestResponse.getBody(), currentStatusCode.value(), is(statusCode) ); + assertThat("status code is incorrect : " + latestResponse.getBody(), currentStatusCode.value(), is(statusCode)); } @And("^the client receives server version (.+)$") - public void the_client_receives_server_version_body(String version) throws Throwable{ - assertThat(latestResponse.getBody(), is(version)) ; + public void the_client_receives_server_version_body(String version) throws Throwable { + assertThat(latestResponse.getBody(), is(version)); } } \ No newline at end of file diff --git a/spring-exceptions/.gitignore b/spring-exceptions/.gitignore index 83c05e60c8..2d669fa30b 100644 --- a/spring-exceptions/.gitignore +++ b/spring-exceptions/.gitignore @@ -1,5 +1,7 @@ *.class +derby.log + #folders# /target /neoDb* diff --git a/spring-exceptions/.settings/.jsdtscope b/spring-exceptions/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-exceptions/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-exceptions/.settings/org.eclipse.jdt.core.prefs b/spring-exceptions/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-exceptions/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-exceptions/.settings/org.eclipse.jdt.ui.prefs b/spring-exceptions/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-exceptions/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-exceptions/.settings/org.eclipse.m2e.core.prefs b/spring-exceptions/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-exceptions/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-exceptions/.settings/org.eclipse.m2e.wtp.prefs b/spring-exceptions/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-exceptions/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-exceptions/.settings/org.eclipse.wst.common.component b/spring-exceptions/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 7785d041ba..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-exceptions/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-exceptions/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-exceptions/.settings/org.eclipse.wst.validation.prefs b/spring-exceptions/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-exceptions/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-exceptions/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-exceptions/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 9e3cb81ef2..733a721c58 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -135,6 +135,27 @@ el-api 2.2 + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + @@ -208,8 +229,8 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE + 4.3.2.RELEASE + 4.1.1.RELEASE 3.20.0-GA 1.2 diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java index 266a04b679..3337e4796d 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java +++ b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java @@ -20,7 +20,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-derby.properties" }) @ComponentScan({ "org.baeldung.persistence" }) public class Cause1NonTransientConfig { diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java index 19e2ceebca..3543526f37 100644 --- a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java +++ b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java @@ -20,7 +20,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-derby.properties" }) @ComponentScan({ "org.baeldung.persistence" }) public class Cause4NonTransientConfig { @@ -72,5 +72,4 @@ public class Cause4NonTransientConfig { // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } - } diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java new file mode 100644 index 0000000000..6d5d998c5b --- /dev/null +++ b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.ex.nontransientexception.cause; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql-incorrect.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +public class Cause5NonTransientConfig { + + @Autowired + private Environment env; + + public Cause5NonTransientConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public HibernateTransactionManager transactionManager() { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory().getObject()); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } +} diff --git a/spring-exceptions/src/main/resources/persistence-derby.properties b/spring-exceptions/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..49fac9877e --- /dev/null +++ b/spring-exceptions/src/main/resources/persistence-derby.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_exceptions;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create diff --git a/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties b/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties new file mode 100644 index 0000000000..b5b8095104 --- /dev/null +++ b/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=com.mysql.jdbc.Driver +jdbc.url=jdbc:mysql:3306://localhost/spring_hibernate4_exceptions?createDatabaseIfNotExist=true +jdbc.user=tutorialuser +jdbc.pass=tutorialmy5ql + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java new file mode 100644 index 0000000000..7a1804ec49 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java @@ -0,0 +1,31 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import javax.sql.DataSource; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.ex.nontransientexception.cause.Cause5NonTransientConfig; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.CannotGetJdbcConnectionException; +import org.springframework.jdbc.core.JdbcTemplate; +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 = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class CannotGetJdbcConnectionExceptionTest { + + @Autowired + private DataSource restDataSource; + + @Test(expected = CannotGetJdbcConnectionException.class) + public void whenJdbcUrlIncorrect_thenCannotGetJdbcConnectionException() { + JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("select * from foo"); + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java deleted file mode 100644 index 2f0a8fe09d..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.ex.nontransientdataaccessexception; - -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.hibernate.SessionFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.CleanupFailureDataAccessException; -import org.springframework.dao.NonTransientDataAccessException; -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 = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CleanupFailureExceptionTest { - - @Autowired - private SessionFactory sessionFactory; - - @Autowired - private IFooService fooService; - - @Test - public void whenCleanupAfterSaving_thenCleanupException() { - try { - final Foo fooEntity = new Foo("foo"); - fooService.create(fooEntity); - } finally { - try { - sessionFactory.close(); - } catch (final NonTransientDataAccessException exc) { - throw new CleanupFailureDataAccessException("Closing connection failed", exc.getCause()); - } - } - } -} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java index aa504223f3..357eb168cd 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java @@ -1,5 +1,7 @@ package org.baeldung.ex.nontransientdataaccessexception; +import javax.sql.DataSource; + import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; @@ -7,6 +9,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -18,9 +22,25 @@ public class DataIntegrityExceptionTest { @Autowired private IFooService fooService; + @Autowired + private DataSource restDataSource; + @Test(expected = DataIntegrityViolationException.class) public void whenSavingNullValue_thenDataIntegrityException() { final Foo fooEntity = new Foo(); fooService.create(fooEntity); } + + @Test(expected = DuplicateKeyException.class) + public void whenSavingDuplicateKeyValues_thenDuplicateKeyException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + + try { + jdbcTemplate.execute("insert into foo(id,name) values (1,'a')"); + jdbcTemplate.execute("insert into foo(id,name) values (1,'b')"); + } finally { + jdbcTemplate.execute("delete from foo where id=1"); + } + } + } diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java index f5e24e3546..69b98b0539 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java @@ -3,10 +3,13 @@ package org.baeldung.ex.nontransientdataaccessexception; import javax.sql.DataSource; import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.IncorrectResultSetColumnCountException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -25,4 +28,26 @@ public class DataRetrievalExceptionTest { jdbcTemplate.queryForObject("select * from foo where id=3", Integer.class); } + + @Test(expected = IncorrectResultSetColumnCountException.class) + public void whenRetrievingMultipleColumns_thenIncorrectResultSetColumnCountException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + try { + jdbcTemplate.execute("insert into foo(id,name) values (1,'a')"); + jdbcTemplate.queryForList("select id,name from foo where id=1", Foo.class); + } finally { + jdbcTemplate.execute("delete from foo where id=1"); + } + } + + @Test(expected = IncorrectResultSizeDataAccessException.class) + public void whenRetrievingMultipleValues_thenIncorrectResultSizeException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + + jdbcTemplate.execute("insert into foo(name) values ('a')"); + jdbcTemplate.execute("insert into foo(name) values ('a')"); + + jdbcTemplate.queryForObject("select id from foo where name='a'", Integer.class); + } + } diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java index 9afe2533de..9c4fd55fa4 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java @@ -1,7 +1,5 @@ package org.baeldung.ex.nontransientdataaccessexception; -import javax.sql.DataSource; - import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; import org.baeldung.persistence.service.IFooService; import org.junit.Test; @@ -14,25 +12,35 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import javax.sql.DataSource; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) public class InvalidResourceUsageExceptionTest { - @Autowired - private IFooService fooService; - @Autowired - private DataSource restDataSource; + @Autowired + private IFooService fooService; - @Test(expected = InvalidDataAccessResourceUsageException.class) - public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { - fooService.findAll(); + @Autowired + private DataSource restDataSource; + + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("revoke select from tutorialuser"); + + try { + fooService.findAll(); + } finally { + jdbcTemplate.execute("grant select to tutorialuser"); + } } - @Test(expected = BadSqlGrammarException.class) - public void whenIncorrectSql_thenBadSqlGrammarException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); - } + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } } diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java deleted file mode 100644 index 7f91b52e00..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.ex.nontransientdataaccessexception; - -import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.PermissionDeniedDataAccessException; -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 = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class PermissionDeniedException { - - @Autowired - private IFooService fooService; - - @Test(expected = PermissionDeniedDataAccessException.class) - public void whenRetrievingDataUserNoSelectRights_thenPermissionDeniedException() { - final Foo foo = new Foo("foo"); - fooService.create(foo); - } - -} diff --git a/spring-hibernate3/.settings/.jsdtscope b/spring-hibernate3/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-hibernate3/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-hibernate3/.settings/org.eclipse.jdt.core.prefs b/spring-hibernate3/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 13146d5df6..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-hibernate3/.settings/org.eclipse.jdt.ui.prefs b/spring-hibernate3/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-hibernate3/.settings/org.eclipse.m2e.core.prefs b/spring-hibernate3/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-hibernate3/.settings/org.eclipse.m2e.wtp.prefs b/spring-hibernate3/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-hibernate3/.settings/org.eclipse.wst.common.component b/spring-hibernate3/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 14b1679703..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-hibernate3/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-hibernate3/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-hibernate3/.settings/org.eclipse.wst.validation.prefs b/spring-hibernate3/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-hibernate3/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-hibernate3/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-hibernate3/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-hibernate4/.settings/.jsdtscope b/spring-hibernate4/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-hibernate4/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-hibernate4/.settings/org.eclipse.jdt.core.prefs b/spring-hibernate4/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 4561074422..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-hibernate4/.settings/org.eclipse.jdt.ui.prefs b/spring-hibernate4/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-hibernate4/.settings/org.eclipse.m2e.core.prefs b/spring-hibernate4/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-hibernate4/.settings/org.eclipse.m2e.wtp.prefs b/spring-hibernate4/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-hibernate4/.settings/org.eclipse.wst.common.component b/spring-hibernate4/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 6192602079..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-hibernate4/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-hibernate4/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-hibernate4/.settings/org.eclipse.wst.validation.prefs b/spring-hibernate4/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-hibernate4/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-hibernate4/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-hibernate4/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-hibernate4/.settings/org.hibernate.eclipse.console.prefs b/spring-hibernate4/.settings/org.hibernate.eclipse.console.prefs deleted file mode 100644 index 7505c63770..0000000000 --- a/spring-hibernate4/.settings/org.hibernate.eclipse.console.prefs +++ /dev/null @@ -1,3 +0,0 @@ -default.configuration= -eclipse.preferences.version=1 -hibernate3.enabled=true diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java new file mode 100644 index 0000000000..b8b012c061 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.hibernate.criteria.model; + +import java.io.Serializable; + +public class Item implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; + + // constructors + public Item() { + + } + + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } + + public Integer getItemId() { + return itemId; + } + + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(final String itemName) { + this.itemName = itemName; + } + + public String getItemDescription() { + return itemDescription; + } + + public Integer getItemPrice() { + return itemPrice; + } + + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } + + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java new file mode 100644 index 0000000000..57f32cfe50 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -0,0 +1,20 @@ +package com.baeldung.hibernate.criteria.util; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateUtil { + + @SuppressWarnings("deprecation") + public static Session getHibernateSession() { + + final SessionFactory sf = new Configuration() + .configure("criteria.cfg.xml").buildSessionFactory(); + + // factory = new Configuration().configure().buildSessionFactory(); + final Session session = sf.openSession(); + return session; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java new file mode 100644 index 0000000000..4db94f2ad7 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -0,0 +1,253 @@ +/** + * ApplicationViewer is the class that starts the application + * First it creates the session object and then creates the + * criteria query. + * + * @author Pritam Banerjee + * @version 1.0 + * @since 07/20/2016 + */ + +package com.baeldung.hibernate.criteria.view; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.LogicalExpression; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; + +public class ApplicationView { + + // default Constructor + public ApplicationView() { + + } + + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + Transaction tx = null; + + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.add(Restrictions.like("itemName", "%item One%")); + final List results = cr.list(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + tx = session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } + + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.gt("itemPrice", 1000)); + final List greaterThanItemsList = cr.list(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); + } + session.close(); + return greaterThanItems; + } + + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.lt("itemPrice", 1000)); + final List lessThanItemsList = cr.list(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i).getItemName(); + } + session.close(); + return lessThanItems; + } + + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.like("itemName", "%chair%")); + final List likeItemsList = cr.list(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i).getItemName(); + } + session.close(); + return likeItems; + } + + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.ilike("itemName", "%Chair%")); + final List ilikeItemsList = cr.list(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i).getItemName(); + } + session.close(); + return ilikeItems; + } + + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + // To get items having price more than 1000 + cr.add(Restrictions.between("itemPrice", 100, 200)); + final List betweenItemsList = cr.list(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i).getItemName(); + } + session.close(); + return betweenItems; + } + + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + final List nullItemsList = cr.list(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i).getItemName(); + } + session.close(); + return nullDescItems; + } + + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNotNull("itemDescription")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } + + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + cr.add(Restrictions.like("itemName", "chair%")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } + + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + cr.add(andExample); + final List andItemsList = cr.list(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i).getItemName(); + } + session.close(); + return andItems; + } + + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); + cr.add(orExample); + final List orItemsList = cr.list(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i).getItemName(); + } + session.close(); + return orItems; + } + + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.addOrder(Order.asc("itemName")); + cr.addOrder(Order.desc("itemPrice")).list(); + final List sortedItemsList = cr.list(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i).getItemName(); + } + session.close(); + return sortedItems; + } + + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()) + .list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } + + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final List avgItemPriceList = session.createCriteria(Item.class) + .setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java new file mode 100644 index 0000000000..91388b107b --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -0,0 +1,82 @@ +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; + } + +} 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 new file mode 100644 index 0000000000..158855f93e --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/User.java @@ -0,0 +1,94 @@ +package com.baeldung.hibernate.fetching.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +public class User implements Serializable { + + private static final long serialVersionUID = 1L; + private Long userId; + private String userName; + private String firstName; + private String lastName; + private Set orderDetail = new HashSet(); + + public User() { + } + + 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; + + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final User other = (User) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(final String userName) { + this.userName = userName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java new file mode 100644 index 0000000000..65ecea2fa4 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -0,0 +1,30 @@ +package com.baeldung.hibernate.fetching.util; + +import org.hibernate.Session; +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(); + } + + public static Session getHibernateSession() { + return new Configuration() + .configure("fetching.cfg.xml") + .buildSessionFactory() + .openSession(); + } + +} 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 new file mode 100644 index 0000000000..90fd302968 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -0,0 +1,110 @@ +package com.baeldung.hibernate.fetching.view; + +import java.sql.Date; +import java.util.List; +import java.util.Set; + +import org.hibernate.Hibernate; +import org.hibernate.Session; +import org.hibernate.Transaction; + + +import com.baeldung.hibernate.fetching.util.HibernateUtil; + +import com.baeldung.hibernate.fetching.model.OrderDetail; + +import com.baeldung.hibernate.fetching.model.User; + + +public class FetchingAppView { + + public FetchingAppView() { + + } + + 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(); + + return (Hibernate.isInitialized(orderDetailSet)); + } + + 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(); + + 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/main/resources/criteria.cfg.xml b/spring-hibernate4/src/main/resources/criteria.cfg.xml new file mode 100644 index 0000000000..a39a32e151 --- /dev/null +++ b/spring-hibernate4/src/main/resources/criteria.cfg.xml @@ -0,0 +1,17 @@ + + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/criteria_create_queries.sql b/spring-hibernate4/src/main/resources/criteria_create_queries.sql new file mode 100644 index 0000000000..3a627dd38c --- /dev/null +++ b/spring-hibernate4/src/main/resources/criteria_create_queries.sql @@ -0,0 +1,7 @@ +CREATE TABLE `item` ( + `ITEM_ID` int(11) NOT NULL AUTO_INCREMENT, + `ITEM_DESC` varchar(100) DEFAULT NULL, + `ITEM_PRICE` int(11) NOT NULL, + `ITEM_NAME` varchar(255) NOT NULL, + PRIMARY KEY (`ITEM_ID`) +) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; diff --git a/spring-hibernate4/src/main/resources/fetching.cfg.xml b/spring-hibernate4/src/main/resources/fetching.cfg.xml new file mode 100644 index 0000000000..4a7e574dda --- /dev/null +++ b/spring-hibernate4/src/main/resources/fetching.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml new file mode 100644 index 0000000000..1f9a7df94e --- /dev/null +++ b/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/fetching_create_queries.sql b/spring-hibernate4/src/main/resources/fetching_create_queries.sql new file mode 100644 index 0000000000..11a4239e0d --- /dev/null +++ b/spring-hibernate4/src/main/resources/fetching_create_queries.sql @@ -0,0 +1,19 @@ +CREATE TABLE `user` ( + `user_id` int(10) NOT NULL AUTO_INCREMENT, + `USERNAME` varchar(100) DEFAULT NULL, + `FIRST_NAME` varchar(255) NOT NULL, + `LAST_NAME` varchar(255) NOT NULL, + PRIMARY KEY (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; + + +CREATE TABLE `user_order` ( + `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, + `ORDER_DATE` date DEFAULT NULL, + `USER_ID` int(10) NOT NULL DEFAULT '0', + `ORDER_DESC` varchar(1024) DEFAULT NULL, + PRIMARY KEY (`ORDER_ID`,`USER_ID`), + KEY `USER_ID` (`USER_ID`), + CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; + diff --git a/spring-hibernate4/src/main/resources/insert_statements.sql b/spring-hibernate4/src/main/resources/insert_statements.sql new file mode 100644 index 0000000000..ae008f29bc --- /dev/null +++ b/spring-hibernate4/src/main/resources/insert_statements.sql @@ -0,0 +1,31 @@ +insert into item (item_id, item_name, item_desc, item_price) +values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(2,'Pogo stick', 'Pogo stick', 466.12); +insert into item (item_id, item_name, item_desc, item_price) +values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) +values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) +values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) +values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) +values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java new file mode 100644 index 0000000000..3bd8c5ee00 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java @@ -0,0 +1,191 @@ +package com.baeldung.hibernate.criteria; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.hibernate.Session; +import org.junit.Test; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import com.baeldung.hibernate.criteria.view.ApplicationView; + +public class HibernateCriteriaTest { + + final private ApplicationView av = new ApplicationView(); + + @Test + public void testPerformanceOfCriteria() { + assertTrue(av.checkIfCriteriaTimeLower()); + } + + @Test + public void testLikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, av.likeCriteria()); + } + + @Test + public void testILikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); + + } + + @Test + public void testNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null") + .list(); + final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { + expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); + } + + @Test + public void testIsNotNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNotNullDescItemsList = session + .createQuery("From Item where itemDescription is not null").list(); + final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { + expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); + + } + + @Test + public void testAverageProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item") + .list(); + + final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; + for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { + expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); + + } + + @Test + public void testRowCountProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); + final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; + for (int i = 0; i < expectedCountProjItemsList.size(); i++) { + expectedCountProjItems[i] = expectedCountProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); + } + + @Test + public void testOrCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedOrCritItemsList = session + .createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); + final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; + for (int i = 0; i < expectedOrCritItemsList.size(); i++) { + expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); + } + + @Test + public void testAndCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAndCritItemsList = session + .createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); + final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; + for (int i = 0; i < expectedAndCritItemsList.size(); i++) { + expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); + } + + @Test + public void testMultiCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedMultiCritItemsList = session + .createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); + final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; + for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { + expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); + } + + @Test + public void testSortCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritItemsList = session + .createQuery("From Item order by itemName asc, itemPrice desc").list(); + final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; + for (int i = 0; i < expectedSortCritItemsList.size(); i++) { + expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); + } + + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); + } + + @Test + public void testLessThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); + } + + @Test + public void betweenCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200") + .list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java new file mode 100644 index 0000000000..8341df9fcb --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -0,0 +1,15 @@ +package com.baeldung.hibernate.criteria; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class HibernateCriteriaTestRunner { + + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java new file mode 100644 index 0000000000..ab27a6ba82 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -0,0 +1,11 @@ +package com.baeldung.hibernate.criteria; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ HibernateCriteriaTest.class }) + +public class HibernateCriteriaTestSuite { + +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java new file mode 100644 index 0000000000..94ee8a3c79 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.fetching; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.hibernate.fetching.view.FetchingAppView; + +public class HibernateFetchingTest { + + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + assertFalse(fav.lazyLoaded()); + } + + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + assertTrue(fav.eagerLoaded()); + } + +} diff --git a/spring-hibernate4/src/test/java/hibernate.cfg.xml b/spring-hibernate4/src/test/java/hibernate.cfg.xml deleted file mode 100644 index 2167eada16..0000000000 --- a/spring-hibernate4/src/test/java/hibernate.cfg.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - -com.mysql.jdbc.Driver -jdbc:mysql://localhost:3306/HIBERTEST2_TEST -root - - - -1 - - -org.hibernate.dialect.MySQLDialect - - -thread - - -org.hibernate.cache.internal.NoCacheProvider - - -true - - - - - - - diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml new file mode 100644 index 0000000000..9e0109aae2 --- /dev/null +++ b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml new file mode 100644 index 0000000000..e0b6516b47 --- /dev/null +++ b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml new file mode 100644 index 0000000000..88882b973e --- /dev/null +++ b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/User.hbm.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml new file mode 100644 index 0000000000..2f941fe8b0 --- /dev/null +++ b/spring-hibernate4/src/test/resources/com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/criteria.cfg.xml b/spring-hibernate4/src/test/resources/criteria.cfg.xml new file mode 100644 index 0000000000..653b5a188a --- /dev/null +++ b/spring-hibernate4/src/test/resources/criteria.cfg.xml @@ -0,0 +1,16 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml new file mode 100644 index 0000000000..4a7e574dda --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml new file mode 100644 index 0000000000..1f9a7df94e --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/spring-jpa/.settings/.jsdtscope b/spring-jpa/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-jpa/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-jpa/.settings/org.eclipse.jdt.core.prefs b/spring-jpa/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 4561074422..0000000000 --- a/spring-jpa/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,95 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-jpa/.settings/org.eclipse.jdt.ui.prefs b/spring-jpa/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-jpa/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-jpa/.settings/org.eclipse.m2e.core.prefs b/spring-jpa/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-jpa/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-jpa/.settings/org.eclipse.m2e.wtp.prefs b/spring-jpa/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-jpa/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-jpa/.settings/org.eclipse.wst.common.component b/spring-jpa/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 0327e45de6..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index b1c99d7726..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-jpa/.settings/org.eclipse.wst.validation.prefs b/spring-jpa/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-jpa/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-jpa/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-jpa/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-jpa/.settings/org.hibernate.eclipse.console.prefs b/spring-jpa/.settings/org.hibernate.eclipse.console.prefs deleted file mode 100644 index 7505c63770..0000000000 --- a/spring-jpa/.settings/org.hibernate.eclipse.console.prefs +++ /dev/null @@ -1,3 +0,0 @@ -default.configuration= -eclipse.preferences.version=1 -hibernate3.enabled=true diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 25dd960435..5acdae7765 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -29,6 +29,11 @@ hibernate-entitymanager ${hibernate.version} + + org.hibernate + hibernate-ehcache + ${hibernate.version} + xml-apis xml-apis @@ -50,6 +55,11 @@ spring-data-jpa ${spring-data-jpa.version} + + com.h2database + h2 + ${h2.version} + @@ -179,13 +189,14 @@ - 4.2.5.RELEASE + 4.3.2.RELEASE 3.20.0-GA - 4.3.11.Final + 5.2.2.Final 5.1.38 - 1.8.2.RELEASE + 1.10.2.RELEASE + 1.4.192 1.7.13 diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java index c9358190e7..010eb5b8a1 100644 --- a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java +++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java @@ -78,6 +78,8 @@ public class PersistenceJPAConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java new file mode 100644 index 0000000000..3ca0dbf5e4 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java @@ -0,0 +1,84 @@ +package org.baeldung.config; + +import com.google.common.base.Preconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +public class PersistenceJPAConfigL2Cache { + + @Autowired + private Environment env; + + public PersistenceJPAConfigL2Cache() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class")); + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java index 585cefb159..209ab081de 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java @@ -1,17 +1,13 @@ package org.baeldung.persistence.model; +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - @Entity +@Cacheable +@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Foo implements Serializable { private static final long serialVersionUID = 1L; diff --git a/spring-jpa/src/main/resources/jpaConfig.xml b/spring-jpa/src/main/resources/jpaConfig.xml index 1f0b8d899f..5afc0af94d 100644 --- a/spring-jpa/src/main/resources/jpaConfig.xml +++ b/spring-jpa/src/main/resources/jpaConfig.xml @@ -21,6 +21,8 @@ ${hibernate.hbm2ddl.auto} ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} diff --git a/spring-jpa/src/main/resources/persistence-h2.properties b/spring-jpa/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..d195af5ec9 --- /dev/null +++ b/spring-jpa/src/main/resources/persistence-h2.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +# jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory \ No newline at end of file diff --git a/spring-jpa/src/main/resources/persistence-multiple-db.properties b/spring-jpa/src/main/resources/persistence-multiple-db.properties index d59956ba03..1a0d99c704 100644 --- a/spring-jpa/src/main/resources/persistence-multiple-db.properties +++ b/spring-jpa/src/main/resources/persistence-multiple-db.properties @@ -9,3 +9,5 @@ jdbc.pass=tutorialmy5ql hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-jpa/src/main/resources/persistence-mysql.properties b/spring-jpa/src/main/resources/persistence-mysql.properties index c4de4ceb80..12b4c93d80 100644 --- a/spring-jpa/src/main/resources/persistence-mysql.properties +++ b/spring-jpa/src/main/resources/persistence-mysql.properties @@ -8,3 +8,5 @@ jdbc.pass=tutorialmy5ql hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-jpa/src/test/java/META-INF/persistence.xml b/spring-jpa/src/test/java/META-INF/persistence.xml index e528491795..922aedbc39 100644 --- a/spring-jpa/src/test/java/META-INF/persistence.xml +++ b/spring-jpa/src/test/java/META-INF/persistence.xml @@ -1,16 +1,20 @@ - - - org.baeldung.persistence.model.Foo - org.baeldung.persistence.model.Bar - - - - - - - - - - + + + org.baeldung.persistence.model.Foo + org.baeldung.persistence.model.Bar + + + + + + + + + + + + diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java index e036a4f3c1..7e6b2722fa 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java @@ -2,6 +2,7 @@ package org.baeldung.persistence.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import org.baeldung.config.ProductConfig; import org.baeldung.config.UserConfig; @@ -57,10 +58,13 @@ public class JpaMultipleDBIntegrationTest { user2.setAge(10); try { user2 = userRepository.save(user2); + userRepository.flush(); + fail("DataIntegrityViolationException should be thrown!"); } catch (final DataIntegrityViolationException e) { + // Expected + } catch (final Exception e) { + fail("DataIntegrityViolationException should be thrown, instead got: " + e); } - - assertNull(userRepository.findOne(user2.getId())); } @Test diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java new file mode 100644 index 0000000000..f97f53b82c --- /dev/null +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -0,0 +1,84 @@ +package org.baeldung.persistence.service; + +import net.sf.ehcache.CacheManager; +import org.baeldung.config.PersistenceJPAConfigL2Cache; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.model.Foo; +import org.junit.Before; +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.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +public class SecondLevelCacheIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + @Autowired + private FooService fooService; + @Autowired + private PlatformTransactionManager platformTransactionManager; + + @Before + public final void before() { + entityManager.getEntityManagerFactory().getCache().evictAll(); + } + + @Test + public final void givenEntityIsLoaded_thenItIsCached() { + final Foo foo = new Foo(randomAlphabetic(6)); + fooService.create(foo); + fooService.findOne(foo.getId()); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) + .getCache("org.baeldung.persistence.model.Foo").getSize(); + assertThat(size, greaterThan(0)); + } + + @Test + public final void givenBarIsUpdatedInNativeQuery_thenFoosAreNotEvicted() { + final Foo foo = new Foo(randomAlphabetic(6)); + fooService.create(foo); + fooService.findOne(foo.getId()); + + new TransactionTemplate(platformTransactionManager).execute(status -> { + final Bar bar = new Bar(randomAlphabetic(6)); + entityManager.persist(bar); + final Query nativeQuery = entityManager.createNativeQuery("update BAR set NAME = :updatedName where ID = :id"); + nativeQuery.setParameter("updatedName", "newName"); + nativeQuery.setParameter("id", bar.getId()); + nativeQuery.unwrap(org.hibernate.SQLQuery.class).addSynchronizedEntityClass(Bar.class); + return nativeQuery.executeUpdate(); + }); + + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) + .getCache("org.baeldung.persistence.model.Foo").getSize(); + assertThat(size, greaterThan(0)); + } + + @Test + public final void givenCacheableQueryIsExecuted_thenItIsCached() { + new TransactionTemplate(platformTransactionManager).execute(status -> { + return entityManager.createQuery("select f from Foo f") + .setHint("org.hibernate.cacheable", true) + .getResultList(); + }); + + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) + .getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); + assertThat(size, greaterThan(0)); + } +} diff --git a/spring-mvc-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-mvc-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-mvc-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-mvc-java/.settings/.jsdtscope b/spring-mvc-java/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-mvc-java/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-mvc-java/.settings/org.eclipse.jdt.core.prefs b/spring-mvc-java/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 5ff04b9f96..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,91 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-mvc-java/.settings/org.eclipse.jdt.ui.prefs b/spring-mvc-java/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-mvc-java/.settings/org.eclipse.m2e.core.prefs b/spring-mvc-java/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-mvc-java/.settings/org.eclipse.m2e.wtp.prefs b/spring-mvc-java/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-mvc-java/.settings/org.eclipse.wst.common.component b/spring-mvc-java/.settings/org.eclipse.wst.common.component deleted file mode 100644 index b23283ab37..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-mvc-java/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-mvc-java/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-mvc-java/.settings/org.eclipse.wst.validation.prefs b/spring-mvc-java/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-mvc-java/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-mvc-java/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-mvc-java/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 33d6306c5a..4d3432d47b 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -111,6 +111,11 @@ ${mockito.version} test + + com.jayway.jsonpath + json-path + 2.2.0 + org.springframework spring-test diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java b/spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java new file mode 100644 index 0000000000..db021b8e8c --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Greeting.java @@ -0,0 +1,22 @@ +package com.baeldung.model; + +public class Greeting { + private int id; + private String message; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java new file mode 100644 index 0000000000..261d5793dc --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class ApplicationConfig extends WebMvcConfigurerAdapter { + + public ApplicationConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/jsp/"); + bean.setSuffix(".jsp"); + return bean; + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java index 8228eafd5c..8dcfe68a84 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java @@ -1,56 +1,80 @@ package com.baeldung.web.controller; -import com.baeldung.model.Company; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; - import java.util.HashMap; import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.model.Company; + @Controller public class CompanyController { - Map companyMap = new HashMap<>(); + Map companyMap = new HashMap<>(); - @RequestMapping(value = "/company", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("companyHome", "company", new Company()); - } + @RequestMapping(value = "/company", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("companyHome", "company", new Company()); + } - @RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Company getCompanyById(@PathVariable final long Id) { - return companyMap.get(Id); - } + @RequestMapping(value = "/company/{Id}", produces = { "application/json", + "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Company getCompanyById(@PathVariable final long Id) { + return companyMap.get(Id); + } - @RequestMapping(value = "/addCompany", method = RequestMethod.POST) - public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", company.getName()); - model.addAttribute("id", company.getId()); + @RequestMapping(value = "/addCompany", method = RequestMethod.POST) + public String submit(@ModelAttribute("company") final Company company, + final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", company.getName()); + model.addAttribute("id", company.getId()); - companyMap.put(company.getId(), company); + companyMap.put(company.getId(), company); - return "companyView"; - } + return "companyView"; + } - @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map matrixVars) { - return new ResponseEntity<>(matrixVars, HttpStatus.OK); - } + @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getEmployeeDataFromCompany( + @MatrixVariable(pathVar = "employee") final Map matrixVars) { + return new ResponseEntity<>(matrixVars, HttpStatus.OK); + } - @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) { - final Map result = new HashMap(); - result.put("name", name); - return new ResponseEntity<>(result, HttpStatus.OK); - } + @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getCompanyName( + @MatrixVariable(value = "name", pathVar = "company") final String name) { + final Map result = new HashMap(); + result.put("name", name); + return new ResponseEntity<>(result, HttpStatus.OK); + } + + @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Company getCompanyResponseBody() { + final Company company = new Company(2, "ABC"); + return company; + } + + @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getCompanyResponseEntity() { + final Company company = new Company(3, "123"); + return new ResponseEntity(company, HttpStatus.OK); + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java new file mode 100644 index 0000000000..6f764fedfb --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/GreetController.java @@ -0,0 +1,59 @@ +package com.baeldung.web.controller; + +import com.baeldung.model.Greeting; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +@Controller +public class GreetController { + + @RequestMapping(value = "/homePage", method = RequestMethod.GET) + public String index() { + return "index"; + } + + @RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greet() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithPathVariable(@PathVariable("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public Greeting greetWithQueryVariable(@RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPost() { + Greeting greeting = new Greeting(); + greeting.setId(1); + greeting.setMessage("Hello World!!!"); + return greeting; + } + + @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { + Greeting greeting = new Greeting(); + greeting.setId(id); + greeting.setMessage("Hello World " + name + "!!!"); + return greeting; + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java new file mode 100644 index 0000000000..8557b15492 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -0,0 +1,13 @@ +package com.baeldung.web.controller.advice; + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; + +@ControllerAdvice +public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { + + public JsonpControllerAdvice() { + super("callback"); + } + +} diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..2cf02bc2d8 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,5 @@ + + + Spring MVC - Integration Testing + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/index.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/index.jsp new file mode 100644 index 0000000000..fa5498c966 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/index.jsp @@ -0,0 +1,66 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1" %> + + + + + Company Data + + + + + + + Send AJAX JSON-P request! + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java new file mode 100644 index 0000000000..61e0f632f1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.web.controller; + + +import com.baeldung.spring.web.config.ApplicationConfig; +import org.junit.Assert; +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.MockServletContext; +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.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.ServletContext; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = {ApplicationConfig.class}) +public class GreetControllerIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + private static final String CONTENT_TYPE = "application/json"; + + + @Before + public void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenWAC_whenServletContext_thenItProvidesGreetController() { + ServletContext servletContext = wac.getServletContext(); + Assert.assertNotNull(servletContext); + Assert.assertTrue(servletContext instanceof MockServletContext); + Assert.assertNotNull(wac.getBean("greetController")); + } + + @Test + public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/homePage")).andDo(print()).andExpect(MockMvcResultMatchers.view().name("index")); + } + + @Test + public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn(); + Assert.assertEquals(CONTENT_TYPE, mvcResult.getResponse().getContentType()); + } + + @Test + public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java new file mode 100644 index 0000000000..0fd71a46dd --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java @@ -0,0 +1,61 @@ +package com.baeldung.web.controller; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +public class GreetControllerTest { + + private MockMvc mockMvc; + private static final String CONTENT_TYPE = "application/json"; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build(); + } + + @Test + public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception { + this.mockMvc.perform(get("/homePage")).andExpect(view().name("index")); + } + + @Test + public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John!!!")); + } + + @Test + public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World Doe!!!")); + } + + @Test + public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); + } + + @Test + public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.message").value("Hello World!!!")); + } + + @Test + public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); + } +} diff --git a/spring-mvc-no-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-mvc-no-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-mvc-no-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - -