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/autovalue-tutorial/pom.xml b/autovalue-tutorial/pom.xml index 37d595dce1..d1f8e825fc 100644 --- a/autovalue-tutorial/pom.xml +++ b/autovalue-tutorial/pom.xml @@ -1,36 +1,37 @@ - 4.0.0 - com.baeldung - autovalue-tutorial - 1.0 - AutoValue - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 7 - 7 - - - - - - - com.google.auto.value - auto-value - 1.2 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + autovalue-tutorial + 1.0 + AutoValue + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 7 + 7 + false + + + + + + + com.google.auto.value + auto-value + 1.2 + - - junit - junit - 4.3 - test - + + junit + junit + 4.3 + test + - + diff --git a/cdi/pom.xml b/cdi/pom.xml new file mode 100644 index 0000000000..b771857938 --- /dev/null +++ b/cdi/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.baeldung + cdi + 1.0-SNAPSHOT + + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + + org.aspectj + aspectjweaver + 1.8.9 + + + org.jboss.weld.se + weld-se-core + 2.3.5.Final + + + + junit + junit + 4.12 + test + + + org.springframework + spring-test + ${spring.version} + test + + + + + + 4.3.1.RELEASE + + + \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/interceptor/Audited.java b/cdi/src/main/java/com/baeldung/interceptor/Audited.java new file mode 100644 index 0000000000..3df4bef95e --- /dev/null +++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java @@ -0,0 +1,14 @@ +package com.baeldung.interceptor; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.interceptor.InterceptorBinding; + +@InterceptorBinding +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Audited { +} 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..c62d9a4127 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java @@ -0,0 +1,20 @@ +package com.baeldung.interceptor; + +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; + +@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..e15f049342 --- /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..e48039706d --- /dev/null +++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.aspect; + +import java.util.List; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.beans.factory.annotation.Autowired; + +@Aspect +public class SpringTestAspect { + @Autowired + private List accumulator; + + @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") + public Object auditMethod(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..b30c4a1326 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.configuration; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +import com.baeldung.spring.aspect.SpringTestAspect; +import com.baeldung.spring.service.SpringSuperService; + +@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..082eb2e0f8 --- /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..3529a796d2 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java @@ -0,0 +1,38 @@ +package com.baeldung.test; + +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 com.baeldung.interceptor.AuditedInterceptor; +import com.baeldung.service.SuperService; + +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..1f3a8d83e3 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java @@ -0,0 +1,34 @@ +package com.baeldung.test; + +import static org.hamcrest.CoreMatchers.is; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.configuration.AppConfig; +import com.baeldung.spring.service.SpringSuperService; + +@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/CharToStringTest.java b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java new file mode 100644 index 0000000000..d91016d104 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java @@ -0,0 +1,53 @@ +package com.baeldung; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CharToStringTest { + + @Test + public void givenChar_whenCallingStringValueOf_shouldConvertToString(){ + final char givenChar = 'x'; + + final String result = String.valueOf(givenChar); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){ + final char givenChar = 'x'; + + final String result = Character.toString(givenChar); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){ + final char givenChar = 'x'; + + final String result = new Character(givenChar).toString(); + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenConcatenated_shouldConvertToString4(){ + final char givenChar = 'x'; + + final String result = givenChar + ""; + + assertThat(result).isEqualTo("x"); + } + + @Test + public void givenChar_whenFormated_shouldConvertToString5(){ + final char givenChar = 'x'; + + final String result = String.format("%c", givenChar); + + assertThat(result).isEqualTo("x"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java new file mode 100644 index 0000000000..8143da5794 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +public class RandomListElementTest { + + @Test + public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() { + List givenList = Arrays.asList(1, 2, 3); + Random rand = new Random(); + givenList.get(rand.nextInt(givenList.size())); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java new file mode 100644 index 0000000000..6c1493d89b --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java @@ -0,0 +1,62 @@ +package com.baeldung; + +import com.google.common.primitives.Ints; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StringToIntOrIntegerTest { + + @Test + public void givenString_whenParsingInt_shouldConvertToInt() { + String givenString = "42"; + + int result = Integer.parseInt(givenString); + + assertThat(result).isEqualTo(42); + } + + + @Test + public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { + String givenString = "42"; + + Integer result = Integer.valueOf(givenString); + + assertThat(result).isEqualTo(new Integer(42)); + } + + @Test + public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() { + String givenString = "42"; + + Integer result = new Integer(givenString); + + assertThat(result).isEqualTo(new Integer(42)); + } + + @Test + public void givenString_whenCallingIntegerDecode_shouldConvertToInt() { + String givenString = "42"; + + int result = Integer.decode(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test + public void givenString_whenTryParse_shouldConvertToInt() { + String givenString = "42"; + + Integer result = Ints.tryParse(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test(expected = NumberFormatException.class) + public void givenInvalidInput_whenParsingInt_shouldThrow() { + String givenString = "nan"; + Integer.parseInt(givenString); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java new file mode 100644 index 0000000000..5363a73afa --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java @@ -0,0 +1,209 @@ +package com.baeldung.completablefuture; + +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class CompletableFutureTest { + + @Test + public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { + + Future completableFuture = calculateAsync(); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + public Future calculateAsync() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); + + return completableFuture; + } + + @Test + public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { + + Future completableFuture = CompletableFuture.completedFuture("Hello"); + + String result = completableFuture.get(); + assertEquals("Hello", result); + + } + + + public Future calculateAsyncWithCancellation() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); + + return completableFuture; + } + + + @Test(expected = CancellationException.class) + public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { + + Future future = calculateAsyncWithCancellation(); + future.get(); + + } + + @Test + public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { + + CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); + + assertEquals("Hello", future.get()); + + } + + @Test + public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); + + future.get(); + + } + + @Test + public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); + + future.get(); + + } + + @Test + public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApply(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + + @Test + public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> s1 + s2); + + assertEquals("Hello World", completableFuture.get()); + + } + + @Test + public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { + + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> System.out.println(s1 + s2)); + + } + + @Test + public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { + + CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); + CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); + CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); + + CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3); + + // ... + + combinedFuture.get(); + + assertTrue(future1.isDone()); + assertTrue(future2.isDone()); + assertTrue(future3.isDone()); + + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); + + assertEquals("Hello Beautiful World", combined); + + } + + @Test + public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { + + String name = null; + + // ... + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + if (name == null) { + throw new RuntimeException("Computation error!"); + } + return "Hello, " + name; + }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); + + assertEquals("Hello, Stranger!", completableFuture.get()); + + } + + @Test(expected = ExecutionException.class) + public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = new CompletableFuture<>(); + + // ... + + completableFuture.completeExceptionally(new RuntimeException("Calculation failed!")); + + // ... + + completableFuture.get(); + + } + + @Test + public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { + + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + + CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); + + assertEquals("Hello World", future.get()); + + } + +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java new file mode 100644 index 0000000000..ce878026d4 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java @@ -0,0 +1,199 @@ +package com.baeldung.functionalinterface; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.google.common.util.concurrent.Uninterruptibles; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class FunctionalInterfaceTest { + + @Test + public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { + + Map nameMap = new HashMap<>(); + Integer value = nameMap.computeIfAbsent("John", s -> s.length()); + + assertEquals(new Integer(4), nameMap.get("John")); + assertEquals(new Integer(4), value); + + } + + @Test + public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { + + Map nameMap = new HashMap<>(); + Integer value = nameMap.computeIfAbsent("John", String::length); + + assertEquals(new Integer(4), nameMap.get("John")); + assertEquals(new Integer(4), value); + + } + + public byte[] transformArray(short[] array, ShortToByteFunction function) { + byte[] transformedArray = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + transformedArray[i] = function.applyAsByte(array[i]); + } + return transformedArray; + } + + @Test + public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() { + + short[] array = {(short) 1, (short) 2, (short) 3}; + byte[] transformedArray = transformArray(array, s -> (byte) (s * 2)); + + byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6}; + assertArrayEquals(expectedArray, transformedArray); + + } + + @Test + public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() { + + Map salaries = new HashMap<>(); + salaries.put("John", 40000); + salaries.put("Freddy", 30000); + salaries.put("Samuel", 50000); + + salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000); + + assertEquals(new Integer(50000), salaries.get("John")); + assertEquals(new Integer(30000), salaries.get("Freddy")); + assertEquals(new Integer(60000), salaries.get("Samuel")); + + } + + + @Test + public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { + + Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); + thread.start(); + + } + + @Test + public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() { + + int[] fibs = {0, 1}; + Stream fibonacci = Stream.generate(() -> { + int result = fibs[1]; + int fib3 = fibs[0] + fibs[1]; + fibs[0] = fibs[1]; + fibs[1] = fib3; + return result; + }); + + List fibonacci5 = fibonacci.limit(5) + .collect(Collectors.toList()); + + assertEquals(new Integer(1), fibonacci5.get(0)); + assertEquals(new Integer(1), fibonacci5.get(1)); + assertEquals(new Integer(2), fibonacci5.get(2)); + assertEquals(new Integer(3), fibonacci5.get(3)); + assertEquals(new Integer(5), fibonacci5.get(4)); + + } + + @Test + public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { + + List names = Arrays.asList("John", "Freddy", "Samuel"); + names.forEach(name -> System.out.println("Hello, " + name)); + + } + + @Test + public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() { + + Map ages = new HashMap<>(); + ages.put("John", 25); + ages.put("Freddy", 24); + ages.put("Samuel", 30); + + ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); + + } + + @Test + public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { + + List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); + + List namesWithA = names.stream() + .filter(name -> name.startsWith("A")) + .collect(Collectors.toList()); + + assertEquals(2, namesWithA.size()); + assertTrue(namesWithA.contains("Angela")); + assertTrue(namesWithA.contains("Aaron")); + + } + + @Test + public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() { + + List names = Arrays.asList("bob", "josh", "megan"); + + names.replaceAll(String::toUpperCase); + + assertEquals("BOB", names.get(0)); + assertEquals("JOSH", names.get(1)); + assertEquals("MEGAN", names.get(2)); + + } + + @Test + public void whenUsingBinaryOperatorWithStreamReduce_thenResultIsSumOfValues() { + + List values = Arrays.asList(3, 5, 8, 9, 12); + + int sum = values.stream() + .reduce(0, (i1, i2) -> i1 + i2); + + assertEquals(37, sum); + + } + + @Test + public void whenComposingTwoFunctions_thenFunctionsExecuteSequentially() { + + Function intToString = Object::toString; + Function quote = s -> "'" + s + "'"; + + Function quoteIntToString = quote.compose(intToString); + + assertEquals("'5'", quoteIntToString.apply(5)); + + } + + public double squareLazy(Supplier lazyValue) { + return Math.pow(lazyValue.get(), 2); + } + + @Test + public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() { + + Supplier lazyValue = () -> { + Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS); + return 9d; + }; + + double valueSquared = squareLazy(lazyValue); + + assertEquals(81d, valueSquared, 0); + + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java new file mode 100644 index 0000000000..3231d6244f --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java @@ -0,0 +1,8 @@ +package com.baeldung.functionalinterface; + +@FunctionalInterface +public interface ShortToByteFunction { + + byte applyAsByte(short s); + +} 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/spring-security-rest-custom/.gitignore b/core-java-9/.gitignore similarity index 100% rename from spring-security-rest-custom/.gitignore rename to core-java-9/.gitignore diff --git a/core-java-9/README.md b/core-java-9/README.md new file mode 100644 index 0000000000..b5d4dbef95 --- /dev/null +++ b/core-java-9/README.md @@ -0,0 +1,5 @@ +========= + +## Core Java 9 Examples + +http://inprogress.baeldung.com/java-9-new-features/ \ No newline at end of file diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml new file mode 100644 index 0000000000..b29838d283 --- /dev/null +++ b/core-java-9/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + com.baeldung + core-java9 + 0.2-SNAPSHOT + + core-java9 + + + + apache.snapshots + http://repository.apache.org/snapshots/ + + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + core-java-9 + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.9 + 1.9 + + true + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + 1.7.13 + 1.0.13 + + + + + 3.6-jigsaw-SNAPSHOT + + + 2.19.1 + + + 1.3 + 4.12 + 1.10.19 + + + diff --git a/core-java-9/src/main/java/.gitignore b/core-java-9/src/main/java/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/src/main/java/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java new file mode 100644 index 0000000000..fd6a496b18 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java @@ -0,0 +1,23 @@ +package com.baeldung.java9.language; + +public interface PrivateInterface { + + private static String staticPrivate() { + return "static private"; + } + + private String instancePrivate() { + return "instance private"; + } + + public default void check(){ + String result = staticPrivate(); + if (!result.equals("static private")) + throw new AssertionError("Incorrect result for static private interface method"); + PrivateInterface pvt = new PrivateInterface() { + }; + result = pvt.instancePrivate(); + if (!result.equals("instance private")) + throw new AssertionError("Incorrect result for instance private interface method"); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java new file mode 100644 index 0000000000..d6682bd0c8 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -0,0 +1,44 @@ +package com.baeldung.java9.process; + +import java.io.File; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.stream.Stream; + + +public class ProcessUtils { + + public static String getClassPath(){ + String cp = System.getProperty("java.class.path"); + System.out.println("ClassPath is "+cp); + return cp; + } + + public static File getJavaCmd() throws IOException{ + String javaHome = System.getProperty("java.home"); + File javaCmd; + if(System.getProperty("os.name").startsWith("Win")){ + javaCmd = new File(javaHome, "bin/java.exe"); + }else{ + javaCmd = new File(javaHome, "bin/java"); + } + if(javaCmd.canExecute()){ + return javaCmd; + }else{ + throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable"); + } + } + + public static String getMainClass(){ + return System.getProperty("sun.java.command"); + } + + public static String getSystemProperties(){ + StringBuilder sb = new StringBuilder(); + System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) ); + return sb.toString(); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java new file mode 100644 index 0000000000..458f746496 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -0,0 +1,22 @@ +package com.baeldung.java9.process; + +import java.util.Optional; + +public class ServiceMain { + + public static void main(String[] args) throws InterruptedException { + ProcessHandle thisProcess = ProcessHandle.current(); + long pid = thisProcess.getPid(); + + + Optional opArgs = Optional.ofNullable(args); + String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); + + for (int i = 0; i < 10000; i++) { + System.out.println("Process " + procName + " with ID " + pid + " is running!"); + Thread.sleep(10000); + } + + } + +} diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml new file mode 100644 index 0000000000..eefdc7a337 --- /dev/null +++ b/core-java-9/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java new file mode 100644 index 0000000000..d6c16b91bc --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -0,0 +1,48 @@ +package com.baeldung.java9; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import java.awt.Image; +import java.awt.image.BaseMultiResolutionImage; +import java.awt.image.BufferedImage; +import java.awt.image.MultiResolutionImage; +import java.util.List; + +import org.junit.Test; + +public class MultiResultionImageTest { + + + @Test + public void baseMultiResImageTest() { + int baseIndex = 1; + int length = 4; + BufferedImage[] resolutionVariants = new BufferedImage[length]; + for (int i = 0; i < length; i++) { + resolutionVariants[i] = createImage(i); + } + MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants); + List rvImageList = bmrImage.getResolutionVariants(); + assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length); + + for (int i = 0; i < length; i++) { + int imageSize = getSize(i); + Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize); + assertSame("Images should be the same", testRVImage, resolutionVariants[i]); + } + + } + + private static int getSize(int i) { + return 8 * (i + 1); + } + + + private static BufferedImage createImage(int i) { + return new BufferedImage(getSize(i), getSize(i), + BufferedImage.TYPE_INT_RGB); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java new file mode 100644 index 0000000000..ab28b0a805 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java @@ -0,0 +1,126 @@ +package com.baeldung.java9.httpclient; + + + +import static java.net.HttpURLConnection.HTTP_OK; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; + +import org.junit.Before; +import org.junit.Test; + +public class SimpleHttpRequestsTest { + + private URI httpURI; + + @Before + public void init() throws URISyntaxException { + httpURI = new URI("http://www.baeldung.com/"); + } + + @Test + public void quickGet() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.create( httpURI ).GET(); + HttpResponse response = request.response(); + int responseStatusCode = response.statusCode(); + String responseBody = response.body(HttpResponse.asString()); + assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); + } + + @Test + public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + HttpRequest request = HttpRequest.create(httpURI).GET(); + long before = System.currentTimeMillis(); + CompletableFuture futureResponse = request.responseAsync(); + futureResponse.thenAccept( response -> { + String responseBody = response.body(HttpResponse.asString()); + }); + HttpResponse resp = futureResponse.get(); + HttpHeaders hs = resp.headers(); + assertTrue("There should be more then 1 header.", hs.map().size() >1); + } + + @Test + public void postMehtod() throws URISyntaxException, IOException, InterruptedException { + HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI); + requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE); + HttpRequest request = requestBuilder.POST(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + @Test + public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{ + CookieManager cManager = new CookieManager(); + cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); + + SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); + + HttpClient.Builder hcBuilder = HttpClient.create(); + hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); + HttpClient httpClient = hcBuilder.build(); + HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com")); + + HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); + HttpResponse response = request.response(); + int statusCode = response.statusCode(); + assertTrue("HTTP return code", statusCode == HTTP_OK); + } + + SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{ + SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters(); + String [] proto = sslP1.getApplicationProtocols(); + String [] cifers = sslP1.getCipherSuites(); + System.out.println(printStringArr(proto)); + System.out.println(printStringArr(cifers)); + return sslP1; + } + + String printStringArr(String ... args ){ + if(args == null){ + return null; + } + StringBuilder sb = new StringBuilder(); + for (String s : args){ + sb.append(s); + sb.append("\n"); + } + return sb.toString(); + } + + String printHeaders(HttpHeaders h){ + if(h == null){ + return null; + } + + StringBuilder sb = new StringBuilder(); + Map> hMap = h.map(); + for(String k : hMap.keySet()){ + sb.append(k).append(":"); + List l = hMap.get(k); + if( l != null ){ + l.forEach( s -> { sb.append(s).append(","); } ); + } + sb.append("\n"); + } + return sb.toString(); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java new file mode 100644 index 0000000000..33da6486f4 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java @@ -0,0 +1,36 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +public class DiamondTest { + + static class FooClass { + FooClass(X x) { + } + + FooClass(X x, Z z) { + } + } + + @Test + public void diamondTest() { + FooClass fc = new FooClass<>(1) { + }; + FooClass fc0 = new FooClass<>(1) { + }; + FooClass fc1 = new FooClass<>(1) { + }; + FooClass fc2 = new FooClass<>(1) { + }; + + FooClass fc3 = new FooClass<>(1, "") { + }; + FooClass fc4 = new FooClass<>(1, "") { + }; + FooClass fc5 = new FooClass<>(1, "") { + }; + FooClass fc6 = new FooClass<>(1, "") { + }; + + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java new file mode 100644 index 0000000000..29ef3930f8 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.language; + +import com.baeldung.java9.language.PrivateInterface; +import org.junit.Test; + +public class PrivateInterfaceTest { + + @Test + public void test() { + PrivateInterface piClass = new PrivateInterface() { + }; + piClass.check(); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java new file mode 100644 index 0000000000..687dfbc390 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java @@ -0,0 +1,70 @@ +package com.baeldung.java9.language; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class TryWithResourcesTest { + + static int closeCount = 0; + + static class MyAutoCloseable implements AutoCloseable{ + final FinalWrapper finalWrapper = new FinalWrapper(); + + public void close() { + closeCount++; + } + + static class FinalWrapper { + public final AutoCloseable finalCloseable = new AutoCloseable() { + @Override + public void close() throws Exception { + closeCount++; + } + }; + } + } + + @Test + public void tryWithResourcesTest() { + MyAutoCloseable mac = new MyAutoCloseable(); + + try (mac) { + assertEquals("Expected and Actual does not match", 0, closeCount); + } + + try (mac.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 1, closeCount); + } catch (Exception ex) { + } + + try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 2, closeCount); + } catch (Exception ex) { + } + + try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) { + assertEquals("Expected and Actual does not match", 3, closeCount); + } catch (Exception ex) { + } + + try { + throw new CloseableException(); + } catch (CloseableException ex) { + try (ex) { + assertEquals("Expected and Actual does not match", 4, closeCount); + } + } + assertEquals("Expected and Actual does not match", 5, closeCount); + } + + + static class CloseableException extends Exception implements AutoCloseable { + @Override + public void close() { + closeCount++; + } + } + +} + + diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java new file mode 100644 index 0000000000..419516cb64 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java @@ -0,0 +1,112 @@ +package com.baeldung.java9.process; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ProcessApi { + + + @Before + public void init() { + + } + + @Test + public void processInfoExample()throws NoSuchAlgorithmException{ + ProcessHandle self = ProcessHandle.current(); + long PID = self.getPid(); + ProcessHandle.Info procInfo = self.info(); + Optional args = procInfo.arguments(); + Optional cmd = procInfo.commandLine(); + Optional startTime = procInfo.startInstant(); + Optional cpuUsage = procInfo.totalCpuDuration(); + + waistCPU(); + System.out.println("Args "+ args); + System.out.println("Command " +cmd.orElse("EmptyCmd")); + System.out.println("Start time: "+ startTime.get().toString()); + System.out.println(cpuUsage.get().toMillis()); + + Stream allProc = ProcessHandle.current().children(); + allProc.forEach(p -> { + System.out.println("Proc "+ p.getPid()); + }); + + } + + @Test + public void createAndDestroyProcess() throws IOException, InterruptedException{ + int numberOfChildProcesses = 5; + for(int i=0; i < numberOfChildProcesses; i++){ + createNewJVM(ServiceMain.class, i).getPid(); + } + + Stream childProc = ProcessHandle.current().children(); + assertEquals( childProc.count(), numberOfChildProcesses); + + childProc = ProcessHandle.current().children(); + childProc.forEach(processHandle -> { + assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive()); + CompletableFuture onProcExit = processHandle.onExit(); + onProcExit.thenAccept(procHandle -> { + System.out.println("Process with PID "+ procHandle.getPid() + " has stopped"); + }); + }); + + Thread.sleep(10000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy()); + }); + + Thread.sleep(5000); + + childProc = ProcessHandle.current().children(); + childProc.forEach(procHandle -> { + assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive()); + }); + + } + + private Process createNewJVM(Class mainClass, int number) throws IOException{ + ArrayList cmdParams = new ArrayList(5); + cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath()); + cmdParams.add("-cp"); + cmdParams.add(ProcessUtils.getClassPath()); + cmdParams.add(mainClass.getName()); + cmdParams.add("Service "+ number); + ProcessBuilder myService = new ProcessBuilder(cmdParams); + myService.inheritIO(); + return myService.start(); + } + + private void waistCPU() throws NoSuchAlgorithmException{ + ArrayList randArr = new ArrayList(4096); + SecureRandom sr = SecureRandom.getInstanceStrong(); + Duration somecpu = Duration.ofMillis(4200L); + Instant end = Instant.now().plus(somecpu); + while (Instant.now().isBefore(end)) { + //System.out.println(sr.nextInt()); + randArr.add( sr.nextInt() ); + } + } + +} diff --git a/core-java-9/src/test/resources/.gitignore b/core-java-9/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-9/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Animal.java b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java new file mode 100644 index 0000000000..3f36243c29 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java @@ -0,0 +1,23 @@ +package com.baeldung.java.reflection; + +public abstract class Animal implements Eating { + + public static final String CATEGORY = "domestic"; + + private String name; + + public Animal(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + protected abstract String getSound(); + +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Bird.java b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java new file mode 100644 index 0000000000..bd6f13094c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java @@ -0,0 +1,36 @@ +package com.baeldung.java.reflection; + +public class Bird extends Animal { + private boolean walks; + + public Bird() { + super("bird"); + } + + public Bird(String name, boolean walks) { + super(name); + setWalks(walks); + } + + public Bird(String name) { + super(name); + } + + @Override + public String eats() { + return "grains"; + } + + @Override + protected String getSound() { + return "chaps"; + } + + public boolean walks() { + return walks; + } + + public void setWalks(boolean walks) { + this.walks = walks; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Eating.java b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java new file mode 100644 index 0000000000..479425cad4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java @@ -0,0 +1,5 @@ +package com.baeldung.java.reflection; + +public interface Eating { + String eats(); +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Goat.java b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java new file mode 100644 index 0000000000..503717ae5e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java @@ -0,0 +1,24 @@ +package com.baeldung.java.reflection; + +public class Goat extends Animal implements Locomotion { + + public Goat(String name) { + super(name); + } + + @Override + protected String getSound() { + return "bleat"; + } + + @Override + public String getLocomotion() { + return "walks"; + } + + @Override + public String eats() { + return "grass"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java new file mode 100644 index 0000000000..047c00cb13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java @@ -0,0 +1,5 @@ +package com.baeldung.java.reflection; + +public interface Locomotion { + String getLocomotion(); +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Person.java b/core-java/src/main/java/com/baeldung/java/reflection/Person.java new file mode 100644 index 0000000000..f3d7f9f001 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Person.java @@ -0,0 +1,6 @@ +package com.baeldung.java.reflection; + +public class Person { + private String name; + private int age; +} diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp deleted file mode 100644 index 20f137b416..0000000000 --- a/core-java/src/main/resources/targetFile.tmp +++ /dev/null @@ -1,2 +0,0 @@ -line 1 -a second line \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java new file mode 100644 index 0000000000..a12a2f205f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java @@ -0,0 +1,326 @@ +package com.baeldung.java.reflection; + +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; +import static org.junit.Assert.*; + +public class ReflectionTest { + + @Test + public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { + Object person = new Person(); + Field[] fields = person.getClass().getDeclaredFields(); + + List actualFieldNames = getFieldNames(fields); + + assertTrue(Arrays.asList("name", "age") + .containsAll(actualFieldNames)); + } + + @Test + public void givenObject_whenGetsClassName_thenCorrect() { + Object goat = new Goat("goat"); + Class clazz = goat.getClass(); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClassName_whenCreatesObject_thenCorrect() + throws ClassNotFoundException { + Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClass_whenRecognisesModifiers_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + int goatMods = goatClass.getModifiers(); + int animalMods = animalClass.getModifiers(); + + assertTrue(Modifier.isPublic(goatMods)); + assertTrue(Modifier.isAbstract(animalMods)); + assertTrue(Modifier.isPublic(animalMods)); + } + + @Test + public void givenClass_whenGetsPackageInfo_thenCorrect() { + Goat goat = new Goat("goat"); + Class goatClass = goat.getClass(); + Package pkg = goatClass.getPackage(); + + assertEquals("com.baeldung.java.reflection", pkg.getName()); + } + + @Test + public void givenClass_whenGetsSuperClass_thenCorrect() { + Goat goat = new Goat("goat"); + String str = "any string"; + + Class goatClass = goat.getClass(); + Class goatSuperClass = goatClass.getSuperclass(); + + assertEquals("Animal", goatSuperClass.getSimpleName()); + assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); + + } + + @Test + public void givenClass_whenGetsImplementedInterfaces_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Class[] goatInterfaces = goatClass.getInterfaces(); + Class[] animalInterfaces = animalClass.getInterfaces(); + + assertEquals(1, goatInterfaces.length); + assertEquals(1, animalInterfaces.length); + assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); + assertEquals("Eating", animalInterfaces[0].getSimpleName()); + } + + @Test + public void givenClass_whenGetsConstructor_thenCorrect() + throws ClassNotFoundException { + Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + Constructor[] constructors = goatClass.getConstructors(); + + assertEquals(1, constructors.length); + assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); + } + + @Test + public void givenClass_whenGetsFields_thenCorrect() + throws ClassNotFoundException { + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Field[] fields = animalClass.getDeclaredFields(); + + List actualFields = getFieldNames(fields); + + assertEquals(2, actualFields.size()); + assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); + } + + @Test + public void givenClass_whenGetsMethods_thenCorrect() + throws ClassNotFoundException { + Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + Method[] methods = animalClass.getDeclaredMethods(); + List actualMethods = getMethodNames(methods); + + assertEquals(4, actualMethods.size()); + assertTrue(actualMethods.containsAll(Arrays.asList("getName", + "setName", "getSound"))); + } + + @Test + public void givenClass_whenGetsAllConstructors_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Constructor[] constructors = birdClass.getConstructors(); + + assertEquals(3, constructors.length); + } + + @Test + public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Constructor cons1 = birdClass.getConstructor(); + Constructor cons2 = birdClass.getConstructor(String.class); + Constructor cons3 = birdClass.getConstructor(String.class, + boolean.class); + } + + @Test + public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + + Constructor cons1 = birdClass.getConstructor(); + Constructor cons2 = birdClass.getConstructor(String.class); + Constructor cons3 = birdClass.getConstructor(String.class, + boolean.class); + + Bird bird1 = (Bird) cons1.newInstance(); + Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); + Bird bird3 = (Bird) cons3.newInstance("dove", true); + + assertEquals("bird", bird1.getName()); + assertEquals("Weaver bird", bird2.getName()); + assertEquals("dove", bird3.getName()); + assertFalse(bird1.walks()); + assertTrue(bird3.walks()); + } + + @Test + public void givenClass_whenGetsPublicFields_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field[] fields = birdClass.getFields(); + assertEquals(1, fields.length); + assertEquals("CATEGORY", fields[0].getName()); + + } + + @Test + public void givenClass_whenGetsPublicFieldByName_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getField("CATEGORY"); + assertEquals("CATEGORY", field.getName()); + + } + + @Test + public void givenClass_whenGetsDeclaredFields_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field[] fields = birdClass.getDeclaredFields(); + assertEquals(1, fields.length); + assertEquals("walks", fields[0].getName()); + } + + @Test + public void givenClass_whenGetsFieldsByName_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getDeclaredField("walks"); + assertEquals("walks", field.getName()); + + } + + @Test + public void givenClassField_whenGetsType_thenCorrect() + throws Exception { + Field field = Class.forName("com.baeldung.java.reflection.Bird") + .getDeclaredField("walks"); + Class fieldClass = field.getType(); + assertEquals("boolean", fieldClass.getSimpleName()); + } + + @Test + public void givenClassField_whenSetsAndGetsValue_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Bird bird = (Bird) birdClass.newInstance(); + Field field = birdClass.getDeclaredField("walks"); + field.setAccessible(true); + + assertFalse(field.getBoolean(bird)); + assertFalse(bird.walks()); + + field.set(bird, true); + + assertTrue(field.getBoolean(bird)); + assertTrue(bird.walks()); + + } + + @Test + public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Field field = birdClass.getField("CATEGORY"); + field.setAccessible(true); + + assertEquals("domestic", field.get(null)); + } + + @Test + public void givenClass_whenGetsAllPublicMethods_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Method[] methods = birdClass.getMethods(); + List methodNames = getMethodNames(methods); + + assertTrue(methodNames.containsAll(Arrays + .asList("equals", "notifyAll", "hashCode", + "walks", "eats", "toString"))); + + } + + @Test + public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() + throws ClassNotFoundException { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); + + List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); + + assertEquals(expectedMethodNames.size(), actualMethodNames.size()); + assertTrue(expectedMethodNames.containsAll(actualMethodNames)); + assertTrue(actualMethodNames.containsAll(expectedMethodNames)); + + } + + @Test + public void givenMethodName_whenGetsMethod_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Method walksMethod = birdClass.getDeclaredMethod("walks"); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", + boolean.class); + + assertFalse(walksMethod.isAccessible()); + assertFalse(setWalksMethod.isAccessible()); + + walksMethod.setAccessible(true); + setWalksMethod.setAccessible(true); + + assertTrue(walksMethod.isAccessible()); + assertTrue(setWalksMethod.isAccessible()); + + } + + @Test + public void givenMethod_whenInvokes_thenCorrect() + throws Exception { + Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + Bird bird = (Bird) birdClass.newInstance(); + Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", + boolean.class); + Method walksMethod = birdClass.getDeclaredMethod("walks"); + boolean walks = (boolean) walksMethod.invoke(bird); + + assertFalse(walks); + assertFalse(bird.walks()); + + setWalksMethod.invoke(bird, true); + boolean walks2 = (boolean) walksMethod.invoke(bird); + + assertTrue(walks2); + assertTrue(bird.walks()); + + } + + private static List getFieldNames(Field[] fields) { + List fieldNames = new ArrayList<>(); + for (Field field : fields) + fieldNames.add(field.getName()); + return fieldNames; + + } + + private static List getMethodNames(Method[] methods) { + List methodNames = new ArrayList<>(); + for (Method method : methods) + methodNames.add(method.getName()); + return methodNames; + } + +} 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/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java new file mode 100644 index 0000000000..9cafa179ab --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java @@ -0,0 +1,146 @@ +package org.baeldung.java.collections; + +import com.google.common.collect.Sets; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; +import java.util.stream.*; + +import static java.util.stream.Collectors.*; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.*; + +public class ArrayListTest { + + private List stringsToSearch; + + @Before + public void setUp() { + List xs = LongStream.range(0, 16) + .boxed() + .map(Long::toHexString) + .collect(toCollection(ArrayList::new)); + stringsToSearch = new ArrayList<>(xs); + stringsToSearch.addAll(xs); + } + + @Test + public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() { + List xs = new ArrayList<>(); + assertTrue(xs.isEmpty()); + } + + @Test + public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { + Collection numbers = + IntStream.range(0, 10).boxed().collect(toSet()); + + List xs = new ArrayList<>(numbers); + assertEquals(10, xs.size()); + assertTrue(numbers.containsAll(xs)); + } + + @Test + public void givenElement_whenAddToArrayList_thenIsAdded() { + List xs = new ArrayList<>(); + + xs.add(1L); + xs.add(2L); + xs.add(1, 3L); + + assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs)); + } + + @Test + public void givenCollection_whenAddToArrayList_thenIsAdded() { + List xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); + LongStream.range(4, 10).boxed() + .collect(collectingAndThen(toCollection(ArrayList::new), ys -> xs.addAll(0, ys))); + + assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs)); + } + + @Test + public void givenExistingElement_whenCallIndexOf_thenReturnCorrectIndex() { + assertEquals(10, stringsToSearch.indexOf("a")); + assertEquals(26, stringsToSearch.lastIndexOf("a")); + } + + @Test + public void givenCondition_whenIterateArrayList_thenFindAllElementsSatisfyingCondition() { + Iterator it = stringsToSearch.iterator(); + Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); + + List result = new ArrayList<>(); + while (it.hasNext()) { + String s = it.next(); + if (matchingStrings.contains(s)) { + result.add(s); + } + } + + assertEquals(6, result.size()); + } + + @Test + public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() { + Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); + + List result = stringsToSearch + .stream() + .filter(matchingStrings::contains) + .collect(toCollection(ArrayList::new)); + + assertEquals(6, result.size()); + } + + @Test + public void givenSortedArray_whenUseBinarySearch_thenFindElement() { + List copy = new ArrayList<>(stringsToSearch); + Collections.sort(copy); + int index = Collections.binarySearch(copy, "f"); + assertThat(index, not(equalTo(-1))); + } + + @Test + public void givenIndex_whenRemove_thenCorrectElementRemoved() { + List xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + Collections.reverse(xs); + + xs.remove(0); + assertThat(xs.get(0), equalTo(8)); + + xs.remove(Integer.valueOf(0)); + assertFalse(xs.contains(0)); + } + + @Test + public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() { + List xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + ListIterator it = xs.listIterator(xs.size()); + List result = new ArrayList<>(xs.size()); + while (it.hasPrevious()) { + result.add(it.previous()); + } + + Collections.reverse(xs); + assertThat(result, equalTo(xs)); + } + + @Test + public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() { + Set matchingStrings + = Sets.newHashSet("a", "b", "c", "d", "e", "f"); + + Iterator it = stringsToSearch.iterator(); + while (it.hasNext()) { + if (matchingStrings.contains(it.next())) { + it.remove(); + } + } + + assertEquals(20, stringsToSearch.size()); + } +} 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/JavaInputStreamToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 55a0904499..1a6ac5f8ce 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -19,6 +19,7 @@ import java.io.Reader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.StandardCopyOption; import java.util.Scanner; import org.apache.commons.io.FileUtils; @@ -191,6 +192,16 @@ public class JavaInputStreamToXUnitTest { IOUtils.closeQuietly(outStream); } + @Test + public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { + final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); + final File targetFile = new File("src/main/resources/targetFile.tmp"); + + java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + IOUtils.closeQuietly(initialStream); + } + @Test public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); 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/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java new file mode 100644 index 0000000000..2c330c513d --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java @@ -0,0 +1,66 @@ +package org.baeldung.java.shell; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.*; +import java.util.concurrent.Executors; +import java.util.function.Consumer; + +public class JavaProcessUnitTest { + private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); + + private static class StreamGobbler implements Runnable { + private InputStream inputStream; + private Consumer consumer; + + public StreamGobbler(InputStream inputStream, Consumer consumer) { + this.inputStream = inputStream; + this.consumer = consumer; + } + + @Override + public void run() { + new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer); + } + } + + private Consumer consumer = new Consumer() { + @Override + public void accept(String s) { + Assert.assertNotNull(s); + } + }; + + private String homeDirectory = System.getProperty("user.home"); + + @Test + public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception { + Process process; + if (IS_WINDOWS) { + process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory)); + } else { + process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory)); + } + StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); + Executors.newSingleThreadExecutor().submit(streamGobbler); + int exitCode = process.waitFor(); + Assert.assertEquals(0, exitCode); + } + + @Test + public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception { + ProcessBuilder builder = new ProcessBuilder(); + if (IS_WINDOWS) { + builder.command("cmd.exe", "/c", "dir"); + } else { + builder.command("sh", "-c", "ls"); + } + builder.directory(new File(homeDirectory)); + Process process = builder.start(); + StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); + Executors.newSingleThreadExecutor().submit(streamGobbler); + int exitCode = process.waitFor(); + Assert.assertEquals(0, exitCode); + } +} 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/deltaspike/.gitignore b/deltaspike/.gitignore new file mode 100644 index 0000000000..aa121e866e --- /dev/null +++ b/deltaspike/.gitignore @@ -0,0 +1,3 @@ +/.idea +baeldung-jee7-seed.iml +/target diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml new file mode 100644 index 0000000000..22cf8f935c --- /dev/null +++ b/deltaspike/pom.xml @@ -0,0 +1,301 @@ + + + 4.0.0 + com.baeldung + deltaspike + 1.0 + war + deltaspike + A starter Java EE 7 webapp which uses DeltaSpike + + http://wildfly.org + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + + UTF-8 + + + 1.0.2.Final + + + 8.2.1.Final + + + 3.1 + 2.16 + 2.5 + + + 1.7 + 1.7 + + + + + + + + org.wildfly.bom + jboss-javaee-7.0-with-tools + ${version.jboss.bom} + pom + import + + + org.wildfly.bom + jboss-javaee-7.0-with-hibernate + ${version.jboss.bom} + pom + import + + + + + + + + + + + javax.enterprise + cdi-api + provided + + + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.2_spec + provided + + + + + org.jboss.resteasy + jaxrs-api + provided + + + + + org.hibernate.javax.persistence + hibernate-jpa-2.1-api + provided + + + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.2_spec + provided + + + + + + + org.hibernate + hibernate-validator + provided + + + org.slf4j + slf4j-api + + + + + + + org.jboss.spec.javax.faces + jboss-jsf-api_2.2_spec + provided + + + + + + + org.hibernate + hibernate-jpamodelgen + provided + + + + + org.hibernate + hibernate-validator-annotation-processor + provided + + + + + junit + junit + test + + + + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + org.jboss.arquillian.protocol + arquillian-protocol-servlet + test + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven + test + + + + org.apache.deltaspike.modules + deltaspike-data-module-api + 1.7.1 + compile + + + + org.apache.deltaspike.modules + deltaspike-data-module-impl + 1.7.1 + runtime + + + + + com.mysema.querydsl + querydsl-apt + 3.7.4 + provided + + + + com.mysema.querydsl + querydsl-jpa + 3.7.4 + + + + org.slf4j + slf4j-log4j12 + 1.6.1 + + + + + + ${project.artifactId} + + + maven-war-plugin + ${version.war.plugin} + + + false + + + + com.mysema.maven + apt-maven-plugin + 1.0.9 + + + + process + + + target/generated-sources/java + com.mysema.query.apt.jpa.JPAAnnotationProcessor + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven.plugin} + + + + + + + + + default + + true + + + + + maven-surefire-plugin + ${version.surefire.plugin} + + true + + + + + + + + + + + + arq-wildfly-managed + + + org.wildfly + wildfly-arquillian-container-managed + test + + + + + diff --git a/deltaspike/src/main/java/baeldung/controller/MemberController.java b/deltaspike/src/main/java/baeldung/controller/MemberController.java new file mode 100644 index 0000000000..7a9e9800f4 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/controller/MemberController.java @@ -0,0 +1,84 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.controller; + +import javax.annotation.PostConstruct; +import javax.enterprise.inject.Model; +import javax.enterprise.inject.Produces; +import javax.faces.application.FacesMessage; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; + +import baeldung.model.Member; +import baeldung.service.MemberRegistration; + +// The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an +// EL name +// Read more about the @Model stereotype in this FAQ: +// http://www.cdi-spec.org/faq/#accordion6 +@Model +public class MemberController { + + @Inject + private FacesContext facesContext; + + @Inject + private MemberRegistration memberRegistration; + + @Produces + @Named + private Member newMember; + + @PostConstruct + public void initNewMember() { + newMember = new Member(); + } + + public void register() throws Exception { + try { + memberRegistration.register(newMember); + FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registered!", "Registration successful"); + facesContext.addMessage(null, m); + initNewMember(); + } catch (Exception e) { + String errorMessage = getRootErrorMessage(e); + FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful"); + facesContext.addMessage(null, m); + } + } + + private String getRootErrorMessage(Exception e) { + // Default to general error message that registration failed. + String errorMessage = "Registration failed. See server log for more information"; + if (e == null) { + // This shouldn't happen, but return the default messages + return errorMessage; + } + + // Start with the exception and recurse to find the root cause + Throwable t = e; + while (t != null) { + // Get the message from the Throwable class instance + errorMessage = t.getLocalizedMessage(); + t = t.getCause(); + } + // This is the root cause message + return errorMessage; + } + +} diff --git a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java new file mode 100644 index 0000000000..9189dbba74 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java @@ -0,0 +1,29 @@ +package baeldung.data; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Disposes; +import javax.enterprise.inject.Produces; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; + +@ApplicationScoped +public class EntityManagerProducer { + @PersistenceUnit(unitName = "primary") + private EntityManagerFactory entityManagerFactory; + + @Produces + @Default + @RequestScoped + public EntityManager create() { + return this.entityManagerFactory.createEntityManager(); + } + + public void dispose(@Disposes @Default EntityManager entityManager) { + if (entityManager.isOpen()) { + entityManager.close(); + } + } +} \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java new file mode 100644 index 0000000000..c1f5fda31d --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java @@ -0,0 +1,54 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.data; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.event.Reception; +import javax.enterprise.inject.Produces; +import javax.inject.Inject; +import javax.inject.Named; +import java.util.List; + +import baeldung.model.Member; + +@RequestScoped +public class MemberListProducer { + + @Inject + private MemberRepository memberRepository; + + private List members; + + // @Named provides access the return value via the EL variable name "members" in the UI (e.g. + // Facelets or JSP view) + @Produces + @Named + public List getMembers() { + return members; + } + + public void onMemberListChanged(@Observes(notifyObserver = Reception.IF_EXISTS) final Member member) { + retrieveAllMembersOrderedByName(); + } + + @PostConstruct + public void retrieveAllMembersOrderedByName() { + members = memberRepository.findAllOrderedByNameWithQueryDSL(); + } +} diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java new file mode 100644 index 0000000000..56a4a4e634 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -0,0 +1,43 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.data; + +import baeldung.model.Member; +import baeldung.model.QMember; +import org.apache.deltaspike.data.api.*; + +import java.util.List; + +@Repository +@EntityManagerConfig(entityManagerResolver = SecondaryEntityManagerResolver.class) +public abstract class MemberRepository extends AbstractEntityRepository implements QueryDslSupport { + + public abstract Member findById(Long id); + + public abstract Member findByEmail(String email); + + @Query("from Member m order by m.name") + public abstract List findAllOrderedByName(); + + public List findAllOrderedByNameWithQueryDSL() { + final QMember member = QMember.member; + return jpaQuery() + .from(member) + .orderBy(member.email.asc()) + .list(member); + } +} diff --git a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java new file mode 100644 index 0000000000..8cb00958ab --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java @@ -0,0 +1,18 @@ +package baeldung.data; + +import com.mysema.query.jpa.impl.JPAQuery; +import org.apache.deltaspike.data.spi.DelegateQueryHandler; +import org.apache.deltaspike.data.spi.QueryInvocationContext; + +import javax.inject.Inject; + +public class QueryDslRepositoryExtension implements QueryDslSupport, DelegateQueryHandler { + + @Inject + private QueryInvocationContext context; + + @Override + public JPAQuery jpaQuery() { + return new JPAQuery(context.getEntityManager()); + } +} diff --git a/deltaspike/src/main/java/baeldung/data/QueryDslSupport.java b/deltaspike/src/main/java/baeldung/data/QueryDslSupport.java new file mode 100644 index 0000000000..72c33cf1b6 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/QueryDslSupport.java @@ -0,0 +1,7 @@ +package baeldung.data; + +import com.mysema.query.jpa.impl.JPAQuery; + +public interface QueryDslSupport { + JPAQuery jpaQuery(); +} diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java new file mode 100644 index 0000000000..41d30d9018 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java @@ -0,0 +1,30 @@ +package baeldung.data; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Disposes; +import javax.enterprise.inject.Produces; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; + +@ApplicationScoped +public class SecondaryEntityManagerProducer { + @PersistenceUnit(unitName = "secondary") + private EntityManagerFactory entityManagerFactory; + + @Produces + @Default + @RequestScoped + @SecondaryPersistenceUnit + public EntityManager create() { + return this.entityManagerFactory.createEntityManager(); + } + + public void dispose(@Disposes @Default EntityManager entityManager) { + if (entityManager.isOpen()) { + entityManager.close(); + } + } +} \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerResolver.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerResolver.java new file mode 100644 index 0000000000..7faaa1ac49 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerResolver.java @@ -0,0 +1,18 @@ +package baeldung.data; + +import org.apache.deltaspike.data.api.EntityManagerResolver; + +import javax.inject.Inject; +import javax.persistence.EntityManager; + +public class SecondaryEntityManagerResolver implements EntityManagerResolver { + + @Inject + @SecondaryPersistenceUnit + private EntityManager entityManager; + + @Override + public EntityManager resolveEntityManager() { + return entityManager; + } +} diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryPersistenceUnit.java b/deltaspike/src/main/java/baeldung/data/SecondaryPersistenceUnit.java new file mode 100644 index 0000000000..e60d0aff05 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SecondaryPersistenceUnit.java @@ -0,0 +1,12 @@ +package baeldung.data; + +import javax.inject.Qualifier; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Qualifier +public @interface SecondaryPersistenceUnit { +} diff --git a/deltaspike/src/main/java/baeldung/model/Member.java b/deltaspike/src/main/java/baeldung/model/Member.java new file mode 100644 index 0000000000..e178dcf63a --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/Member.java @@ -0,0 +1,93 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import javax.xml.bind.annotation.XmlRootElement; + +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotEmpty; + +@SuppressWarnings("serial") +@Entity +@XmlRootElement +@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email")) +public class Member implements Serializable { + + @Id + @GeneratedValue + private Long id; + + @NotNull + @Size(min = 1, max = 25) + @Pattern(regexp = "[^0-9]*", message = "Must not contain numbers") + private String name; + + @NotNull + @NotEmpty + @Email + private String email; + + @NotNull + @Size(min = 10, max = 12) + @Digits(fraction = 0, integer = 12) + @Column(name = "phone_number") + private String phoneNumber; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } +} diff --git a/deltaspike/src/main/java/baeldung/rest/JaxRsActivator.java b/deltaspike/src/main/java/baeldung/rest/JaxRsActivator.java new file mode 100644 index 0000000000..9357ae0ea6 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/rest/JaxRsActivator.java @@ -0,0 +1,33 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.rest; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +/** + * A class extending {@link Application} and annotated with @ApplicationPath is the Java EE 7 "no XML" approach to activating + * JAX-RS. + *

+ *

+ * Resources are served relative to the servlet path specified in the {@link ApplicationPath} annotation. + *

+ */ +@ApplicationPath("/rest") +public class JaxRsActivator extends Application { + /* class body intentionally left blank */ +} diff --git a/deltaspike/src/main/java/baeldung/rest/MemberResourceRESTService.java b/deltaspike/src/main/java/baeldung/rest/MemberResourceRESTService.java new file mode 100644 index 0000000000..5a09e45591 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/rest/MemberResourceRESTService.java @@ -0,0 +1,185 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.rest; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.persistence.NoResultException; +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.ValidationException; +import javax.validation.Validator; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import baeldung.data.MemberRepository; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; + +/** + * JAX-RS Example + *

+ * This class produces a RESTful service to read/write the contents of the members table. + */ +@Path("/members") +@RequestScoped +public class MemberResourceRESTService { + + @Inject + private Logger log; + + @Inject + private Validator validator; + + @Inject + private MemberRepository repository; + + @Inject + MemberRegistration registration; + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List listAllMembers() { + return repository.findAllOrderedByName(); + } + + @GET + @Path("/{id:[0-9][0-9]*}") + @Produces(MediaType.APPLICATION_JSON) + public Member lookupMemberById(@PathParam("id") long id) { + Member member = repository.findById(id); + if (member == null) { + throw new WebApplicationException(Response.Status.NOT_FOUND); + } + return member; + } + + /** + * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok, + * or with a map of fields, and related errors. + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response createMember(Member member) { + + Response.ResponseBuilder builder = null; + + try { + // Validates member using bean validation + validateMember(member); + + registration.register(member); + + // Create an "ok" response + builder = Response.ok(); + } catch (ConstraintViolationException ce) { + // Handle bean validation issues + builder = createViolationResponse(ce.getConstraintViolations()); + } catch (ValidationException e) { + // Handle the unique constrain violation + Map responseObj = new HashMap<>(); + responseObj.put("email", "Email taken"); + builder = Response.status(Response.Status.CONFLICT).entity(responseObj); + } catch (Exception e) { + // Handle generic exceptions + Map responseObj = new HashMap<>(); + responseObj.put("error", e.getMessage()); + builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); + } + + return builder.build(); + } + + /** + *

+ * Validates the given Member variable and throws validation exceptions based on the type of error. If the error is standard + * bean validation errors then it will throw a ConstraintValidationException with the set of the constraints violated. + *

+ *

+ * If the error is caused because an existing member with the same email is registered it throws a regular validation + * exception so that it can be interpreted separately. + *

+ * + * @param member Member to be validated + * @throws ConstraintViolationException If Bean Validation errors exist + * @throws ValidationException If member with the same email already exists + */ + private void validateMember(Member member) throws ConstraintViolationException, ValidationException { + // Create a bean validator and check for issues. + Set> violations = validator.validate(member); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(new HashSet>(violations)); + } + + // Check the uniqueness of the email address + if (emailAlreadyExists(member.getEmail())) { + throw new ValidationException("Unique Email Violation"); + } + } + + /** + * Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used + * by clients to show violations. + * + * @param violations A set of violations that needs to be reported + * @return JAX-RS response containing all violations + */ + private Response.ResponseBuilder createViolationResponse(Set> violations) { + log.fine("Validation completed. violations found: " + violations.size()); + + Map responseObj = new HashMap<>(); + + for (ConstraintViolation violation : violations) { + responseObj.put(violation.getPropertyPath().toString(), violation.getMessage()); + } + + return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); + } + + /** + * Checks if a member with the same email address is already registered. This is the only way to easily capture the + * "@UniqueConstraint(columnNames = "email")" constraint from the Member class. + * + * @param email The email to check + * @return True if the email already exists, and false otherwise + */ + public boolean emailAlreadyExists(String email) { + Member member = null; + try { + member = repository.findByEmail(email); + } catch (NoResultException e) { + // ignore + } + return member != null; + } +} diff --git a/deltaspike/src/main/java/baeldung/service/MemberRegistration.java b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java new file mode 100644 index 0000000000..ec65471622 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java @@ -0,0 +1,85 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.service; + +import baeldung.data.MemberRepository; +import baeldung.data.SecondaryPersistenceUnit; +import baeldung.model.Member; +import baeldung.model.QMember; + +import javax.ejb.Stateless; +import javax.enterprise.event.Event; +import javax.enterprise.inject.Default; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.ValidationException; +import javax.validation.Validator; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; + +@Stateless +public class MemberRegistration { + + @Inject + private Logger log; + + @Inject + private MemberRepository repository; + + @Inject + private Event memberEventSrc; + + @Inject + private Validator validator; + + private void validateMember(Member member) throws ConstraintViolationException, ValidationException { + // Create a bean validator and check for issues. + Set> violations = validator.validate(member); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(new HashSet>(violations)); + } + + // Check the uniqueness of the email address + if (emailAlreadyExists(member.getEmail())) { + throw new ValidationException("Unique Email Violation"); + } + } + + + public void register(Member member) throws Exception { + log.info("Registering " + member.getName()); + validateMember(member); + repository.save(member); + memberEventSrc.fire(member); + } + + public boolean emailAlreadyExists(String email) { + Member member = null; + try { + member = repository.findByEmail(email); + } catch (NoResultException e) { + // ignore + } + return member != null; + } + +} diff --git a/deltaspike/src/main/java/baeldung/util/Resources.java b/deltaspike/src/main/java/baeldung/util/Resources.java new file mode 100644 index 0000000000..2cc1f235d7 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/util/Resources.java @@ -0,0 +1,53 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.util; + +import java.util.logging.Logger; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.faces.context.FacesContext; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +/** + * This class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans + *

+ *

+ * Example injection on a managed bean field: + *

+ *

+ *

+ * @Inject
+ * private EntityManager em;
+ * 
+ */ +public class Resources { + + @Produces + public Logger produceLog(InjectionPoint injectionPoint) { + return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); + } + + @Produces + @RequestScoped + public FacesContext produceFacesContext() { + return FacesContext.getCurrentInstance(); + } + +} diff --git a/deltaspike/src/main/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/main/resources/META-INF/apache-deltaspike.properties new file mode 100644 index 0000000000..a861ad729a --- /dev/null +++ b/deltaspike/src/main/resources/META-INF/apache-deltaspike.properties @@ -0,0 +1 @@ +globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy diff --git a/deltaspike/src/main/resources/META-INF/persistence.xml b/deltaspike/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..b68c2c1bb1 --- /dev/null +++ b/deltaspike/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,21 @@ + + + + java:jboss/datasources/baeldung-jee7-seedDS + + + + + + + java:jboss/datasources/baeldung-jee7-seed-secondaryDS + + + + + + diff --git a/deltaspike/src/main/resources/import.sql b/deltaspike/src/main/resources/import.sql new file mode 100644 index 0000000000..154f4e9923 --- /dev/null +++ b/deltaspike/src/main/resources/import.sql @@ -0,0 +1,19 @@ +-- +-- JBoss, Home of Professional Open Source +-- Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual +-- contributors by the @authors tag. See the copyright.txt in the +-- distribution for a full listing of individual contributors. +-- +-- Licensed 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. +-- + +-- You can use this file to load seed data into the database using SQL statements +insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212') diff --git a/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-ds.xml b/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-ds.xml new file mode 100644 index 0000000000..1a8e350667 --- /dev/null +++ b/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-ds.xml @@ -0,0 +1,37 @@ + + + + + + + jdbc:h2:mem:baeldung-jee7-seed;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + diff --git a/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-secondary-ds.xml b/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-secondary-ds.xml new file mode 100644 index 0000000000..c4c9afb2e0 --- /dev/null +++ b/deltaspike/src/main/webapp/WEB-INF/baeldung-jee7-seed-secondary-ds.xml @@ -0,0 +1,19 @@ + + + + + + jdbc:h2:mem:baeldung-jee7-seed;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + diff --git a/deltaspike/src/main/webapp/WEB-INF/beans.xml b/deltaspike/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..0090177eb7 --- /dev/null +++ b/deltaspike/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,23 @@ + + + + + diff --git a/deltaspike/src/main/webapp/WEB-INF/faces-config.xml b/deltaspike/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..26cf98b669 --- /dev/null +++ b/deltaspike/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,25 @@ + + + + + diff --git a/deltaspike/src/main/webapp/WEB-INF/templates/default.xhtml b/deltaspike/src/main/webapp/WEB-INF/templates/default.xhtml new file mode 100644 index 0000000000..2f001f8626 --- /dev/null +++ b/deltaspike/src/main/webapp/WEB-INF/templates/default.xhtml @@ -0,0 +1,55 @@ + + + + + baeldung-jee7-seed + + + + +
+
+ +
+
+ + [Template content will be inserted here] + +
+ + +
+
+ diff --git a/deltaspike/src/main/webapp/index.html b/deltaspike/src/main/webapp/index.html new file mode 100644 index 0000000000..dd6c4fb886 --- /dev/null +++ b/deltaspike/src/main/webapp/index.html @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/deltaspike/src/main/webapp/index.xhtml b/deltaspike/src/main/webapp/index.xhtml new file mode 100644 index 0000000000..0f515601be --- /dev/null +++ b/deltaspike/src/main/webapp/index.xhtml @@ -0,0 +1,97 @@ + + + + +

Welcome to WildFly!

+ +
+

You have successfully deployed a Java EE 7 Enterprise + Application.

+

Your application can run on:

+ +
+ + +

Member Registration

+

Enforces annotation-based constraints defined on the + model class.

+ + + + + + + + + + + + + + +

+ + + + +

+
+

Members

+ + No registered members. + + + + Id + #{_member.id} + + + Name + #{_member.name} + + + Email + #{_member.email} + + + Phone # + #{_member.phoneNumber} + + + REST URL + /rest/members/#{_member.id} + + + REST URL for all members: /rest/members + + +
+
diff --git a/deltaspike/src/main/webapp/resources/css/screen.css b/deltaspike/src/main/webapp/resources/css/screen.css new file mode 100644 index 0000000000..0e81d5a9d2 --- /dev/null +++ b/deltaspike/src/main/webapp/resources/css/screen.css @@ -0,0 +1,202 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +/* Core styles for the page */ +body { + margin: 0; + padding: 0; + background-color: #F1F1F1; + font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; + font-size: 0.8em; + color:#363636; +} + +#container { + margin: 0 auto; + padding: 0 20px 10px 20px; + border-top: 5px solid #000000; + border-left: 5px solid #8c8f91; + border-right: 5px solid #8c8f91; + border-bottom: 25px solid #8c8f91; + width: 865px; /* subtract 40px from banner width for padding */ + background: #FFFFFF; + background-image: url(#{request.contextPath}/resources/gfx/headerbkg.png); + background-repeat: repeat-x; + padding-top: 30px; + box-shadow: 3px 3px 15px #d5d5d5; +} +#content { + float: left; + width: 500px; + margin: 20px; +} +#aside { + font-size: 0.9em; + width: 275px; + float: left; + margin: 20px 0px; + border: 1px solid #D5D5D5; + background: #F1F1F1; + background-image: url(#{request.contextPath}/resources/gfx/asidebkg.png); + background-repeat: repeat-x; + padding: 20px; +} + +#aside ul { + padding-left: 30px; +} +.dualbrand { + float: right; + padding-right: 10px; +} +#footer { + clear: both; + text-align: center; + color: #666666; + font-size: 0.85em; +} +code { + font-size: 1.1em; +} +a { + color: #4a5d75; + text-decoration: none; +} +a:hover { + color: #369; + text-decoration: underline; +} +h1 { + color:#243446; + font-size: 2.25em; +} +h2 { + font-size: 1em; +} +h3 { + color:#243446; +} +h4 { +} +h5 { +} +h6 { +} +/* Member registration styles */ +span.invalid { + padding-left: 3px; + color: red; +} +form { + padding: 1em; + font: 80%/1 sans-serif; + width: 375px; + border: 1px solid #D5D5D5; +} +label { + float: left; + width: 15%; + margin-left: 20px; + margin-right: 0.5em; + padding-top: 0.2em; + text-align: right; + font-weight: bold; + color:#363636; +} +input { + margin-bottom: 8px; +} +.register { + float: left; + margin-left: 85px; +} + +/* ----- table style ------- */ + + +/* = Simple Table style (black header, grey/white stripes */ + +.simpletablestyle { + background-color:#E6E7E8; + clear:both; + width: 550px; +} + +.simpletablestyle img { + border:0px; +} + +.simpletablestyle td { + height:2em; + padding-left: 6px; + font-size:11px; + padding:5px 5px; +} + +.simpletablestyle th { + background: url(#{request.contextPath}/resources/gfx/bkg-blkheader.png) black repeat-x top left; + font-size:12px; + font-weight:normal; + padding:0 10px 0 5px; + border-bottom:#999999 dotted 1px; +} + +.simpletablestyle thead { + background: url(#{request.contextPath}/resources/gfx/bkg-blkheader.png) black repeat-x top left; + height:31px; + font-size:10px; + font-weight:bold; + color:#FFFFFF; + text-align:left; +} + +.simpletablestyle .header a { + color:#94aebd; +} + +.simpletablestype tfoot { + height: 20px; + font-size: 10px; + font-weight: bold; + background-color: #EAECEE; + text-align: center; +} + +.simpletablestyle tr.header td { + padding: 0px 10px 0px 5px; +} + + +.simpletablestyle .subheader { + background-color: #e6e7e8; + font-size:10px; + font-weight:bold; + color:#000000; + text-align:left; +} + +/* Using new CSS3 selectors for styling*/ +.simpletablestyle tr:nth-child(odd) { + background: #f4f3f3; +} +.simpletablestyle tr:nth-child(even) { + background: #ffffff; +} + +.simpletablestyle td a:hover { + color:#3883ce; + text-decoration:none; +} diff --git a/deltaspike/src/main/webapp/resources/gfx/asidebkg.png b/deltaspike/src/main/webapp/resources/gfx/asidebkg.png new file mode 100644 index 0000000000..543d66ad37 Binary files /dev/null and b/deltaspike/src/main/webapp/resources/gfx/asidebkg.png differ diff --git a/deltaspike/src/main/webapp/resources/gfx/bkg-blkheader.png b/deltaspike/src/main/webapp/resources/gfx/bkg-blkheader.png new file mode 100644 index 0000000000..54b95f349f Binary files /dev/null and b/deltaspike/src/main/webapp/resources/gfx/bkg-blkheader.png differ diff --git a/deltaspike/src/main/webapp/resources/gfx/dualbrand_logo.png b/deltaspike/src/main/webapp/resources/gfx/dualbrand_logo.png new file mode 100644 index 0000000000..68853292cb Binary files /dev/null and b/deltaspike/src/main/webapp/resources/gfx/dualbrand_logo.png differ diff --git a/deltaspike/src/main/webapp/resources/gfx/headerbkg.png b/deltaspike/src/main/webapp/resources/gfx/headerbkg.png new file mode 100644 index 0000000000..2669028ba2 Binary files /dev/null and b/deltaspike/src/main/webapp/resources/gfx/headerbkg.png differ diff --git a/deltaspike/src/main/webapp/resources/gfx/wildfly_400x130.jpg b/deltaspike/src/main/webapp/resources/gfx/wildfly_400x130.jpg new file mode 100644 index 0000000000..667c5a66a3 Binary files /dev/null and b/deltaspike/src/main/webapp/resources/gfx/wildfly_400x130.jpg differ diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java new file mode 100644 index 0000000000..0270d2d164 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java @@ -0,0 +1,84 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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. + */ +package baeldung.test; + +import static org.junit.Assert.assertNotNull; + +import java.io.File; +import java.util.logging.Logger; + +import javax.inject.Inject; + +import baeldung.data.*; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; +import baeldung.util.Resources; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(Arquillian.class) +public class MemberRegistrationTest { + @Deployment + public static Archive createTestArchive() { + File[] files = Maven.resolver().loadPomFromFile("pom.xml") + .importRuntimeDependencies().resolve().withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class, "test.war") + .addClasses( + EntityManagerProducer.class, + Member.class, + MemberRegistration.class, + MemberRepository.class, + Resources.class, + QueryDslRepositoryExtension.class, + QueryDslSupport.class, + SecondaryPersistenceUnit.class, + SecondaryEntityManagerProducer.class, + SecondaryEntityManagerResolver.class) + .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") + .addAsResource("META-INF/apache-deltaspike.properties") + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsWebInfResource("test-ds.xml") + .addAsWebInfResource("test-secondary-ds.xml") + .addAsLibraries(files); + } + + @Inject + MemberRegistration memberRegistration; + + @Inject + Logger log; + + @Test + public void testRegister() throws Exception { + Member newMember = new Member(); + newMember.setName("Jane Doe"); + newMember.setEmail("jane@mailinator.com"); + newMember.setPhoneNumber("2125551234"); + memberRegistration.register(newMember); + assertNotNull(newMember.getId()); + log.info(newMember.getName() + " was persisted with id " + newMember.getId()); + } + +} diff --git a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties new file mode 100644 index 0000000000..a861ad729a --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties @@ -0,0 +1 @@ +globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy diff --git a/deltaspike/src/test/resources/META-INF/test-persistence.xml b/deltaspike/src/test/resources/META-INF/test-persistence.xml new file mode 100644 index 0000000000..bc9fbcbeef --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/test-persistence.xml @@ -0,0 +1,21 @@ + + + + java:jboss/datasources/baeldung-jee7-seedTestDS + + + + + + + java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS + + + + + + diff --git a/deltaspike/src/test/resources/arquillian.xml b/deltaspike/src/test/resources/arquillian.xml new file mode 100644 index 0000000000..14f9e53bbd --- /dev/null +++ b/deltaspike/src/test/resources/arquillian.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + target\wildfly-run\wildfly-10.0.0.Final + + + + diff --git a/deltaspike/src/test/resources/test-ds.xml b/deltaspike/src/test/resources/test-ds.xml new file mode 100644 index 0000000000..8c5d022690 --- /dev/null +++ b/deltaspike/src/test/resources/test-ds.xml @@ -0,0 +1,16 @@ + + + + jdbc:h2:mem:baeldung-jee7-seed-test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + diff --git a/deltaspike/src/test/resources/test-secondary-ds.xml b/deltaspike/src/test/resources/test-secondary-ds.xml new file mode 100644 index 0000000000..f545adc6d6 --- /dev/null +++ b/deltaspike/src/test/resources/test-secondary-ds.xml @@ -0,0 +1,16 @@ + + + + jdbc:h2:mem:baeldung-jee7-seed-test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + 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/src/test/resources/dozer_custom_convertor.xml b/dozer/src/test/resources/dozer_custom_convertor.xml new file mode 100644 index 0000000000..0cbe5a7918 --- /dev/null +++ b/dozer/src/test/resources/dozer_custom_convertor.xml @@ -0,0 +1,14 @@ + + + + + + com.baeldung.dozer.Personne3 + com.baeldung.dozer.Person3 + + + + + \ No newline at end of file diff --git a/dozer/src/test/resources/dozer_mapping.xml b/dozer/src/test/resources/dozer_mapping.xml new file mode 100644 index 0000000000..13f31db11a --- /dev/null +++ b/dozer/src/test/resources/dozer_mapping.xml @@ -0,0 +1,17 @@ + + + + com.baeldung.dozer.Personne + com.baeldung.dozer.Person + + nom + name + + + surnom + nickname + + + \ No newline at end of file diff --git a/dozer/src/test/resources/dozer_mapping2.xml b/dozer/src/test/resources/dozer_mapping2.xml new file mode 100644 index 0000000000..63411568b6 --- /dev/null +++ b/dozer/src/test/resources/dozer_mapping2.xml @@ -0,0 +1,17 @@ + + + + com.baeldung.dozer.Personne + com.baeldung.dozer.Person + + nom + name + + + surnom + nickname + + + \ No newline at end of file diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java new file mode 100644 index 0000000000..3f7723facd --- /dev/null +++ b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java @@ -0,0 +1,63 @@ +package org.baeldung.equalshashcode.entities; + +import java.util.ArrayList; +import java.util.HashSet; + +public class ComplexClass { + + private ArrayList genericArrayList; + private HashSet integerHashSet; + + public ComplexClass(ArrayList genericArrayList, HashSet integerHashSet) { + super(); + this.genericArrayList = genericArrayList; + this.integerHashSet = integerHashSet; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((genericArrayList == null) ? 0 : genericArrayList.hashCode()); + result = prime * result + ((integerHashSet == null) ? 0 : integerHashSet.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof ComplexClass)) + return false; + ComplexClass other = (ComplexClass) obj; + if (genericArrayList == null) { + if (other.genericArrayList != null) + return false; + } else if (!genericArrayList.equals(other.genericArrayList)) + return false; + if (integerHashSet == null) { + if (other.integerHashSet != null) + return false; + } else if (!integerHashSet.equals(other.integerHashSet)) + return false; + return true; + } + + protected ArrayList getGenericArrayList() { + return genericArrayList; + } + + protected void setGenericArrayList(ArrayList genericArrayList) { + this.genericArrayList = genericArrayList; + } + + protected HashSet getIntegerHashSet() { + return integerHashSet; + } + + protected void setIntegerHashSet(HashSet integerHashSet) { + this.integerHashSet = integerHashSet; + } +} diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java new file mode 100644 index 0000000000..ebe005688c --- /dev/null +++ b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -0,0 +1,54 @@ +package org.baeldung.equalshashcode.entities; + +public class PrimitiveClass { + + private boolean primitiveBoolean; + private int primitiveInt; + + public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) { + super(); + this.primitiveBoolean = primitiveBoolean; + this.primitiveInt = primitiveInt; + } + + protected boolean isPrimitiveBoolean() { + return primitiveBoolean; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (primitiveBoolean ? 1231 : 1237); + result = prime * result + primitiveInt; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PrimitiveClass other = (PrimitiveClass) obj; + if (primitiveBoolean != other.primitiveBoolean) + return false; + if (primitiveInt != other.primitiveInt) + return false; + return true; + } + + protected void setPrimitiveBoolean(boolean primitiveBoolean) { + this.primitiveBoolean = primitiveBoolean; + } + + protected int getPrimitiveInt() { + return primitiveInt; + } + + protected void setPrimitiveInt(int primitiveInt) { + this.primitiveInt = primitiveInt; + } +} diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java new file mode 100644 index 0000000000..315ef41a12 --- /dev/null +++ b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java @@ -0,0 +1,60 @@ +package org.baeldung.equalshashcode.entities; + +public class Rectangle extends Shape { + private double width; + private double length; + + public Rectangle(double width, double length) { + this.width = width; + this.length = length; + } + + @Override + public double area() { + // A = w * l + return width * length; + } + + @Override + public double perimeter() { + // P = 2(w + l) + return 2 * (width + length); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(length); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(width); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Rectangle other = (Rectangle) obj; + if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length)) + return false; + if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width)) + return false; + return true; + } + + protected double getWidth() { + return width; + } + + protected double getLength() { + return length; + } + +} \ No newline at end of file diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java new file mode 100644 index 0000000000..3bfc81da8f --- /dev/null +++ b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Shape.java @@ -0,0 +1,7 @@ +package org.baeldung.equalshashcode.entities; + +public abstract class Shape { + public abstract double area(); + + public abstract double perimeter(); +} diff --git a/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java new file mode 100644 index 0000000000..f11e34f0ba --- /dev/null +++ b/eclipse/src/main/java/org/baeldung/equalshashcode/entities/Square.java @@ -0,0 +1,58 @@ +package org.baeldung.equalshashcode.entities; + +import java.awt.Color; + +public class Square extends Rectangle { + + Color color; + + public Square(double width, Color color) { + super(width, width); + this.color = color; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((color == null) ? 0 : color.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof Square)) { + return false; + } + Square other = (Square) obj; + if (color == null) { + if (other.color != null) { + return false; + } + } else if (!color.equals(other.color)) { + return false; + } + return true; + } + + protected Color getColor() { + return color; + } + + protected void setColor(Color color) { + this.color = color; + } + +} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java new file mode 100644 index 0000000000..09123e988b --- /dev/null +++ b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java @@ -0,0 +1,34 @@ +package org.baeldung.equalshashcode.entities; + +import java.util.ArrayList; +import java.util.HashSet; + +import org.junit.Assert; +import org.junit.Test; + +public class ComplexClassTest { + + @Test + public void testEqualsAndHashcodes() { + + ArrayList strArrayList = new ArrayList(); + strArrayList.add("abc"); + strArrayList.add("def"); + ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45, 67)); + ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45, 67)); + + ArrayList strArrayListD = new ArrayList(); + strArrayListD.add("lmn"); + strArrayListD.add("pqr"); + ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45, 67)); + + // equals() + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + // hashCode() + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + // non-equal objects are not equals() and have different hashCode() + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java new file mode 100644 index 0000000000..feb04d65ff --- /dev/null +++ b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java @@ -0,0 +1,24 @@ +package org.baeldung.equalshashcode.entities; + +import org.junit.Assert; +import org.junit.Test; + +public class PrimitiveClassTest { + + @Test + public void testTwoEqualsObjects() { + + PrimitiveClass aObject = new PrimitiveClass(false, 2); + PrimitiveClass bObject = new PrimitiveClass(false, 2); + PrimitiveClass dObject = new PrimitiveClass(true, 2); + + // equals() + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + // hashCode() + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + // non-equal objects are not equals() and have different hashCode() + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java new file mode 100644 index 0000000000..53ca199405 --- /dev/null +++ b/eclipse/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java @@ -0,0 +1,27 @@ +package org.baeldung.equalshashcode.entities; + +import java.awt.Color; + +import org.junit.Assert; +import org.junit.Test; + +public class SquareClassTest { + + @Test + public void testEqualsAndHashcodes() { + + Square aObject = new Square(10, Color.BLUE); + Square bObject = new Square(10, Color.BLUE); + + Square dObject = new Square(20, Color.BLUE); + + // equals() + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + // hashCode() + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + // non-equal objects are not equals() and have different hashCode() + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/elasticsearch/README.md b/elasticsearch/README.md new file mode 100644 index 0000000000..e21070dbee --- /dev/null +++ b/elasticsearch/README.md @@ -0,0 +1,6 @@ +========= + +## ElasticSearch + +### Relevant Articles: +- [A Guide to ElasticSearch](http://www.baeldung.com/????????) diff --git a/elasticsearch/pom.xml b/elasticsearch/pom.xml new file mode 100644 index 0000000000..c12f258b98 --- /dev/null +++ b/elasticsearch/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + + com.baeldung + elasticsearch + 0.0.1-SNAPSHOT + jar + + elasticsearch + http://maven.apache.org + + + UTF-8 + + + + + org.elasticsearch + elasticsearch + 2.3.5 + + + com.alibaba + fastjson + 1.2.13 + + + junit + junit + 4.12 + test + + + diff --git a/elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java b/elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java new file mode 100644 index 0000000000..8f0b19a186 --- /dev/null +++ b/elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java @@ -0,0 +1,52 @@ +package com.baeldung.elasticsearch; + +import java.util.Date; + +public class Person { + + private int age; + + private String fullName; + + private Date dateOfBirth; + + public Person() { + + } + + public Person(int age, String fullName, Date dateOfBirth) { + super(); + this.age = age; + this.fullName = fullName; + this.dateOfBirth = dateOfBirth; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + @Override + public String toString() { + return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]"; + } +} diff --git a/elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java new file mode 100644 index 0000000000..a5f103c005 --- /dev/null +++ b/elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -0,0 +1,130 @@ +package com.baeldung.elasticsearch; + +import static org.elasticsearch.node.NodeBuilder.*; +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.search.SearchType; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.node.Node; +import org.elasticsearch.search.SearchHit; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; + +public class ElasticSearchUnitTests { + private List listOfPersons = new ArrayList(); + String jsonString = null; + Client client = null; + + @Before + public void setUp() { + Person person1 = new Person(10, "John Doe", new Date()); + Person person2 = new Person(25, "Janette Doe", new Date()); + listOfPersons.add(person1); + listOfPersons.add(person2); + jsonString = JSON.toJSONString(listOfPersons); + Node node = nodeBuilder().clusterName("elasticsearch").client(true).node(); + client = node.client(); + } + + @Test + public void givenJsonString_whenJavaObject_thenIndexDocument() { + String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; + IndexResponse response = client.prepareIndex("people", "Doe") + .setSource(jsonObject).get(); + String index = response.getIndex(); + String type = response.getType(); + assertTrue(response.isCreated()); + assertEquals(index, "people"); + assertEquals(type, "Doe"); + } + + @Test + public void givenDocumentId_whenJavaObject_thenDeleteDocument() { + String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; + IndexResponse response = client.prepareIndex("people", "Doe") + .setSource(jsonObject).get(); + String id = response.getId(); + DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get(); + assertTrue(deleteResponse.isFound()); + } + + @Test + public void givenSearchRequest_whenMatchAll_thenReturnAllResults() { + SearchResponse response = client.prepareSearch().execute().actionGet(); + SearchHit[] searchHits = response.getHits().getHits(); + List results = new ArrayList(); + for (SearchHit hit : searchHits) { + String sourceAsString = hit.getSourceAsString(); + Person person = JSON.parseObject(sourceAsString, Person.class); + results.add(person); + } + } + + @Test + public void givenSearchParamters_thenReturnResults() { + boolean isExecutedSuccessfully = true; + SearchResponse response = client.prepareSearch() + .setTypes() + .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) + .setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)) + .setFrom(0).setSize(60).setExplain(true) + .execute() + .actionGet(); + + SearchResponse response2 = client.prepareSearch() + .setTypes() + .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) + .setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")) + .setFrom(0).setSize(60).setExplain(true) + .execute() + .actionGet(); + + SearchResponse response3 = client.prepareSearch() + .setTypes() + .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) + .setPostFilter(QueryBuilders.matchQuery("John", "Name*")) + .setFrom(0).setSize(60).setExplain(true) + .execute() + .actionGet(); + try { + response2.getHits(); + response3.getHits(); + SearchHit[] searchHits = response.getHits().getHits(); + List results = new ArrayList(); + for (SearchHit hit : searchHits) { + String sourceAsString = hit.getSourceAsString(); + Person person = JSON.parseObject(sourceAsString, Person.class); + results.add(person); + } + } catch (Exception e) { + isExecutedSuccessfully = false; + } + assertTrue(isExecutedSuccessfully); + } + + @Test + public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { + XContentBuilder builder = XContentFactory.jsonBuilder() + .startObject() + .field("fullName", "Test") + .field("salary", "11500") + .field("age", "10") + .endObject(); + IndexResponse response = client.prepareIndex("people", "Doe") + .setSource(builder).get(); + assertTrue(response.isCreated()); + } +} diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml new file mode 100644 index 0000000000..dbcd4f1b1d --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + front-controller-pattern + war + + + enterprise-patterns-parent + com.baeldung.enterprise.patterns + 1.0.0-SNAPSHOT + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.0.M1 + + + /front-controller + + + + + + diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java new file mode 100644 index 0000000000..4dfc12c050 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.enterprise.patterns.front.controller; + +import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; +import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FrontControllerServlet extends HttpServlet { + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(getServletContext(), request, response); + command.process(); + } + + private FrontCommand getCommand(HttpServletRequest request) { + try { + return (FrontCommand) getCommandClass(request) + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + throw new RuntimeException("Failed to get command!", e); + } + } + + private Class getCommandClass(HttpServletRequest request) { + try { + return Class.forName( + String.format( + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + request.getParameter("command") + ) + ); + } catch (ClassNotFoundException e) { + return UnknownCommand.class; + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java new file mode 100644 index 0000000000..12a008faeb --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java @@ -0,0 +1,32 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand { + protected ServletContext context; + protected HttpServletRequest request; + protected HttpServletResponse response; + + public void init( + ServletContext servletContext, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse + ) { + this.context = servletContext; + this.request = servletRequest; + this.response = servletResponse; + } + + public abstract void process() throws ServletException, IOException; + + protected void forward(String target) throws ServletException, IOException { + target = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = context.getRequestDispatcher(target); + dispatcher.forward(request, response); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java new file mode 100644 index 0000000000..0c5bd64bbc --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java @@ -0,0 +1,21 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import com.baeldung.enterprise.patterns.front.controller.data.Book; +import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class SearchCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + Book book = new BookshelfImpl().getInstance() + .findByTitle(request.getParameter("title")); + if (book != null) { + request.setAttribute("book", book); + forward("book-found"); + } else { + forward("book-notfound"); + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java new file mode 100644 index 0000000000..90103c8f42 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java @@ -0,0 +1,11 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + forward("unknown"); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..634e05c3a0 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public class Book { + private String author; + private String title; + private Double price; + + public Book() { + } + + public Book(String author, String title, Double price) { + this.author = author; + this.title = title; + this.price = price; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..524e000bd9 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,15 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public interface Bookshelf { + + default void init() { + add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + Bookshelf getInstance(); + + boolean add(E book); + + Book findByTitle(String title); +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java new file mode 100644 index 0000000000..3862418857 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java @@ -0,0 +1,24 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +import java.util.ArrayList; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + private static Bookshelf INSTANCE; + + @Override + public Bookshelf getInstance() { + if (INSTANCE == null) { + INSTANCE = new BookshelfImpl(); + INSTANCE.init(); + } + return INSTANCE; + } + + @Override + public Book findByTitle(String title) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) + .findFirst() + .orElse(null); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png new file mode 100644 index 0000000000..bd475bf3f3 Binary files /dev/null and b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png differ diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml new file mode 100644 index 0000000000..fbd4f416ef --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml + +class Handler { +doGet +doPost +} + +abstract class AbstractCommand { +process +} +class ConcreteCommand1 { +process +} +class ConcreteCommand2 { +process +} + +Handler .right.> AbstractCommand +AbstractCommand <|-- ConcreteCommand1 +AbstractCommand <|-- ConcreteCommand2 + +@enduml \ No newline at end of file diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..42e08b4a46 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,12 @@ + + + + Bookshelf: Title found + + +

Our Bookshelf contains this title:

+

${book.getTitle()}

+

Author: ${book.getAuthor()}

+ + + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..2f8ac01755 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -0,0 +1,10 @@ + + + + Bookshelf: Title not found + + +

Our Bookshelf doesn't contains this title:

+

${param.get("title")}

+ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..b52b2de8d5 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1,9 @@ + + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..77113db09b --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + front-controller + com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + + + front-controller + / + + diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml new file mode 100644 index 0000000000..2fba12547f --- /dev/null +++ b/enterprise-patterns/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + enterprise-patterns-parent + pom + + front-controller-pattern + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + diff --git a/feign-client/README.md b/feign-client/README.md new file mode 100644 index 0000000000..e6ade4d161 --- /dev/null +++ b/feign-client/README.md @@ -0,0 +1,5 @@ +## Feign Hypermedia Client ## + +This is the implementation of a [spring-hypermedia-api][1] client using Feign. + +[1]: https://github.com/eugenp/spring-hypermedia-api diff --git a/feign-client/pom.xml b/feign-client/pom.xml new file mode 100644 index 0000000000..af61883f1b --- /dev/null +++ b/feign-client/pom.xml @@ -0,0 +1,99 @@ + + + 4.0.0 + + com.baeldung.feign + feign-client + 1.0.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + io.github.openfeign + feign-core + 9.3.1 + + + io.github.openfeign + feign-okhttp + 9.3.1 + + + io.github.openfeign + feign-gson + 9.3.1 + + + io.github.openfeign + feign-slf4j + 9.3.1 + + + org.slf4j + slf4j-api + 1.7.21 + + + org.apache.logging.log4j + log4j-core + 2.6.2 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.6.2 + + + org.projectlombok + lombok + 1.16.10 + provided + + + junit + junit + 4.12 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + true + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java new file mode 100644 index 0000000000..9c0c359d88 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -0,0 +1,26 @@ +package com.baeldung.feign; + +import com.baeldung.feign.clients.BookClient; +import feign.Feign; +import feign.Logger; +import feign.gson.GsonDecoder; +import feign.gson.GsonEncoder; +import feign.okhttp.OkHttpClient; +import feign.slf4j.Slf4jLogger; +import lombok.Getter; + +@Getter +public class BookControllerFeignClientBuilder { + private BookClient bookClient = createClient(BookClient.class, + "http://localhost:8081/api/books"); + + private static T createClient(Class type, String uri) { + return Feign.builder() + .client(new OkHttpClient()) + .encoder(new GsonEncoder()) + .decoder(new GsonDecoder()) + .logger(new Slf4jLogger(type)) + .logLevel(Logger.Level.FULL) + .target(type, uri); + } +} diff --git a/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java b/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java new file mode 100644 index 0000000000..df20ef8f93 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java @@ -0,0 +1,21 @@ +package com.baeldung.feign.clients; + +import com.baeldung.feign.models.Book; +import com.baeldung.feign.models.BookResource; +import feign.Headers; +import feign.Param; +import feign.RequestLine; + +import java.util.List; + +public interface BookClient { + @RequestLine("GET /{isbn}") + BookResource findByIsbn(@Param("isbn") String isbn); + + @RequestLine("GET") + List findAll(); + + @RequestLine("POST") + @Headers("Content-Type: application/json") + void create(Book book); +} diff --git a/feign-client/src/main/java/com/baeldung/feign/models/Book.java b/feign-client/src/main/java/com/baeldung/feign/models/Book.java new file mode 100644 index 0000000000..cda4412e27 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/models/Book.java @@ -0,0 +1,18 @@ +package com.baeldung.feign.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class Book { + private String isbn; + private String author; + private String title; + private String synopsis; + private String language; +} diff --git a/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java b/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java new file mode 100644 index 0000000000..7902db9fe8 --- /dev/null +++ b/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java @@ -0,0 +1,14 @@ +package com.baeldung.feign.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class BookResource { + private Book book; +} diff --git a/feign-client/src/main/resources/log4j2.xml b/feign-client/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..659c5fda0e --- /dev/null +++ b/feign-client/src/main/resources/log4j2.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java new file mode 100644 index 0000000000..e7e058a336 --- /dev/null +++ b/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java @@ -0,0 +1,58 @@ +package com.baeldung.feign.clients; + +import com.baeldung.feign.BookControllerFeignClientBuilder; +import com.baeldung.feign.models.Book; +import com.baeldung.feign.models.BookResource; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@Slf4j +@RunWith(JUnit4.class) +public class BookClientTest { + private BookClient bookClient; + + @Before + public void setup() { + BookControllerFeignClientBuilder feignClientBuilder = new BookControllerFeignClientBuilder(); + bookClient = feignClientBuilder.getBookClient(); + } + + @Test + public void givenBookClient_shouldRunSuccessfully() throws Exception { + List books = bookClient.findAll().stream() + .map(BookResource::getBook) + .collect(Collectors.toList()); + assertTrue(books.size() > 2); + log.info("{}", books); + } + + @Test + public void givenBookClient_shouldFindOneBook() throws Exception { + Book book = bookClient.findByIsbn("0151072558").getBook(); + assertThat(book.getAuthor(), containsString("Orwell")); + log.info("{}", book); + } + + @Test + public void givenBookClient_shouldPostBook() throws Exception { + String isbn = UUID.randomUUID().toString(); + Book book = new Book(isbn, "Me", "It's me!", null, null); + bookClient.create(book); + + book = bookClient.findByIsbn(isbn).getBook(); + assertThat(book.getAuthor(), is("Me")); + log.info("{}", book); + } +} diff --git a/flyway-migration/.gitignore b/flyway-migration/.gitignore new file mode 100644 index 0000000000..abffe04ed2 --- /dev/null +++ b/flyway-migration/.gitignore @@ -0,0 +1,4 @@ +.classpath +.project +.settings +target/ \ No newline at end of file diff --git a/flyway-migration/db/migration/V1_0__create_employee_schema.sql b/flyway-migration/db/migration/V1_0__create_employee_schema.sql new file mode 100644 index 0000000000..09408faecb --- /dev/null +++ b/flyway-migration/db/migration/V1_0__create_employee_schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS `employee` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20), +`email` varchar(50), +`date_of_birth` timestamp + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; \ No newline at end of file diff --git a/flyway-migration/db/migration/V2_0__create_department_schema.sql b/flyway-migration/db/migration/V2_0__create_department_schema.sql new file mode 100644 index 0000000000..2b9d3364a5 --- /dev/null +++ b/flyway-migration/db/migration/V2_0__create_department_schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS `department` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20) + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; + +ALTER TABLE `employee` ADD `dept_id` int AFTER `email`; \ No newline at end of file diff --git a/flyway-migration/myFlywayConfig.properties b/flyway-migration/myFlywayConfig.properties new file mode 100644 index 0000000000..22f3afefd3 --- /dev/null +++ b/flyway-migration/myFlywayConfig.properties @@ -0,0 +1,5 @@ +flyway.user=root +flyway.password=mysql +flyway.schemas=app-db +flyway.url=jdbc:mysql://localhost:3306/ +flyway.locations=filesystem:db/migration \ No newline at end of file diff --git a/flyway-migration/pom.xml b/flyway-migration/pom.xml new file mode 100644 index 0000000000..6e9d683a0e --- /dev/null +++ b/flyway-migration/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + com.baeldung + flyway-migration + 1.0 + flyway-migration + A sample project to demonstrate Flyway migrations + + + mysql + mysql-connector-java + 6.0.3 + + + + + + org.flywaydb + flyway-maven-plugin + 4.0.3 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file 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 function; + private WeakHashMap cache; + private Set> entries; + private Function function; - public GuavaMapFromSet( Set keys, Function function) { - this.function = function; - this.cache = new WeakHashMap(); - this.entries = new MyEntrySet(keys); - } + public GuavaMapFromSet(Set keys, Function 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/.gitignore b/hystrix/.gitignore new file mode 100644 index 0000000000..b092c8122f --- /dev/null +++ b/hystrix/.gitignore @@ -0,0 +1,12 @@ +*.class + +#folders# +/target +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear +*.iml \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 0ec5fa0411..42828e1c97 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -6,16 +6,22 @@ com.baeldung hystrix 1.0 - hystrix + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + 1.8 - 1.4.10 + 1.5.4 0.20.7 @@ -27,41 +33,76 @@ 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 + ${hystrix-metrics-event-stream.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 + + + org.springframework.boot + spring-boot-maven-plugin + org.apache.maven.plugins maven-compiler-plugin diff --git a/hystrix/src/main/java/com/baeldung/hystrix/AppConfig.java b/hystrix/src/main/java/com/baeldung/hystrix/AppConfig.java new file mode 100644 index 0000000000..8b11ac99c3 --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/AppConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class AppConfig { + + public static void main(String[] args) { + SpringApplication.run(AppConfig.class, args); + } + + @Bean + public ServletRegistrationBean adminServletRegistrationBean() { + return new ServletRegistrationBean(new HystrixMetricsStreamServlet(), "/hystrix.stream"); + } +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/CommandHelloWorld.java b/hystrix/src/main/java/com/baeldung/hystrix/CommandHelloWorld.java similarity index 100% rename from hystrix/src/test/java/com/baeldung/hystrix/CommandHelloWorld.java rename to hystrix/src/main/java/com/baeldung/hystrix/CommandHelloWorld.java diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java new file mode 100644 index 0000000000..3a650c2f4f --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixAspect.java @@ -0,0 +1,83 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.*; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +@Aspect +public class HystrixAspect { + + private HystrixCommand.Setter config; + 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(); + } + + @PostConstruct + private void setup() { + this.config = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey)); + this.config = config.andCommandKey(HystrixCommandKey.Factory.asKey(key)); + + this.commandProperties = HystrixCommandProperties.Setter(); + this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout); + this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow); + + this.threadPoolProperties = HystrixThreadPoolProperties.Setter(); + this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount); + + this.config.andCommandPropertiesDefaults(commandProperties); + this.config.andThreadPoolPropertiesDefaults(threadPoolProperties); + } + + private static class RemoteServiceCommand extends HystrixCommand { + + private final ProceedingJoinPoint joinPoint; + + RemoteServiceCommand(final Setter config, final ProceedingJoinPoint joinPoint) { + super(config); + this.joinPoint = joinPoint; + } + + @Override + protected String run() throws Exception { + try { + return (String) joinPoint.proceed(); + } catch (final Throwable th) { + throw new Exception(th); + } + + } + } + +} diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixCircuitBreaker.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixCircuitBreaker.java new file mode 100644 index 0000000000..e7c0694a7b --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixCircuitBreaker.java @@ -0,0 +1,11 @@ +package com.baeldung.hystrix; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface HystrixCircuitBreaker { +} diff --git a/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java new file mode 100644 index 0000000000..69d9e30ff8 --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/HystrixController.java @@ -0,0 +1,22 @@ +package com.baeldung.hystrix; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HystrixController { + + @Autowired + private SpringExistingClient client; + + @RequestMapping("/withHystrix") + public String withHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithHystrix(); + } + + @RequestMapping("/withOutHystrix") + public String withOutHystrix() throws InterruptedException{ + return client.invokeRemoteServiceWithOutHystrix(); + } +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestCommand.java b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceTestCommand.java similarity index 100% rename from hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestCommand.java rename to hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceTestCommand.java diff --git a/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java similarity index 86% rename from hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java rename to hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java index 54c626a67a..d302166ea8 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java +++ b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java @@ -1,7 +1,7 @@ package com.baeldung.hystrix; -class RemoteServiceTestSimulator { +public class RemoteServiceTestSimulator { private long wait; diff --git a/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java new file mode 100644 index 0000000000..525c7b4785 --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/SpringExistingClient.java @@ -0,0 +1,20 @@ +package com.baeldung.hystrix; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component("springClient") +public class SpringExistingClient { + + @Value("${remoteservice.timeout}") + private int remoteServiceDelay; + + @HystrixCircuitBreaker + public String invokeRemoteServiceWithHystrix() throws InterruptedException{ + return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); + } + + public String invokeRemoteServiceWithOutHystrix() throws InterruptedException{ + return new RemoteServiceTestSimulator(remoteServiceDelay).execute(); + } +} diff --git a/hystrix/src/main/resources/application.properties b/hystrix/src/main/resources/application.properties new file mode 100644 index 0000000000..50c241d03f --- /dev/null +++ b/hystrix/src/main/resources/application.properties @@ -0,0 +1,8 @@ +remoteservice.command.group.key=RemoteServiceGroup +remoteservice.command.key=RemoteServiceKey +remoteservice.command.execution.timeout=10000 +remoteservice.command.threadpool.coresize=5 +remoteservice.command.threadpool.maxsize=10 +remoteservice.command.task.queue.size=5 +remoteservice.command.sleepwindow=5000 +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 773c76536f..d72895aab9 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -1,62 +1,132 @@ 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 static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class HystrixTimeoutTest { - private static HystrixCommand.Setter config; - private static HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); - - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Before - public void setup() { - config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); - } - @Test - public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){ + public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){ assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @Test - public void givenTimeoutEqualTo100_andDefaultSettings_thenReturnSuccess() throws InterruptedException { - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success")); + public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess() + throws InterruptedException { + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2")); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), + equalTo("Success")); } - @Test - public void givenTimeoutEqualTo10000_andDefaultSettings_thenExpectHystrixRuntimeException() throws InterruptedException { - exception.expect(HystrixRuntimeException.class); + @Test(expected = HystrixRuntimeException.class) + public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException { + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3")); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); } @Test - public void givenTimeoutEqualTo5000_andExecutionTimeoutEqualTo10000_thenReturnSuccess() throws InterruptedException { + public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); - assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(5_000)).execute(), equalTo("Success")); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); } - @Test - public void givenTimeoutEqualTo15000_andExecutionTimeoutEqualTo10000_thenExpectHystrixRuntimeException() throws InterruptedException { - exception.expect(HystrixRuntimeException.class); - commandProperties.withExecutionTimeoutInMilliseconds(10_000); + @Test(expected = HystrixRuntimeException.class) + public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() + throws InterruptedException { + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); + commandProperties.withExecutionTimeoutInMilliseconds(5_000); config.andCommandPropertiesDefaults(commandProperties); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute(); } + @Test + public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool")); + HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); + commandProperties.withExecutionTimeoutInMilliseconds(10_000); + config.andCommandPropertiesDefaults(commandProperties); + config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() + .withMaxQueueSize(10) + .withCoreSize(3) + .withQueueSizeRejectionThreshold(10)); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + } + + @Test + public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() + throws InterruptedException { + + HystrixCommand.Setter config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker")); + HystrixCommandProperties.Setter properties = HystrixCommandProperties.Setter(); + properties.withExecutionTimeoutInMilliseconds(1000); + + properties.withCircuitBreakerSleepWindowInMilliseconds(4000); + properties.withExecutionIsolationStrategy( + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + properties.withCircuitBreakerEnabled(true); + properties.withCircuitBreakerRequestVolumeThreshold(1); + + config.andCommandPropertiesDefaults(properties); + + config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() + .withMaxQueueSize(1) + .withCoreSize(1) + .withQueueSizeRejectionThreshold(1)); + + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); + Thread.sleep(5000); + + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), + equalTo("Success")); + } + + public String invokeRemoteService(HystrixCommand.Setter config, int timeout) + throws InterruptedException { + String response = null; + try { + response = new RemoteServiceTestCommand(config, + new RemoteServiceTestSimulator(timeout)).execute(); + } catch (HystrixRuntimeException ex) { + System.out.println("ex = " + ex); + } + return response; + } } diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java new file mode 100644 index 0000000000..004314b0ed --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppConfig.class) +public class SpringAndHystrixIntegrationTest { + + @Autowired + private HystrixController hystrixController; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void givenTimeOutOf15000_whenClientCalledWithHystrix_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + hystrixController.withHystrix(); + } + + @Test + public void givenTimeOutOf15000_whenClientCalledWithOutHystrix_thenExpectSuccess() throws InterruptedException { + assertThat(hystrixController.withOutHystrix(), equalTo("Success")); + } + +} diff --git a/immutables/pom.xml b/immutables/pom.xml new file mode 100644 index 0000000000..2b4aba59b1 --- /dev/null +++ b/immutables/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.baeldung + immutables + 1.0.0-SNAPSHOT + + + + org.immutables + value + 2.2.10 + + + junit + junit + 4.12 + test + + + org.assertj + assertj-core + 3.5.2 + test + + + org.mutabilitydetector + MutabilityDetector + 0.9.5 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/Address.java b/immutables/src/main/java/com/baeldung/immutable/Address.java new file mode 100644 index 0000000000..93474dc043 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/Address.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable; + +import org.immutables.value.Value; + +@Value.Immutable +public interface Address { + String getStreetName(); + Integer getNumber(); +} diff --git a/immutables/src/main/java/com/baeldung/immutable/Person.java b/immutables/src/main/java/com/baeldung/immutable/Person.java new file mode 100644 index 0000000000..466daf42c2 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable; + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); +} diff --git a/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java b/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java new file mode 100644 index 0000000000..78fe28c50c --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java @@ -0,0 +1,13 @@ +package com.baeldung.immutable.auxiliary; + + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); + + @Value.Auxiliary + abstract String getAuxiliaryField(); +} \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/default_/Person.java b/immutables/src/main/java/com/baeldung/immutable/default_/Person.java new file mode 100644 index 0000000000..bc48f11a38 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/default_/Person.java @@ -0,0 +1,14 @@ +package com.baeldung.immutable.default_; + +import org.immutables.value.Value; + +@Value.Immutable(prehash = true) +public abstract class Person { + + abstract String getName(); + + @Value.Default + Integer getAge() { + return 42; + } +} diff --git a/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java b/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java new file mode 100644 index 0000000000..4e8218f99c --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java @@ -0,0 +1,14 @@ +package com.baeldung.immutable.parameter; + + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + + @Value.Parameter + abstract String getName(); + + @Value.Parameter + abstract Integer getAge(); +} \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java b/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java new file mode 100644 index 0000000000..5e5dd4d9e9 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable.prehash; + +import org.immutables.value.Value; + +@Value.Immutable(prehash = true) +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); +} diff --git a/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java b/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java new file mode 100644 index 0000000000..bf075569db --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java @@ -0,0 +1,27 @@ +package com.baeldung.immutable; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable; + +public class ImmutablePersonTest { + + @Test + public void whenModifying_shouldCreateNewInstance() throws Exception { + final ImmutablePerson john = ImmutablePerson.builder() + .age(42) + .name("John") + .build(); + + final ImmutablePerson john43 = john.withAge(43); + + assertThat(john) + .isNotSameAs(john43); + + assertThat(john.getAge()) + .isEqualTo(42); + + assertImmutable(ImmutablePerson.class); + } +} \ No newline at end of file diff --git a/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java b/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java new file mode 100644 index 0000000000..83f9e51ed5 --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java @@ -0,0 +1,33 @@ +package com.baeldung.immutable.auxiliary; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ImmutablePersonAuxiliaryTest { + + @Test + public void whenComparing_shouldIgnore() throws Exception { + final ImmutablePerson john1 = ImmutablePerson.builder() + .name("John") + .age(42) + .auxiliaryField("Value1") + .build(); + + final ImmutablePerson john2 = ImmutablePerson.builder() + .name("John") + .age(42) + .auxiliaryField("Value2") + .build(); + + + assertThat(john1.equals(john2)) + .isTrue(); + + assertThat(john1.toString()) + .isEqualTo(john2.toString()); + + assertThat(john1.hashCode()) + .isEqualTo(john2.hashCode()); + } +} \ No newline at end of file diff --git a/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java b/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java new file mode 100644 index 0000000000..5cf4ac0cf7 --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java @@ -0,0 +1,17 @@ +package com.baeldung.immutable.default_; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ImmutablePersonDefaultTest { + + @Test + public void whenInstantiating_shouldUseDefaultValue() throws Exception { + + final ImmutablePerson john = ImmutablePerson.builder().name("John").build(); + + assertThat(john.getAge()).isEqualTo(42); + + } +} \ No newline at end of file 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/java-cassandra/pom.xml b/java-cassandra/pom.xml new file mode 100644 index 0000000000..265a230eb4 --- /dev/null +++ b/java-cassandra/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + com.baeldung + cassandra-java-client + 1.0.0-SNAPSHOT + + cassandra-java-client + + + UTF-8 + + + 1.7.21 + 1.1.7 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + + 3.5.1 + + + 3.1.0 + + + + + + com.datastax.cassandra + cassandra-driver-core + ${cassandra-driver-core.version} + true + + + + + org.cassandraunit + cassandra-unit + 3.0.0.1 + + + + + com.google.guava + guava + 19.0 + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + junit + junit + ${junit.version} + test + + + + + java-cassandra + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java new file mode 100644 index 0000000000..c67a2c2ddb --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java @@ -0,0 +1,44 @@ +package com.baeldung.cassandra.java.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.cassandra.java.client.domain.Book; +import com.baeldung.cassandra.java.client.repository.BookRepository; +import com.baeldung.cassandra.java.client.repository.KeyspaceRepository; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; + +public class CassandraClient { + private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class); + + public static void main(String args[]) { + CassandraConnector connector = new CassandraConnector(); + connector.connect("127.0.0.1", null); + Session session = connector.getSession(); + + KeyspaceRepository sr = new KeyspaceRepository(session); + sr.createKeyspace("library", "SimpleStrategy", 1); + sr.useKeyspace("library"); + + BookRepository br = new BookRepository(session); + br.createTable(); + br.alterTablebooks("publisher", "text"); + + br.createTableBooksByTitle(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + br.insertBookBatch(book); + + br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle())); + br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle())); + + br.deletebookByTitle("Effective Java"); + br.deleteTable("books"); + br.deleteTable("booksByTitle"); + + sr.deleteKeyspace("library"); + + connector.close(); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java new file mode 100644 index 0000000000..e035335ca0 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java @@ -0,0 +1,51 @@ +package com.baeldung.cassandra.java.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Cluster.Builder; +import com.datastax.driver.core.Host; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.Session; + +/** + * + * This is an implementation of a simple Java client. + * + */ +public class CassandraConnector { + private static final Logger LOG = LoggerFactory.getLogger(CassandraConnector.class); + + private Cluster cluster; + + private Session session; + + public void connect(final String node, final Integer port) { + + Builder b = Cluster.builder().addContactPoint(node); + + if (port != null) { + b.withPort(port); + } + cluster = b.build(); + + Metadata metadata = cluster.getMetadata(); + LOG.info("Cluster name: " + metadata.getClusterName()); + + for (Host host : metadata.getAllHosts()) { + LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack()); + } + + session = cluster.connect(); + } + + public Session getSession() { + return this.session; + } + + public void close() { + session.close(); + cluster.close(); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java new file mode 100644 index 0000000000..e6c7753eb3 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java @@ -0,0 +1,66 @@ +package com.baeldung.cassandra.java.client.domain; + +import java.util.UUID; + +public class Book { + + private UUID id; + + private String title; + + private String author; + + private String subject; + + private String publisher; + + Book() { + } + + public Book(UUID id, String title, String author, String subject) { + this.id = id; + this.title = title; + this.author = author; + this.subject = subject; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java new file mode 100644 index 0000000000..31e2969e01 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java @@ -0,0 +1,177 @@ +package com.baeldung.cassandra.java.client.repository; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.cassandra.java.client.domain.Book; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; + +public class BookRepository { + + private static final String TABLE_NAME = "books"; + + private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle"; + + private Session session; + + public BookRepository(Session session) { + this.session = session; + } + + /** + * Creates the books table. + */ + public void createTable() { + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME).append("(").append("id uuid PRIMARY KEY, ").append("title text,").append("author text,").append("subject text);"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Creates the books table. + */ + public void createTableBooksByTitle() { + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME_BY_TITLE).append("(").append("id uuid, ").append("title text,").append("PRIMARY KEY (title, id));"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Alters the table books and adds an extra column. + */ + public void alterTablebooks(String columnName, String columnType) { + StringBuilder sb = new StringBuilder("ALTER TABLE ").append(TABLE_NAME).append(" ADD ").append(columnName).append(" ").append(columnType).append(";"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a row in the table books. + * + * @param book + */ + public void insertbook(Book book) { + StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '") + .append(book.getSubject()).append("');"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a row in the table booksByTitle. + * @param book + */ + public void insertbookByTitle(Book book) { + StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Insert a book into two identical tables using a batch query. + * + * @param book + */ + public void insertBookBatch(Book book) { + StringBuilder sb = new StringBuilder("BEGIN BATCH ") + .append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ") + .append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '") + .append(book.getSubject()).append("');") + .append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ") + .append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');") + .append("APPLY BATCH;"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Select book by id. + * + * @return + */ + public Book selectByTitle(String title) { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';"); + + final String query = sb.toString(); + + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book s = new Book(r.getUUID("id"), r.getString("title"), null, null); + books.add(s); + } + + return books.get(0); + } + + /** + * Select all books from books + * + * @return + */ + public List selectAll() { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); + + final String query = sb.toString(); + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book book = new Book(r.getUUID("id"), r.getString("title"), r.getString("author"), r.getString("subject")); + books.add(book); + } + return books; + } + + /** + * Select all books from booksByTitle + * @return + */ + public List selectAllBookByTitle() { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE); + + final String query = sb.toString(); + ResultSet rs = session.execute(query); + + List books = new ArrayList(); + + for (Row r : rs) { + Book book = new Book(r.getUUID("id"), r.getString("title"), null, null); + books.add(book); + } + return books; + } + + /** + * Delete a book by title. + */ + public void deletebookByTitle(String title) { + StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';"); + + final String query = sb.toString(); + session.execute(query); + } + + /** + * Delete table. + * + * @param tableName the name of the table to delete. + */ + public void deleteTable(String tableName) { + StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(tableName); + + final String query = sb.toString(); + session.execute(query); + } +} diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java new file mode 100644 index 0000000000..f15558f040 --- /dev/null +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.cassandra.java.client.repository; + +import com.datastax.driver.core.Session; + +/** + * Repository to handle the Cassandra schema. + * + */ +public class KeyspaceRepository { + private Session session; + + public KeyspaceRepository(Session session) { + this.session = session; + } + + /** + * Method used to create any keyspace - schema. + * + * @param schemaName the name of the schema. + * @param replicatioonStrategy the replication strategy. + * @param numberOfReplicas the number of replicas. + * + */ + public void createKeyspace(String keyspaceName, String replicatioonStrategy, int numberOfReplicas) { + StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ").append(keyspaceName).append(" WITH replication = {").append("'class':'").append(replicatioonStrategy).append("','replication_factor':").append(numberOfReplicas).append("};"); + + final String query = sb.toString(); + + session.execute(query); + } + + public void useKeyspace(String keyspace) { + session.execute("USE " + keyspace); + } + + /** + * Method used to delete the specified schema. + * It results in the immediate, irreversable removal of the keyspace, including all tables and data contained in the keyspace. + * + * @param schemaName the name of the keyspace to delete. + */ + public void deleteKeyspace(String keyspaceName) { + StringBuilder sb = new StringBuilder("DROP KEYSPACE ").append(keyspaceName); + + final String query = sb.toString(); + + session.execute(query); + } +} diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..62eae94c7c --- /dev/null +++ b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,174 @@ +package com.baeldung.cassandra.java.client.repository; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.cassandra.java.client.CassandraConnector; +import com.baeldung.cassandra.java.client.domain.Book; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.core.utils.UUIDs; + +public class BookRepositoryIntegrationTest { + + private KeyspaceRepository schemaRepository; + + private BookRepository bookRepository; + + private Session session; + + final String KEYSPACE_NAME = "testLibrary"; + final String BOOKS = "books"; + final String BOOKS_BY_TITLE = "booksByTitle"; + + @BeforeClass + public static void init() throws ConfigurationException, TTransportException, IOException, InterruptedException { + // Start an embedded Cassandra Server + EmbeddedCassandraServerHelper.startEmbeddedCassandra(20000L); + } + + @Before + public void connect() { + CassandraConnector client = new CassandraConnector(); + client.connect("127.0.0.1", 9142); + this.session = client.getSession(); + schemaRepository = new KeyspaceRepository(session); + schemaRepository.createKeyspace(KEYSPACE_NAME, "SimpleStrategy", 1); + schemaRepository.useKeyspace(KEYSPACE_NAME); + bookRepository = new BookRepository(session); + } + + @Test + public void whenCreatingATable_thenCreatedCorrectly() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + ResultSet result = session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + + // Collect all the column names in one list. + List columnNames = result.getColumnDefinitions().asList().stream().map(cl -> cl.getName()).collect(Collectors.toList()); + assertEquals(columnNames.size(), 4); + assertTrue(columnNames.contains("id")); + assertTrue(columnNames.contains("title")); + assertTrue(columnNames.contains("author")); + assertTrue(columnNames.contains("subject")); + } + + @Test + public void whenAlteringTable_thenAddedColumnExists() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + bookRepository.alterTablebooks("publisher", "text"); + + ResultSet result = session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + + boolean columnExists = result.getColumnDefinitions().asList().stream().anyMatch(cl -> cl.getName().equals("publisher")); + assertTrue(columnExists); + } + + @Test + public void whenAddingANewBook_thenBookExists() { + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + String title = "Effective Java"; + String author = "Joshua Bloch"; + Book book = new Book(UUIDs.timeBased(), title, author, "Programming"); + bookRepository.insertbookByTitle(book); + + Book savedBook = bookRepository.selectByTitle(title); + assertEquals(book.getTitle(), savedBook.getTitle()); + } + + @Test + public void whenAddingANewBookBatch_ThenBookAddedInAllTables() { + // Create table books + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + // Create table booksByTitle + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + String title = "Effective Java"; + String author = "Joshua Bloch"; + Book book = new Book(UUIDs.timeBased(), title, author, "Programming"); + bookRepository.insertBookBatch(book); + + List books = bookRepository.selectAll(); + + assertEquals(1, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + + List booksByTitle = bookRepository.selectAllBookByTitle(); + + assertEquals(1, booksByTitle.size()); + assertTrue(booksByTitle.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + } + + @Test + public void whenSelectingAll_thenReturnAllRecords() { + bookRepository.deleteTable(BOOKS); + bookRepository.createTable(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + bookRepository.insertbook(book); + + book = new Book(UUIDs.timeBased(), "Clean Code", "Robert C. Martin", "Programming"); + bookRepository.insertbook(book); + + List books = bookRepository.selectAll(); + + assertEquals(2, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Clean Code"))); + } + + @Test + public void whenDeletingABookByTitle_thenBookIsDeleted() { + bookRepository.deleteTable(BOOKS_BY_TITLE); + bookRepository.createTableBooksByTitle(); + + Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); + bookRepository.insertbookByTitle(book); + + book = new Book(UUIDs.timeBased(), "Clean Code", "Robert C. Martin", "Programming"); + bookRepository.insertbookByTitle(book); + + bookRepository.deletebookByTitle("Clean Code"); + + List books = bookRepository.selectAllBookByTitle(); + assertEquals(1, books.size()); + assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java"))); + assertFalse(books.stream().anyMatch(b -> b.getTitle().equals("Clean Code"))); + + } + + @Test(expected = InvalidQueryException.class) + public void whenDeletingATable_thenUnconfiguredTable() { + bookRepository.createTable(); + bookRepository.deleteTable(BOOKS); + + session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";"); + } + + @AfterClass + public static void cleanup() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9df46b3176 --- /dev/null +++ b/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.cassandra.java.client.repository; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.baeldung.cassandra.java.client.CassandraConnector; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class KeyspaceRepositoryIntegrationTest { + + private KeyspaceRepository schemaRepository; + + private Session session; + + @BeforeClass + public static void init() throws ConfigurationException, TTransportException, IOException, InterruptedException { + // Start an embedded Cassandra Server + EmbeddedCassandraServerHelper.startEmbeddedCassandra(20000L); + } + + @Before + public void connect() { + CassandraConnector client = new CassandraConnector(); + client.connect("127.0.0.1", 9142); + this.session = client.getSession(); + schemaRepository = new KeyspaceRepository(session); + } + + @Test + public void whenCreatingAKeyspace_thenCreated() { + String keyspaceName = "testBaeldungKeyspace"; + schemaRepository.createKeyspace(keyspaceName, "SimpleStrategy", 1); + + // ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = 'testBaeldungKeyspace';"); + + ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces;"); + + // Check if the Keyspace exists in the returned keyspaces. + List matchedKeyspaces = result.all().stream().filter(r -> r.getString(0).equals(keyspaceName.toLowerCase())).map(r -> r.getString(0)).collect(Collectors.toList()); + assertEquals(matchedKeyspaces.size(), 1); + assertTrue(matchedKeyspaces.get(0).equals(keyspaceName.toLowerCase())); + } + + @Test + public void whenDeletingAKeyspace_thenDoesNotExist() { + String keyspaceName = "testBaeldungKeyspace"; + + // schemaRepository.createKeyspace(keyspaceName, "SimpleStrategy", 1); + schemaRepository.deleteKeyspace(keyspaceName); + + ResultSet result = session.execute("SELECT * FROM system_schema.keyspaces;"); + boolean isKeyspaceCreated = result.all().stream().anyMatch(r -> r.getString(0).equals(keyspaceName.toLowerCase())); + assertFalse(isKeyspaceCreated); + } + + @AfterClass + public static void cleanup() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} 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..4159ef35c9 --- /dev/null +++ b/mapstruct/pom.xml @@ -0,0 +1,60 @@ + + + 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 + + + org.springframework + spring-context + 4.3.2.RELEASE + + + org.springframework + spring-test + 4.3.2.RELEASE + 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/com/baeldung/dto/DivisionDTO.java b/mapstruct/src/main/java/com/baeldung/dto/DivisionDTO.java new file mode 100644 index 0000000000..37f8bd111b --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/dto/DivisionDTO.java @@ -0,0 +1,33 @@ +package com.baeldung.dto; + +public class DivisionDTO { + + public DivisionDTO() { + } + + public DivisionDTO(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/com/baeldung/dto/EmployeeDTO.java b/mapstruct/src/main/java/com/baeldung/dto/EmployeeDTO.java new file mode 100644 index 0000000000..5da3165683 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/dto/EmployeeDTO.java @@ -0,0 +1,42 @@ +package com.baeldung.dto; + +public class EmployeeDTO { + + private int employeeId; + private String employeeName; + private DivisionDTO division; + private String employeeStartDt; + + 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 DivisionDTO getDivision() { + return division; + } + + public void setDivision(DivisionDTO division) { + this.division = division; + } + + public String getEmployeeStartDt() { + return employeeStartDt; + } + + public void setEmployeeStartDt(String employeeStartDt) { + this.employeeStartDt = employeeStartDt; + } + +} diff --git a/mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java b/mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java new file mode 100644 index 0000000000..ec8d80c4af --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/dto/SimpleSource.java @@ -0,0 +1,24 @@ +package com.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/com/baeldung/entity/Division.java b/mapstruct/src/main/java/com/baeldung/entity/Division.java new file mode 100644 index 0000000000..7b1416d6c5 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/Division.java @@ -0,0 +1,33 @@ +package com.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/com/baeldung/entity/Employee.java b/mapstruct/src/main/java/com/baeldung/entity/Employee.java new file mode 100644 index 0000000000..04044f4dfe --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/Employee.java @@ -0,0 +1,44 @@ +package com.baeldung.entity; + +import java.util.Date; + +public class Employee { + + private int id; + private String name; + private Division division; + private Date startDt; + + 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; + } + + public Date getStartDt() { + return startDt; + } + + public void setStartDt(Date startDt) { + this.startDt = startDt; + } + +} diff --git a/mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java b/mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java new file mode 100644 index 0000000000..d9cba1c372 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/SimpleDestination.java @@ -0,0 +1,24 @@ +package com.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/com/baeldung/mapper/EmployeeMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/EmployeeMapper.java new file mode 100644 index 0000000000..8e00103d0e --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/EmployeeMapper.java @@ -0,0 +1,30 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.DivisionDTO; +import com.baeldung.dto.EmployeeDTO; +import com.baeldung.entity.Division; +import com.baeldung.entity.Employee; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +import java.util.List; + +@Mapper +public interface EmployeeMapper { + + @Mappings({ @Mapping(target = "employeeId", source = "entity.id"), @Mapping(target = "employeeName", source = "entity.name"), @Mapping(target = "employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss") }) + EmployeeDTO employeeToEmployeeDTO(Employee entity); + + @Mappings({ @Mapping(target = "id", source = "dto.employeeId"), @Mapping(target = "name", source = "dto.employeeName"), @Mapping(target = "startDt", source = "dto.employeeStartDt", dateFormat = "dd-MM-yyyy HH:mm:ss") }) + Employee employeeDTOtoEmployee(EmployeeDTO dto); + + DivisionDTO divisionToDivisionDTO(Division entity); + + Division divisionDTOtoDivision(DivisionDTO dto); + + List convertEmployeeDTOListToEmployeeList(List list); + + List convertEmployeeListToEmployeeDTOList(List list); + +} diff --git a/mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java new file mode 100644 index 0000000000..f3f2187c20 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/SimpleSourceDestinationMapper.java @@ -0,0 +1,14 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.SimpleSource; +import com.baeldung.entity.SimpleDestination; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface SimpleSourceDestinationMapper { + + SimpleDestination sourceToDestination(SimpleSource source); + + SimpleSource destinationToSource(SimpleDestination destination); + +} diff --git a/mapstruct/src/main/resources/applicationContext.xml b/mapstruct/src/main/resources/applicationContext.xml new file mode 100644 index 0000000000..22d8d1b769 --- /dev/null +++ b/mapstruct/src/main/resources/applicationContext.xml @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java new file mode 100644 index 0000000000..7da6c41dc1 --- /dev/null +++ b/mapstruct/src/test/java/com/baeldung/mapper/EmployeeMapperTest.java @@ -0,0 +1,123 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.DivisionDTO; +import com.baeldung.dto.EmployeeDTO; +import com.baeldung.entity.Division; +import com.baeldung.entity.Employee; +import org.junit.Test; +import org.mapstruct.factory.Mappers; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class EmployeeMapperTest { + + EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); + + private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss"; + + @Test + public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() { + EmployeeDTO dto = new EmployeeDTO(); + dto.setEmployeeId(1); + dto.setEmployeeName("John"); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + + assertEquals(dto.getEmployeeId(), entity.getId()); + assertEquals(dto.getEmployeeName(), entity.getName()); + } + + @Test + public void givenEmployeewithDiffNametoEmployeeDTO_whenMaps_thenCorrect() { + Employee entity = new Employee(); + entity.setId(1); + entity.setName("John"); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + + assertEquals(dto.getEmployeeId(), entity.getId()); + assertEquals(dto.getEmployeeName(), entity.getName()); + } + + @Test + public void givenEmployeeDTOwithNestedMappingToEmployee_whenMaps_thenCorrect() { + EmployeeDTO dto = new EmployeeDTO(); + dto.setDivision(new DivisionDTO(1, "Division1")); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + + assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); + assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); + } + + @Test + public void givenEmployeeWithNestedMappingToEmployeeDTO_whenMaps_thenCorrect() { + Employee entity = new Employee(); + entity.setDivision(new Division(1, "Division1")); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + + assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); + assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); + } + + @Test + public void givenEmployeeListToEmployeeDTOList_whenMaps_thenCorrect() { + List employeeList = new ArrayList<>(); + Employee emp = new Employee(); + emp.setId(1); + emp.setName("EmpName"); + emp.setDivision(new Division(1, "Division1")); + employeeList.add(emp); + + List employeeDtoList = mapper.convertEmployeeListToEmployeeDTOList(employeeList); + EmployeeDTO employeeDTO = employeeDtoList.get(0); + assertEquals(employeeDTO.getEmployeeId(), emp.getId()); + assertEquals(employeeDTO.getEmployeeName(), emp.getName()); + assertEquals(employeeDTO.getDivision().getId(), emp.getDivision().getId()); + assertEquals(employeeDTO.getDivision().getName(), emp.getDivision().getName()); + } + + @Test + public void givenEmployeeDTOListToEmployeeList_whenMaps_thenCorrect() { + List employeeDTOList = new ArrayList<>(); + EmployeeDTO empDTO = new EmployeeDTO(); + empDTO.setEmployeeId(1); + empDTO.setEmployeeName("EmpName"); + empDTO.setDivision(new DivisionDTO(1, "Division1")); + employeeDTOList.add(empDTO); + + List employeeList = mapper.convertEmployeeDTOListToEmployeeList(employeeDTOList); + Employee employee = employeeList.get(0); + assertEquals(employee.getId(), empDTO.getEmployeeId()); + assertEquals(employee.getName(), empDTO.getEmployeeName()); + assertEquals(employee.getDivision().getId(), empDTO.getDivision().getId()); + assertEquals(employee.getDivision().getName(), empDTO.getDivision().getName()); + } + + @Test + public void givenEmployeeWithStartDateMappingToEmployeeDTO_whenMaps_thenCorrect() throws ParseException { + Employee entity = new Employee(); + entity.setStartDt(new Date()); + + EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); + SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); + assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); + } + + @Test + public void givenEmployeeDTOWithStartDateMappingToEmployee_whenMaps_thenCorrect() throws ParseException { + EmployeeDTO dto = new EmployeeDTO(); + dto.setEmployeeStartDt("01-04-2016 01:00:00"); + + Employee entity = mapper.employeeDTOtoEmployee(dto); + SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); + assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); + } +} diff --git a/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java new file mode 100644 index 0000000000..a7addf33a7 --- /dev/null +++ b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java @@ -0,0 +1,44 @@ +package com.baeldung.mapper; + +import static org.junit.Assert.assertEquals; + +import com.baeldung.dto.SimpleSource; +import com.baeldung.entity.SimpleDestination; +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext.xml") +public class SimpleSourceDestinationMapperTest { + + @Autowired + SimpleSourceDestinationMapper simpleSourceDestinationMapper; + + @Test + public void givenSimpleSourceToSimpleDestination_whenMaps_thenCorrect() { + 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() { + 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/orika/src/main/java/com/baeldung/orika/Dest.java b/orika/src/main/java/com/baeldung/orika/Dest.java new file mode 100644 index 0000000000..4f050230ce --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Dest.java @@ -0,0 +1,37 @@ +package com.baeldung.orika; + +public class Dest { + @Override + public String toString() { + return "Dest [name=" + name + ", age=" + age + "]"; + } + + private String name; + private int age; + + public Dest() { + + } + + public Dest(String name, int age) { + 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/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/orika/src/main/java/com/baeldung/orika/Person.java b/orika/src/main/java/com/baeldung/orika/Person.java new file mode 100644 index 0000000000..90ae8dee5e --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Person.java @@ -0,0 +1,48 @@ +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; + + public Person() { + + } + + public Person(String name, String nickname, int age) { + 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/orika/src/main/java/com/baeldung/orika/Person3.java b/orika/src/main/java/com/baeldung/orika/Person3.java new file mode 100644 index 0000000000..8661edfc10 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Person3.java @@ -0,0 +1,38 @@ +package com.baeldung.orika; + +public class Person3 { + private String name; + private String dtob; + + public Person3() { + + } + + public Person3(String name, String dtob) { + 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/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/orika/src/main/java/com/baeldung/orika/Personne.java b/orika/src/main/java/com/baeldung/orika/Personne.java new file mode 100644 index 0000000000..47789dd323 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Personne.java @@ -0,0 +1,44 @@ +package com.baeldung.orika; + +public class Personne { + private String nom; + private String surnom; + private int age; + + public Personne(String nom, String surnom, int age) { + 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; + } + + @Override + public String toString() { + return "Personne [nom=" + nom + ", surnom=" + surnom + ", age=" + age + + "]"; + } + +} diff --git a/orika/src/main/java/com/baeldung/orika/Personne3.java b/orika/src/main/java/com/baeldung/orika/Personne3.java new file mode 100644 index 0000000000..35323c612a --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Personne3.java @@ -0,0 +1,37 @@ +package com.baeldung.orika; + +public class Personne3 { + private String name; + private long dtob; + + public Personne3() { + + } + + public Personne3(String name, long dtob) { + 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/orika/src/main/java/com/baeldung/orika/Source.java b/orika/src/main/java/com/baeldung/orika/Source.java new file mode 100644 index 0000000000..a973bab388 --- /dev/null +++ b/orika/src/main/java/com/baeldung/orika/Source.java @@ -0,0 +1,36 @@ +package com.baeldung.orika; + +public class Source { + @Override + public String toString() { + return "Source [name=" + name + ", age=" + age + "]"; + } + + private String name; + private int age; + + public Source() { + } + + public Source(String name, int age) { + 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/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/play-framework/student-api/.gitignore b/play-framework/student-api/.gitignore new file mode 100644 index 0000000000..eb372fc719 --- /dev/null +++ b/play-framework/student-api/.gitignore @@ -0,0 +1,8 @@ +logs +target +/.idea +/.idea_modules +/.classpath +/.project +/.settings +/RUNNING_PID diff --git a/play-framework/student-api/LICENSE b/play-framework/student-api/LICENSE new file mode 100644 index 0000000000..4baedcb95f --- /dev/null +++ b/play-framework/student-api/LICENSE @@ -0,0 +1,8 @@ +This software is licensed under the Apache 2 license, quoted below. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project 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. \ No newline at end of file diff --git a/play-framework/student-api/README b/play-framework/student-api/README new file mode 100644 index 0000000000..f21d092edf --- /dev/null +++ b/play-framework/student-api/README @@ -0,0 +1,49 @@ +This is your new Play application +================================= + +This file will be packaged with your application when using `activator dist`. + +There are several demonstration files available in this template. + +Controllers +=========== + +- HomeController.java: + + Shows how to handle simple HTTP requests. + +- AsyncController.java: + + Shows how to do asynchronous programming when handling a request. + +- CountController.java: + + Shows how to inject a component into a controller and use the component when + handling requests. + +Components +========== + +- Module.java: + + Shows how to use Guice to bind all the components needed by your application. + +- Counter.java: + + An example of a component that contains state, in this case a simple counter. + +- ApplicationTimer.java: + + An example of a component that starts when the application starts and stops + when the application stops. + +Filters +======= + +- Filters.java: + + Creates the list of HTTP filters used by your application. + +- ExampleFilter.java + + A simple filter that adds a header to every response. \ No newline at end of file diff --git a/play-framework/student-api/app/Filters.java b/play-framework/student-api/app/Filters.java new file mode 100644 index 0000000000..255de8ca93 --- /dev/null +++ b/play-framework/student-api/app/Filters.java @@ -0,0 +1,46 @@ +import javax.inject.*; +import play.*; +import play.mvc.EssentialFilter; +import play.http.HttpFilters; +import play.mvc.*; + +import filters.ExampleFilter; + +/** + * This class configures filters that run on every request. This + * class is queried by Play to get a list of filters. + * + * Play will automatically use filters from any class called + * Filters that is placed the root package. You can load filters + * from a different class by adding a `play.http.filters` setting to + * the application.conf configuration file. + */ +@Singleton +public class Filters implements HttpFilters { + + private final Environment env; + private final EssentialFilter exampleFilter; + + /** + * @param env Basic environment settings for the current application. + * @param exampleFilter A demonstration filter that adds a header to + */ + @Inject + public Filters(Environment env, ExampleFilter exampleFilter) { + this.env = env; + this.exampleFilter = exampleFilter; + } + + @Override + public EssentialFilter[] filters() { + // Use the example filter if we're running development mode. If + // we're running in production or test mode then don't use any + // filters at all. + if (env.mode().equals(Mode.DEV)) { + return new EssentialFilter[] { exampleFilter }; + } else { + return new EssentialFilter[] {}; + } + } + +} diff --git a/play-framework/student-api/app/Module.java b/play-framework/student-api/app/Module.java new file mode 100644 index 0000000000..6e7d1766ef --- /dev/null +++ b/play-framework/student-api/app/Module.java @@ -0,0 +1,31 @@ +import com.google.inject.AbstractModule; +import java.time.Clock; + +import services.ApplicationTimer; +import services.AtomicCounter; +import services.Counter; + +/** + * This class is a Guice module that tells Guice how to bind several + * different types. This Guice module is created when the Play + * application starts. + * + * Play will automatically use any class called `Module` that is in + * the root package. You can create modules in other locations by + * adding `play.modules.enabled` settings to the `application.conf` + * configuration file. + */ +public class Module extends AbstractModule { + + @Override + public void configure() { + // Use the system clock as the default implementation of Clock + bind(Clock.class).toInstance(Clock.systemDefaultZone()); + // Ask Guice to create an instance of ApplicationTimer when the + // application starts. + bind(ApplicationTimer.class).asEagerSingleton(); + // Set AtomicCounter as the implementation for Counter. + bind(Counter.class).to(AtomicCounter.class); + } + +} diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/student-api/app/controllers/AsyncController.java new file mode 100644 index 0000000000..33cd112837 --- /dev/null +++ b/play-framework/student-api/app/controllers/AsyncController.java @@ -0,0 +1,60 @@ +package controllers; + +import akka.actor.ActorSystem; +import javax.inject.*; +import play.*; +import play.mvc.*; +import java.util.concurrent.Executor; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; +import scala.concurrent.duration.Duration; +import scala.concurrent.ExecutionContextExecutor; + +/** + * This controller contains an action that demonstrates how to write + * simple asynchronous code in a controller. It uses a timer to + * asynchronously delay sending a response for 1 second. + * + * @param actorSystem We need the {@link ActorSystem}'s + * {@link Scheduler} to run code after a delay. + * @param exec We need a Java {@link Executor} to apply the result + * of the {@link CompletableFuture} and a Scala + * {@link ExecutionContext} so we can use the Akka {@link Scheduler}. + * An {@link ExecutionContextExecutor} implements both interfaces. + */ +@Singleton +public class AsyncController extends Controller { + + private final ActorSystem actorSystem; + private final ExecutionContextExecutor exec; + + @Inject + public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) { + this.actorSystem = actorSystem; + this.exec = exec; + } + + /** + * An action that returns a plain text message after a delay + * of 1 second. + * + * The configuration in the routes file means that this method + * will be called when the application receives a GET request with + * a path of /message. + */ + public CompletionStage message() { + return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec); + } + + private CompletionStage getFutureMessage(long time, TimeUnit timeUnit) { + CompletableFuture future = new CompletableFuture<>(); + actorSystem.scheduler().scheduleOnce( + Duration.create(time, timeUnit), + () -> future.complete("Hi!"), + exec + ); + return future; + } + +} diff --git a/play-framework/student-api/app/controllers/CountController.java b/play-framework/student-api/app/controllers/CountController.java new file mode 100644 index 0000000000..02fcb15f8e --- /dev/null +++ b/play-framework/student-api/app/controllers/CountController.java @@ -0,0 +1,35 @@ +package controllers; + +import javax.inject.*; +import play.*; +import play.mvc.*; + +import services.Counter; + +/** + * This controller demonstrates how to use dependency injection to + * bind a component into a controller class. The class contains an + * action that shows an incrementing count to users. The {@link Counter} + * object is injected by the Guice dependency injection system. + */ +@Singleton +public class CountController extends Controller { + + private final Counter counter; + + @Inject + public CountController(Counter counter) { + this.counter = counter; + } + + /** + * An action that responds with the {@link Counter}'s current + * count. The result is plain text. This action is mapped to + * GET requests with a path of /count + * requests by an entry in the routes config file. + */ + public Result count() { + return ok(Integer.toString(counter.nextCount())); + } + +} diff --git a/play-framework/student-api/app/controllers/HomeController.java b/play-framework/student-api/app/controllers/HomeController.java new file mode 100644 index 0000000000..6a79856eb4 --- /dev/null +++ b/play-framework/student-api/app/controllers/HomeController.java @@ -0,0 +1,23 @@ +package controllers; + +import play.mvc.*; + +import views.html.*; + +/** + * This controller contains an action to handle HTTP requests + * to the application's home page. + */ +public class HomeController extends Controller { + + /** + * An action that renders an HTML page with a welcome message. + * The configuration in the routes file means that + * this method will be called when the application receives a + * GET request with a path of /. + */ + public Result index() { + return ok(index.render("Your new application is ready.")); + } + +} diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java new file mode 100644 index 0000000000..0adedfa432 --- /dev/null +++ b/play-framework/student-api/app/controllers/StudentController.java @@ -0,0 +1,56 @@ +package controllers; +import models.*; +import util.*; +import play.mvc.*; +import play.libs.Json; +import play.libs.Json.*; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; + +public class StudentController extends Controller { + public Result create() { + JsonNode json = request().body().asJson(); + if(json == null) + return badRequest(Util.createResponse("Expecting Json data",false)); + Student student=StudentStore.getInstance().addStudent((Student)Json.fromJson(json,Student.class)); + JsonNode jsonObject=Json.toJson(student); + return created(Util.createResponse(jsonObject,true)); + } + public Result update() { + JsonNode json = request().body().asJson(); + if(json == null) + return badRequest(Util.createResponse("Expecting Json data",false)); + Student student=StudentStore.getInstance().updateStudent((Student)Json.fromJson(json,Student.class)); + if(student==null){ + return notFound(Util.createResponse("Student not found",false)); + } + + JsonNode jsonObject=Json.toJson(student); + return ok(Util.createResponse(jsonObject,true)); + } + public Result retrieve(int id) { + Student student=StudentStore.getInstance().getStudent(id); + if(student==null){ + return notFound(Util.createResponse("Student with id:"+id+" not found",false)); + } + JsonNode jsonObjects=Json.toJson(student); + return ok(Util.createResponse(jsonObjects,true)); + } + public Result listStudents() { + List result=StudentStore.getInstance().getAllStudents(); + ObjectMapper mapper = new ObjectMapper(); + + JsonNode jsonData=mapper.convertValue(result, JsonNode.class); + return ok(Util.createResponse(jsonData,true)); + + } + public Result delete(int id) { + boolean status=StudentStore.getInstance().deleteStudent(id); + if(!status){ + return notFound(Util.createResponse("Student with id:"+id+" not found",false)); + } + return ok(Util.createResponse("Student with id:"+id+" deleted",true)); + } + +} diff --git a/play-framework/student-api/app/filters/ExampleFilter.java b/play-framework/student-api/app/filters/ExampleFilter.java new file mode 100644 index 0000000000..67a6a36cc3 --- /dev/null +++ b/play-framework/student-api/app/filters/ExampleFilter.java @@ -0,0 +1,45 @@ +package filters; + +import akka.stream.Materializer; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Function; +import javax.inject.*; +import play.mvc.*; +import play.mvc.Http.RequestHeader; + + +/** + * This is a simple filter that adds a header to all requests. It's + * added to the application's list of filters by the + * {@link Filters} class. + */ +@Singleton +public class ExampleFilter extends Filter { + + private final Executor exec; + + /** + * @param mat This object is needed to handle streaming of requests + * and responses. + * @param exec This class is needed to execute code asynchronously. + * It is used below by the thenAsyncApply method. + */ + @Inject + public ExampleFilter(Materializer mat, Executor exec) { + super(mat); + this.exec = exec; + } + + @Override + public CompletionStage apply( + Function> next, + RequestHeader requestHeader) { + + return next.apply(requestHeader).thenApplyAsync( + result -> result.withHeader("X-ExampleFilter", "foo"), + exec + ); + } + +} diff --git a/play-framework/student-api/app/models/Student.java b/play-framework/student-api/app/models/Student.java new file mode 100644 index 0000000000..dc539767bd --- /dev/null +++ b/play-framework/student-api/app/models/Student.java @@ -0,0 +1,47 @@ +package models; +public class Student { + private String firstName; + private String lastName; + private int age; + private int id; + public Student(){} + public Student(String firstName, String lastName, int age) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + +} diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/student-api/app/models/StudentStore.java new file mode 100644 index 0000000000..3290e141cd --- /dev/null +++ b/play-framework/student-api/app/models/StudentStore.java @@ -0,0 +1,52 @@ +package models; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StudentStore { + private static StudentStore instance; + private Map students = new HashMap<>(); + + public static StudentStore getInstance() { + if (instance == null) + instance = new StudentStore(); + return instance; + } + + public Student addStudent(Student student) { + int id = students.size() + 1; + student.setId(id); + students.put(id, student); + return student; + } + + public Student getStudent(int id) { + if (students.containsKey(id)) + return students.get(id); + return null; + } + + public List getAllStudents() { + return new ArrayList(students.values()); + } + + public Student updateStudent(Student student) { + int id=student.getId(); + if (students.containsKey(id)) { + student.setId(id); + students.put(id, student); + return student; + } + return null; + } + + public boolean deleteStudent(int id) { + + if (!students.containsKey(id)) + return false; + students.remove(id); + return true; + + } +} \ No newline at end of file diff --git a/play-framework/student-api/app/services/ApplicationTimer.java b/play-framework/student-api/app/services/ApplicationTimer.java new file mode 100644 index 0000000000..a951562b1d --- /dev/null +++ b/play-framework/student-api/app/services/ApplicationTimer.java @@ -0,0 +1,50 @@ +package services; + +import java.time.Clock; +import java.time.Instant; +import java.util.concurrent.CompletableFuture; +import javax.inject.*; +import play.Logger; +import play.inject.ApplicationLifecycle; + +/** + * This class demonstrates how to run code when the + * application starts and stops. It starts a timer when the + * application starts. When the application stops it prints out how + * long the application was running for. + * + * This class is registered for Guice dependency injection in the + * {@link Module} class. We want the class to start when the application + * starts, so it is registered as an "eager singleton". See the code + * in the {@link Module} class to see how this happens. + * + * This class needs to run code when the server stops. It uses the + * application's {@link ApplicationLifecycle} to register a stop hook. + */ +@Singleton +public class ApplicationTimer { + + private final Clock clock; + private final ApplicationLifecycle appLifecycle; + private final Instant start; + + @Inject + public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) { + this.clock = clock; + this.appLifecycle = appLifecycle; + // This code is called when the application starts. + start = clock.instant(); + Logger.info("ApplicationTimer demo: Starting application at " + start); + + // When the application starts, register a stop hook with the + // ApplicationLifecycle object. The code inside the stop hook will + // be run when the application stops. + appLifecycle.addStopHook(() -> { + Instant stop = clock.instant(); + Long runningTime = stop.getEpochSecond() - start.getEpochSecond(); + Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s."); + return CompletableFuture.completedFuture(null); + }); + } + +} diff --git a/play-framework/student-api/app/services/AtomicCounter.java b/play-framework/student-api/app/services/AtomicCounter.java new file mode 100644 index 0000000000..41f741cbf7 --- /dev/null +++ b/play-framework/student-api/app/services/AtomicCounter.java @@ -0,0 +1,26 @@ +package services; + +import java.util.concurrent.atomic.AtomicInteger; +import javax.inject.*; + +/** + * This class is a concrete implementation of the {@link Counter} trait. + * It is configured for Guice dependency injection in the {@link Module} + * class. + * + * This class has a {@link Singleton} annotation because we need to make + * sure we only use one counter per application. Without this + * annotation we would get a new instance every time a {@link Counter} is + * injected. + */ +@Singleton +public class AtomicCounter implements Counter { + + private final AtomicInteger atomicCounter = new AtomicInteger(); + + @Override + public int nextCount() { + return atomicCounter.getAndIncrement(); + } + +} diff --git a/play-framework/student-api/app/services/Counter.java b/play-framework/student-api/app/services/Counter.java new file mode 100644 index 0000000000..dadad8b09d --- /dev/null +++ b/play-framework/student-api/app/services/Counter.java @@ -0,0 +1,13 @@ +package services; + +/** + * This interface demonstrates how to create a component that is injected + * into a controller. The interface represents a counter that returns a + * incremented number each time it is called. + * + * The {@link Modules} class binds this interface to the + * {@link AtomicCounter} implementation. + */ +public interface Counter { + int nextCount(); +} diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/student-api/app/util/Util.java new file mode 100644 index 0000000000..3718b50677 --- /dev/null +++ b/play-framework/student-api/app/util/Util.java @@ -0,0 +1,17 @@ +package util; +import com.fasterxml.jackson.databind.node.ObjectNode; +import play.libs.Json; +import play.libs.Json.*; +import com.fasterxml.jackson.databind.JsonNode; + +public class Util{ + public static ObjectNode createResponse(Object response,boolean ok){ + ObjectNode result = Json.newObject(); + result.put("isSuccessfull", ok); + if(response instanceof String) + result.put("body",(String)response); + else result.put("body",(JsonNode)response); + + return result; + } +} \ No newline at end of file diff --git a/play-framework/student-api/app/views/index.scala.html b/play-framework/student-api/app/views/index.scala.html new file mode 100644 index 0000000000..4539f5a10b --- /dev/null +++ b/play-framework/student-api/app/views/index.scala.html @@ -0,0 +1,20 @@ +@* + * This template takes a single argument, a String containing a + * message to display. + *@ +@(message: String) + +@* + * Call the `main` template with two arguments. The first + * argument is a `String` with the title of the page, the second + * argument is an `Html` object containing the body of the page. + *@ +@main("Welcome to Play") { + + @* + * Get an `Html` object by calling the built-in Play welcome + * template and passing a `String` message. + *@ + @play20.welcome(message, style = "Java") + +} diff --git a/play-framework/student-api/app/views/main.scala.html b/play-framework/student-api/app/views/main.scala.html new file mode 100644 index 0000000000..9414f4be6e --- /dev/null +++ b/play-framework/student-api/app/views/main.scala.html @@ -0,0 +1,23 @@ +@* + * This template is called from the `index` template. This template + * handles the rendering of the page header and body tags. It takes + * two arguments, a `String` for the title of the page and an `Html` + * object to insert into the body of the page. + *@ +@(title: String)(content: Html) + + + + + @* Here's where we render the page title `String`. *@ + @title + + + + + + @* And here's where we render the `Html` object containing + * the page content. *@ + @content + + diff --git a/play-framework/student-api/bin/activator b/play-framework/student-api/bin/activator new file mode 100644 index 0000000000..a8b11d482f --- /dev/null +++ b/play-framework/student-api/bin/activator @@ -0,0 +1,397 @@ +#!/usr/bin/env bash + +### ------------------------------- ### +### Helper methods for BASH scripts ### +### ------------------------------- ### + +realpath () { +( + TARGET_FILE="$1" + FIX_CYGPATH="$2" + + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + + COUNT=0 + while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ] + do + TARGET_FILE=$(readlink "$TARGET_FILE") + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + COUNT=$(($COUNT + 1)) + done + + # make sure we grab the actual windows path, instead of cygwin's path. + if [[ "x$FIX_CYGPATH" != "x" ]]; then + echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")" + else + echo "$(pwd -P)/$TARGET_FILE" + fi +) +} + + +# Uses uname to detect if we're in the odd cygwin environment. +is_cygwin() { + local os=$(uname -s) + case "$os" in + CYGWIN*) return 0 ;; + *) return 1 ;; + esac +} + +# TODO - Use nicer bash-isms here. +CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi) + + +# This can fix cygwin style /cygdrive paths so we get the +# windows style paths. +cygwinpath() { + local file="$1" + if [[ "$CYGWIN_FLAG" == "true" ]]; then + echo $(cygpath -w $file) + else + echo $file + fi +} + +# Make something URI friendly +make_url() { + url="$1" + local nospaces=${url// /%20} + if is_cygwin; then + echo "/${nospaces//\\//}" + else + echo "$nospaces" + fi +} + +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands +declare java_cmd=java +declare java_version +declare -r real_script_path="$(realpath "$0")" +declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")" +declare -r sbt_bin_dir="$(dirname "$real_script_path")" +declare -r app_version="1.3.10" + +declare -r script_name=activator +declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" ) +userhome="$HOME" +if is_cygwin; then + # cygwin sets home to something f-d up, set to real windows homedir + userhome="$USERPROFILE" +fi +declare -r activator_user_home_dir="${userhome}/.activator" +declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt" +declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt" + +echoerr () { + echo 1>&2 "$@" +} +vlog () { + [[ $verbose || $debug ]] && echoerr "$@" +} +dlog () { + [[ $debug ]] && echoerr "$@" +} + +jar_file () { + echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")" +} + +acquire_sbt_jar () { + sbt_jar="$(jar_file)" + + if [[ ! -f "$sbt_jar" ]]; then + echoerr "Could not find launcher jar: $sbt_jar" + exit 2 + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + [[ $verbose || $debug ]] && echo "# Executing command line:" && { + for arg; do + if printf "%s\n" "$arg" | grep -q ' '; then + printf "\"%s\"\n" "$arg" + else + printf "%s\n" "$arg" + fi + done + echo "" + } + + # THis used to be exec, but we loose the ability to re-hook stty then + # for cygwin... Maybe we should flag the feature here... + "$@" +} + +addJava () { + dlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + dlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +addResidual () { + dlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addDebugger () { + addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1" +} + +get_mem_opts () { + # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings. + # The reason is the Xms/Xmx, if they don't line up, cause errors. + if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then + echo "" + else + # a ham-fisted attempt to move some memory settings in concert + # so they need not be messed around with individually. + local mem=${1:-1024} + local codecache=$(( $mem / 8 )) + (( $codecache > 128 )) || codecache=128 + (( $codecache < 512 )) || codecache=512 + local class_metadata_size=$(( $codecache * 2 )) + local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize") + + echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m" + fi +} + +require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + echo "$opt requires <$type> argument" + exit 1 + fi +} + +is_function_defined() { + declare -f "$1" > /dev/null +} + +# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter +detect_terminal_for_ui() { + [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && { + addResidual "ui" + } + # SPECIAL TEST FOR MAC + [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && { + echo "Detected MAC OSX launched script...." + echo "Swapping to UI" + addResidual "ui" + } +} + +process_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v|-verbose) verbose=1 && shift ;; + -d|-debug) debug=1 && shift ;; + + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; + -batch) exec &1 | awk -F '"' '/version/ {print $2}') + vlog "[process_args] java_version = '$java_version'" +} + +# Detect that we have java installed. +checkJava() { + local required_version="$1" + # Now check to see if it's a good enough version + if [[ "$java_version" == "" ]]; then + echo + echo No java installations was detected. + echo Please go to http://www.java.com/getjava/ and download + echo + exit 1 + elif [[ ! "$java_version" > "$required_version" ]]; then + echo + echo The java installation you have is not up to date + echo $script_name requires at least version $required_version+, you have + echo version $java_version + echo + echo Please go to http://www.java.com/getjava/ and download + echo a valid Java Runtime and install before running $script_name. + echo + exit 1 + fi +} + + +run() { + # no jar? download it. + [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || { + # still no jar? uh-oh. + echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar" + exit 1 + } + + # process the combined args, then reset "$@" to the residuals + process_args "$@" + detect_terminal_for_ui + set -- "${residual_args[@]}" + argumentCount=$# + + # TODO - java check should be configurable... + checkJava "1.6" + + #If we're in cygwin, we should use the windows config, and terminal hacks + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty -icanon min 1 -echo > /dev/null 2>&1 + addJava "-Djline.terminal=jline.UnixTerminal" + addJava "-Dsbt.cygwin=true" + fi + + # run sbt + execRunner "$java_cmd" \ + "-Dactivator.home=$(make_url "$sbt_home")" \ + ${SBT_OPTS:-$default_sbt_opts} \ + $(get_mem_opts $sbt_mem) \ + ${JAVA_OPTS} \ + ${java_args[@]} \ + -jar "$sbt_jar" \ + "${sbt_commands[@]}" \ + "${residual_args[@]}" + + exit_code=$? + + # Clean up the terminal from cygwin hacks. + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty icanon echo > /dev/null 2>&1 + fi + exit $exit_code +} + + +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r sbt_opts_file=".sbtopts" +declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts" +declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt" + +usage() { + cat < path to global settings/plugins directory (default: ~/.sbt) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series) + -ivy path to local Ivy repository (default: ~/.ivy2) + -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem)) + -no-share use all local caches; no sharing + -no-global uses global caches, but does not use global ~/.sbt directory. + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + + # sbt version (default: from project/build.properties if present, else latest release) + -sbt-version use the specified version of sbt + -sbt-jar use the specified jar as the sbt launcher + -sbt-rc use an RC version of sbt + -sbt-snapshot use a snapshot version of sbt + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # jvm options and output control + JAVA_OPTS environment variable, if unset uses "$java_opts" + SBT_OPTS environment variable, if unset uses "$default_sbt_opts" + ACTIVATOR_OPTS Environment variable, if unset uses "" + .sbtopts if this file exists in the current directory, it is + prepended to the runner args + /etc/sbt/sbtopts if this file exists, it is prepended to the runner args + -Dkey=val pass -Dkey=val directly to the java runtime + -J-X pass option -X directly to the java runtime + (-J is stripped) + -S-X add -X to sbt's scalacOptions (-S is stripped) + +In the case of duplicated or conflicting options, the order above +shows precedence: JAVA_OPTS lowest, command line options highest. +EOM +} + + + +process_my_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) addJava "$noshare_opts" && shift ;; + -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -batch) exec ^&1') do ( + if %%~j==java set JAVAINSTALLED=1 + if %%~j==openjdk set JAVAINSTALLED=1 +) + +rem Detect the same thing about javac +if "%_JAVACCMD%"=="" ( + if not "%JAVA_HOME%"=="" ( + if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe" + ) +) +if "%_JAVACCMD%"=="" set _JAVACCMD=javac +for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do ( + if %%~j==javac set JAVACINSTALLED=1 +) + +rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style +set JAVAOK=true +if not defined JAVAINSTALLED set JAVAOK=false +if not defined JAVACINSTALLED set JAVAOK=false + +if "%JAVAOK%"=="false" ( + echo. + echo A Java JDK is not installed or can't be found. + if not "%JAVA_HOME%"=="" ( + echo JAVA_HOME = "%JAVA_HOME%" + ) + echo. + echo Please go to + echo http://www.oracle.com/technetwork/java/javase/downloads/index.html + echo and download a valid Java JDK and install before running Activator. + echo. + echo If you think this message is in error, please check + echo your environment variables to see if "java.exe" and "javac.exe" are + echo available via JAVA_HOME or PATH. + echo. + if defined DOUBLECLICKED pause + exit /B 1 +) + +rem Check what Java version is being used to determine what memory options to use +for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( + set JAVA_VERSION=%%g +) + +rem Strips away the " characters +set JAVA_VERSION=%JAVA_VERSION:"=% + +rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below +for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do ( + set MAJOR=%%v + set MINOR=%%w + set BUILD=%%x + + set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M + if "!MINOR!" LSS "8" ( + set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M + ) + + set MEM_OPTS=!META_SIZE! + ) + +rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. +set _JAVA_OPTS=%JAVA_OPTS% +if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% + +set DEBUG_OPTS= + +rem Loop through the arguments, building remaining args in args variable +set args= +:argsloop +if not "%~1"=="" ( + rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them. + rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack. + set arg1=%~1 + if "!arg1:~0,2!"=="-D" ( + set "args=%args% "%~1"="%~2"" + shift + shift + goto argsloop + ) + + if "%~1"=="-jvm-debug" ( + if not "%~2"=="" ( + rem This piece of magic somehow checks that an argument is a number + for /F "delims=0123456789" %%i in ("%~2") do ( + set var="%%i" + ) + if defined var ( + rem Not a number, assume no argument given and default to 9999 + set JPDA_PORT=9999 + ) else ( + rem Port was given, shift arguments + set JPDA_PORT=%~2 + shift + ) + ) else ( + set JPDA_PORT=9999 + ) + shift + + set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT! + goto argsloop + ) + rem else + set "args=%args% "%~1"" + shift + goto argsloop +) + +:run + +if "!args!"=="" ( + if defined DOUBLECLICKED ( + set CMDS="ui" + ) else set CMDS=!args! +) else set CMDS=!args! + +rem We add a / in front, so we get file:///C: instead of file://C: +rem Java considers the later a UNC path. +rem We also attempt a solid effort at making it URI friendly. +rem We don't even bother with UNC paths. +set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/! +set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20! + +rem Checks if the command contains spaces to know if it should be wrapped in quotes or not +set NON_SPACED_CMD=%_JAVACMD: =% +if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% +if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% + +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end + +@endlocal + +exit /B %ERROR_CODE% diff --git a/play-framework/student-api/build.sbt b/play-framework/student-api/build.sbt new file mode 100644 index 0000000000..0f5ea736f6 --- /dev/null +++ b/play-framework/student-api/build.sbt @@ -0,0 +1,13 @@ +name := """student-api""" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.11.7" + +libraryDependencies ++= Seq( + javaJdbc, + cache, + javaWs +) diff --git a/play-framework/student-api/conf/application.conf b/play-framework/student-api/conf/application.conf new file mode 100644 index 0000000000..489d3f9b3e --- /dev/null +++ b/play-framework/student-api/conf/application.conf @@ -0,0 +1,353 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile +# ~~~~~ +# Play uses HOCON as its configuration file format. HOCON has a number +# of advantages over other config formats, but there are two things that +# can be used when modifying settings. +# +# You can include other configuration files in this main application.conf file: +#include "extra-config.conf" +# +# You can declare variables and substitute for them: +#mykey = ${some.value} +# +# And if an environment variable exists when there is no other subsitution, then +# HOCON will fall back to substituting environment variable: +#mykey = ${JAVA_HOME} + +## Akka +# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration +# https://www.playframework.com/documentation/latest/JavaAkka#Configuration +# ~~~~~ +# Play uses Akka internally and exposes Akka Streams and actors in Websockets and +# other streaming HTTP responses. +akka { + # "akka.log-config-on-start" is extraordinarly useful because it log the complete + # configuration at INFO level, including defaults and overrides, so it s worth + # putting at the very top. + # + # Put the following in your conf/logback.xml file: + # + # + # + # And then uncomment this line to debug the configuration. + # + #log-config-on-start = true +} + +## Secret key +# http://www.playframework.com/documentation/latest/ApplicationSecret +# ~~~~~ +# The secret key is used to sign Play's session cookie. +# This must be changed for production, but we don't recommend you change it in this file. +play.crypto.secret = "changeme" + +## Modules +# https://www.playframework.com/documentation/latest/Modules +# ~~~~~ +# Control which modules are loaded when Play starts. Note that modules are +# the replacement for "GlobalSettings", which are deprecated in 2.5.x. +# Please see https://www.playframework.com/documentation/latest/GlobalSettings +# for more information. +# +# You can also extend Play functionality by using one of the publically available +# Play modules: https://playframework.com/documentation/latest/ModuleDirectory +play.modules { + # By default, Play will load any class called Module that is defined + # in the root package (the "app" directory), or you can define them + # explicitly below. + # If there are any built-in modules that you want to disable, you can list them here. + #enabled += my.application.Module + + # If there are any built-in modules that you want to disable, you can list them here. + #disabled += "" +} + +## IDE +# https://www.playframework.com/documentation/latest/IDE +# ~~~~~ +# Depending on your IDE, you can add a hyperlink for errors that will jump you +# directly to the code location in the IDE in dev mode. The following line makes +# use of the IntelliJ IDEA REST interface: +#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" + +## Internationalisation +# https://www.playframework.com/documentation/latest/JavaI18N +# https://www.playframework.com/documentation/latest/ScalaI18N +# ~~~~~ +# Play comes with its own i18n settings, which allow the user's preferred language +# to map through to internal messages, or allow the language to be stored in a cookie. +play.i18n { + # The application languages + langs = [ "en" ] + + # Whether the language cookie should be secure or not + #langCookieSecure = true + + # Whether the HTTP only attribute of the cookie should be set to true + #langCookieHttpOnly = true +} + +## Play HTTP settings +# ~~~~~ +play.http { + ## Router + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # Define the Router object to use for this application. + # This router will be looked up first when the application is starting up, + # so make sure this is the entry point. + # Furthermore, it's assumed your route file is named properly. + # So for an application router like `my.application.Router`, + # you may need to define a router file `conf/my.application.routes`. + # Default to Routes in the root package (aka "apps" folder) (and conf/routes) + #router = my.application.Router + + ## Action Creator + # https://www.playframework.com/documentation/latest/JavaActionCreator + # ~~~~~ + #actionCreator = null + + ## ErrorHandler + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # If null, will attempt to load a class called ErrorHandler in the root package, + #errorHandler = null + + ## Filters + # https://www.playframework.com/documentation/latest/ScalaHttpFilters + # https://www.playframework.com/documentation/latest/JavaHttpFilters + # ~~~~~ + # Filters run code on every request. They can be used to perform + # common logic for all your actions, e.g. adding common headers. + # Defaults to "Filters" in the root package (aka "apps" folder) + # Alternatively you can explicitly register a class here. + #filters = my.application.Filters + + ## Session & Flash + # https://www.playframework.com/documentation/latest/JavaSessionFlash + # https://www.playframework.com/documentation/latest/ScalaSessionFlash + # ~~~~~ + session { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + + # Sets the max-age field of the cookie to 5 minutes. + # NOTE: this only sets when the browser will discard the cookie. Play will consider any + # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, + # you need to put a timestamp in the session and check it at regular intervals to possibly expire it. + #maxAge = 300 + + # Sets the domain on the session cookie. + #domain = "example.com" + } + + flash { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + } +} + +## Netty Provider +# https://www.playframework.com/documentation/latest/SettingsNetty +# ~~~~~ +play.server.netty { + # Whether the Netty wire should be logged + #log.wire = true + + # If you run Play on Linux, you can use Netty's native socket transport + # for higher performance with less garbage. + #transport = "native" +} + +## WS (HTTP Client) +# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS +# ~~~~~ +# The HTTP client primarily used for REST APIs. The default client can be +# configured directly, but you can also create different client instances +# with customized settings. You must enable this by adding to build.sbt: +# +# libraryDependencies += ws // or javaWs if using java +# +play.ws { + # Sets HTTP requests not to follow 302 requests + #followRedirects = false + + # Sets the maximum number of open HTTP connections for the client. + #ahc.maxConnectionsTotal = 50 + + ## WS SSL + # https://www.playframework.com/documentation/latest/WsSSL + # ~~~~~ + ssl { + # Configuring HTTPS with Play WS does not require programming. You can + # set up both trustManager and keyManager for mutual authentication, and + # turn on JSSE debugging in development with a reload. + #debug.handshake = true + #trustManager = { + # stores = [ + # { type = "JKS", path = "exampletrust.jks" } + # ] + #} + } +} + +## Cache +# https://www.playframework.com/documentation/latest/JavaCache +# https://www.playframework.com/documentation/latest/ScalaCache +# ~~~~~ +# Play comes with an integrated cache API that can reduce the operational +# overhead of repeated requests. You must enable this by adding to build.sbt: +# +# libraryDependencies += cache +# +play.cache { + # If you want to bind several caches, you can bind the individually + #bindCaches = ["db-cache", "user-cache", "session-cache"] +} + +## Filters +# https://www.playframework.com/documentation/latest/Filters +# ~~~~~ +# There are a number of built-in filters that can be enabled and configured +# to give Play greater security. You must enable this by adding to build.sbt: +# +# libraryDependencies += filters +# +play.filters { + ## CORS filter configuration + # https://www.playframework.com/documentation/latest/CorsFilter + # ~~~~~ + # CORS is a protocol that allows web applications to make requests from the browser + # across different domains. + # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has + # dependencies on CORS settings. + cors { + # Filter paths by a whitelist of path prefixes + #pathPrefixes = ["/some/path", ...] + + # The allowed origins. If null, all origins are allowed. + #allowedOrigins = ["http://www.example.com"] + + # The allowed HTTP methods. If null, all methods are allowed + #allowedHttpMethods = ["GET", "POST"] + } + + ## CSRF Filter + # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter + # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter + # ~~~~~ + # Play supports multiple methods for verifying that a request is not a CSRF request. + # The primary mechanism is a CSRF token. This token gets placed either in the query string + # or body of every form submitted, and also gets placed in the users session. + # Play then verifies that both tokens are present and match. + csrf { + # Sets the cookie to be sent only over HTTPS + #cookie.secure = true + + # Defaults to CSRFErrorHandler in the root package. + #errorHandler = MyCSRFErrorHandler + } + + ## Security headers filter configuration + # https://www.playframework.com/documentation/latest/SecurityHeaders + # ~~~~~ + # Defines security headers that prevent XSS attacks. + # If enabled, then all options are set to the below configuration by default: + headers { + # The X-Frame-Options header. If null, the header is not set. + #frameOptions = "DENY" + + # The X-XSS-Protection header. If null, the header is not set. + #xssProtection = "1; mode=block" + + # The X-Content-Type-Options header. If null, the header is not set. + #contentTypeOptions = "nosniff" + + # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. + #permittedCrossDomainPolicies = "master-only" + + # The Content-Security-Policy header. If null, the header is not set. + #contentSecurityPolicy = "default-src 'self'" + } + + ## Allowed hosts filter configuration + # https://www.playframework.com/documentation/latest/AllowedHostsFilter + # ~~~~~ + # Play provides a filter that lets you configure which hosts can access your application. + # This is useful to prevent cache poisoning attacks. + hosts { + # Allow requests to example.com, its subdomains, and localhost:9000. + #allowed = [".example.com", "localhost:9000"] + } +} + +## Evolutions +# https://www.playframework.com/documentation/latest/Evolutions +# ~~~~~ +# Evolutions allows database scripts to be automatically run on startup in dev mode +# for database migrations. You must enable this by adding to build.sbt: +# +# libraryDependencies += evolutions +# +play.evolutions { + # You can disable evolutions for a specific datasource if necessary + #db.default.enabled = false +} + +## Database Connection Pool +# https://www.playframework.com/documentation/latest/SettingsJDBC +# ~~~~~ +# Play doesn't require a JDBC database to run, but you can easily enable one. +# +# libraryDependencies += jdbc +# +play.db { + # The combination of these two settings results in "db.default" as the + # default JDBC pool: + #config = "db" + #default = "default" + + # Play uses HikariCP as the default connection pool. You can override + # settings by changing the prototype: + prototype { + # Sets a fixed JDBC connection pool size of 50 + #hikaricp.minimumIdle = 50 + #hikaricp.maximumPoolSize = 50 + } +} + +## JDBC Datasource +# https://www.playframework.com/documentation/latest/JavaDatabase +# https://www.playframework.com/documentation/latest/ScalaDatabase +# ~~~~~ +# Once JDBC datasource is set up, you can work with several different +# database options: +# +# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick +# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA +# EBean: https://playframework.com/documentation/latest/JavaEbean +# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm +# +db { + # You can declare as many datasources as you want. + # By convention, the default datasource is named `default` + + # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database + #default.driver = org.h2.Driver + #default.url = "jdbc:h2:mem:play" + #default.username = sa + #default.password = "" + + # You can turn on SQL logging for any datasource + # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements + #default.logSql=true +} diff --git a/play-framework/student-api/conf/logback.xml b/play-framework/student-api/conf/logback.xml new file mode 100644 index 0000000000..86ec12c0af --- /dev/null +++ b/play-framework/student-api/conf/logback.xml @@ -0,0 +1,41 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/play-framework/student-api/conf/routes b/play-framework/student-api/conf/routes new file mode 100644 index 0000000000..ab55792683 --- /dev/null +++ b/play-framework/student-api/conf/routes @@ -0,0 +1,12 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +GET / controllers.StudentController.listStudents() +POST /:id controllers.StudentController.retrieve(id:Int) +POST / controllers.StudentController.create() +PUT / controllers.StudentController.update() +DELETE /:id controllers.StudentController.delete(id:Int) + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/student-api/libexec/activator-launch-1.3.10.jar b/play-framework/student-api/libexec/activator-launch-1.3.10.jar new file mode 100644 index 0000000000..69050e7dec Binary files /dev/null and b/play-framework/student-api/libexec/activator-launch-1.3.10.jar differ diff --git a/play-framework/student-api/project/build.properties b/play-framework/student-api/project/build.properties new file mode 100644 index 0000000000..6d9fa6badb --- /dev/null +++ b/play-framework/student-api/project/build.properties @@ -0,0 +1,4 @@ +#Activator-generated Properties +#Wed Sep 07 12:29:40 EAT 2016 +template.uuid=c373963b-f5ad-433b-8e74-178e7ae25b1c +sbt.version=0.13.11 diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/student-api/project/plugins.sbt new file mode 100644 index 0000000000..51c5b2a35a --- /dev/null +++ b/play-framework/student-api/project/plugins.sbt @@ -0,0 +1,21 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.6") + +// Web plugins +addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3") +addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7") +addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") +addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.2") + +// Play enhancer - this automatically generates getters/setters for public fields +// and rewrites accessors of these fields to use the getters/setters. Remove this +// plugin if you prefer not to have this feature, or disable on a per project +// basis using disablePlugins(PlayEnhancer) in your build.sbt +addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0") + +// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using +// enablePlugins(PlayEbean). +// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0") diff --git a/play-framework/student-api/public/images/favicon.png b/play-framework/student-api/public/images/favicon.png new file mode 100644 index 0000000000..c7d92d2ae4 Binary files /dev/null and b/play-framework/student-api/public/images/favicon.png differ diff --git a/play-framework/student-api/public/javascripts/hello.js b/play-framework/student-api/public/javascripts/hello.js new file mode 100644 index 0000000000..02ee13c7ca --- /dev/null +++ b/play-framework/student-api/public/javascripts/hello.js @@ -0,0 +1,3 @@ +if (window.console) { + console.log("Welcome to your Play application's JavaScript!"); +} diff --git a/play-framework/student-api/public/stylesheets/main.css b/play-framework/student-api/public/stylesheets/main.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java new file mode 100644 index 0000000000..3d7c4875aa --- /dev/null +++ b/play-framework/student-api/test/ApplicationTest.java @@ -0,0 +1,45 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.*; + +import play.mvc.*; +import play.test.*; +import play.data.DynamicForm; +import play.data.validation.ValidationError; +import play.data.validation.Constraints.RequiredValidator; +import play.i18n.Lang; +import play.libs.F; +import play.libs.F.*; +import play.twirl.api.Content; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + + +/** + * + * Simple (JUnit) tests that can call all parts of a play app. + * If you are interested in mocking a whole application, see the wiki for more details. + * + */ +public class ApplicationTest { + + @Test + public void simpleCheck() { + int a = 1 + 1; + assertEquals(2, a); + } + + @Test + public void renderTemplate() { + Content html = views.html.index.render("Your new application is ready."); + assertEquals("text/html", html.contentType()); + assertTrue(html.body().contains("Your new application is ready.")); + } + + +} diff --git a/play-framework/student-api/test/IntegrationTest.java b/play-framework/student-api/test/IntegrationTest.java new file mode 100644 index 0000000000..c53c71e124 --- /dev/null +++ b/play-framework/student-api/test/IntegrationTest.java @@ -0,0 +1,25 @@ +import org.junit.*; + +import play.mvc.*; +import play.test.*; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + +import static org.fluentlenium.core.filter.FilterConstructor.*; + +public class IntegrationTest { + + /** + * add your integration test here + * in this example we just check if the welcome page is being shown + */ + @Test + public void test() { + running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { + browser.goTo("http://localhost:3333"); + assertTrue(browser.pageSource().contains("Your new application is ready.")); + }); + } + +} diff --git a/pom.xml b/pom.xml index 97a164b5b2..41b348c893 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -8,29 +9,42 @@ pom - + UTF-8 - + assertj apache-cxf - apache-fop + + autovalue-tutorial + + cdi core-java core-java-8 + couchbase-sdk-intro couchbase-sdk-spring-service + dozer dependency-injection - gatling + deltaspike + + enterprise-patterns + feign-client + gson gson-jackson-performance guava guava18 guava19 + handling-spring-static-resources httpclient + + immutables + jackson javaxval jjwt @@ -39,18 +53,26 @@ json json-path junit5 - mockito - mocks jee7schedule + + log4j + + mockito + mocks + mutation-testing + + orika + querydsl + rest-assured rest-testing resteasy - log4j spring-all + spring-akka spring-apache-camel spring-autowire spring-batch @@ -69,6 +91,7 @@ spring-hibernate3 spring-hibernate4 spring-jpa + spring-jpa-jndi spring-katharsis spring-mockito spring-mvc-java @@ -79,7 +102,10 @@ spring-quartz spring-spel spring-rest + spring-rest-angular spring-rest-docs + spring-cloud + spring-cloud-data-flow spring-security-basic-auth spring-security-custom-permission @@ -94,18 +120,18 @@ spring-security-rest-custom spring-security-rest-digest-auth spring-security-rest-full + spring-security-x509 spring-thymeleaf spring-zuul + spring-mvc-velocity + jsf xml lombok redis - webjars - wicket - mutation-testing - spring-mvc-velocity xstream + java-cassandra diff --git a/sockets/pom.xml b/sockets/pom.xml new file mode 100644 index 0000000000..24e8e436f3 --- /dev/null +++ b/sockets/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + com.baeldung + sockets + 1.0 + sockets + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 8 + 8 + + + + + + + junit + junit + 4.3 + test + + + + diff --git a/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/sockets/src/main/java/com/baeldung/socket/EchoClient.java new file mode 100644 index 0000000000..e8ec97c80a --- /dev/null +++ b/sockets/src/main/java/com/baeldung/socket/EchoClient.java @@ -0,0 +1,43 @@ +package com.baeldung.socket; + +import java.io.*; +import java.net.*; + +public class EchoClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader( + clientSocket.getInputStream())); + } catch (IOException e) { + System.out.print(e); + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + String resp = in.readLine(); + return resp; + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java new file mode 100644 index 0000000000..2ece1ceebe --- /dev/null +++ b/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -0,0 +1,71 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoMultiServer { + private ServerSocket serverSocket; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + while (true) + new EchoClientHandler(serverSocket.accept()).run(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + stop(); + } + + } + + public void stop() { + try { + + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private static class EchoClientHandler extends Thread { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public EchoClientHandler(Socket socket) { + this.clientSocket = socket; + } + + public void run() { + try { + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader( + clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("bye"); + break; + } + out.println(inputLine); + } + + in.close(); + out.close(); + clientSocket.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] args) { + EchoMultiServer server = new EchoMultiServer(); + server.start(5555); + } + +} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/sockets/src/main/java/com/baeldung/socket/EchoServer.java new file mode 100644 index 0000000000..3607afa7f5 --- /dev/null +++ b/sockets/src/main/java/com/baeldung/socket/EchoServer.java @@ -0,0 +1,50 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader( + clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("good bye"); + break; + } + out.println(inputLine); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + EchoServer server = new EchoServer(); + server.start(4444); + } + +} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/sockets/src/main/java/com/baeldung/socket/GreetClient.java new file mode 100644 index 0000000000..7252827c87 --- /dev/null +++ b/sockets/src/main/java/com/baeldung/socket/GreetClient.java @@ -0,0 +1,46 @@ +package com.baeldung.socket; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +public class GreetClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader( + clientSocket.getInputStream())); + } catch (IOException e) { + + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + String resp = in.readLine(); + return resp; + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/sockets/src/main/java/com/baeldung/socket/GreetServer.java new file mode 100644 index 0000000000..8bf675c7b9 --- /dev/null +++ b/sockets/src/main/java/com/baeldung/socket/GreetServer.java @@ -0,0 +1,47 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class GreetServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader( + clientSocket.getInputStream())); + String greeting = in.readLine(); + if ("hello server".equals(greeting)) + out.println("hello client"); + else + out.println("unrecognised greeting"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + public static void main(String[] args) { + GreetServer server=new GreetServer(); + server.start(6666); + } + +} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java new file mode 100644 index 0000000000..19a59c211c --- /dev/null +++ b/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -0,0 +1,57 @@ +package com.baeldung.socket; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +public class EchoMultiTest { + + { + Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555)); + } + + + @Test + public void givenClient1_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", 5555); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + + @Test + public void givenClient2_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", 5555); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + + @Test + public void givenClient3_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", 5555); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + +} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/sockets/src/test/java/com/baeldung/socket/EchoTest.java new file mode 100644 index 0000000000..0f0c02e4d8 --- /dev/null +++ b/sockets/src/test/java/com/baeldung/socket/EchoTest.java @@ -0,0 +1,41 @@ +package com.baeldung.socket; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +public class EchoTest { + { + Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444)); + } + + EchoClient client = new EchoClient(); + + @Before + public void init() { + client.startConnection("127.0.0.1", 4444); + } + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { + + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + String resp3 = client.sendMessage("!"); + String resp4 = client.sendMessage("."); + assertEquals("hello", resp1); + assertEquals("world", resp2); + assertEquals("!", resp3); + assertEquals("good bye", resp4); + } + + @After + public void tearDown() { + client.stopConnection(); + } + +} diff --git a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java b/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java new file mode 100644 index 0000000000..fedc32fb39 --- /dev/null +++ b/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java @@ -0,0 +1,36 @@ +package com.baeldung.socket; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +public class GreetServerTest { + + GreetClient client; + + { + Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666)); + } + + @Before + public void init() { + client = new GreetClient(); + client.startConnection("127.0.0.1", 6666); + + } + + @Test + public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() { + String response = client.sendMessage("hello server"); + assertEquals("hello client", response); + } + + @After + public void finish() { + client.stopConnection(); + } +} 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/EventListenerExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java new file mode 100644 index 0000000000..e9cd1a159d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/EventListenerExampleBean.java @@ -0,0 +1,19 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerExampleBean { + private static final Logger LOG = Logger.getLogger(EventListenerExampleBean.class); + + public static int counter; + + @EventListener + public void onApplicationEvent(ContextRefreshedEvent event) { + LOG.info("Increment counter"); + counter++; + } +} 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..5a20ff5602 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,156 +1,177 @@ - 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-thymeleaf + + + 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 + + + + org.webjars + bootstrap + 3.3.4 + + + org.webjars + jquery + 2.1.4 + + - - 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 - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin + pl.project13.maven + git-commit-id-plugin + 2.2.1 - + - - - 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/webjars/src/main/java/com/baeldung/TestController.java b/spring-boot/src/main/java/com/baeldung/TestController.java similarity index 100% rename from webjars/src/main/java/com/baeldung/TestController.java rename to spring-boot/src/main/java/com/baeldung/TestController.java diff --git a/webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java similarity index 100% rename from webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java rename to spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java 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..1da2bd2989 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -0,0 +1,30 @@ +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; + +import java.util.HashMap; +import java.util.Map; + +@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 Map getCommitId() { + Map result = new HashMap<>(); + result.put("Commit message",commitMessage); + result.put("Commit branch", branch); + result.put("Commit id", commitId); + return result; + } +} 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/webjars/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html similarity index 100% rename from webjars/src/main/resources/templates/index.html rename to spring-boot/src/main/resources/templates/index.html diff --git a/webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java similarity index 100% rename from webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java 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-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml new file mode 100644 index 0000000000..2ddb9d85a3 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + batch-job + 0.0.1-SNAPSHOT + jar + + batch-job + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-task-starter + 1.0.1.RELEASE + + + + org.springframework.boot + spring-boot-starter-batch + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java new file mode 100644 index 0000000000..f717f0f644 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.task.configuration.EnableTask; + +@EnableTask +@EnableBatchProcessing +@SpringBootApplication +public class BatchJobApplication { + + public static void main(String[] args) { + SpringApplication.run(BatchJobApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java new file mode 100644 index 0000000000..dc6a5e2827 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java @@ -0,0 +1,38 @@ +package org.baeldung.spring.cloud; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class JobConfiguration { + + private static final Log logger = LogFactory.getLog(JobConfiguration.class); + + @Autowired + public JobBuilderFactory jobBuilderFactory; + + @Autowired + public StepBuilderFactory stepBuilderFactory; + + @Bean + public Job job() { + return jobBuilderFactory.get("job").start(stepBuilderFactory.get("jobStep1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + logger.info("Job was run"); + return RepeatStatus.FINISHED; + } + }).build()).build(); + } +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java new file mode 100644 index 0000000000..5f18ec75c4 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BatchJobApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml new file mode 100644 index 0000000000..94c4106d6f --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + data-flow-server + 0.0.1-SNAPSHOT + jar + + data-flow-server + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-dataflow-server-local + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dataflow-dependencies + 1.0.0.BUILD-SNAPSHOT + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + 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-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java b/spring-cloud-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java new file mode 100644 index 0000000000..227c10b620 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/main/java/org/baeldung/spring/cloud/DataFlowServerApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.spring.cloud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.dataflow.server.EnableDataFlowServer; + +@EnableDataFlowServer +@SpringBootApplication +public class DataFlowServerApplication { + + public static void main(String[] args) { + SpringApplication.run(DataFlowServerApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java new file mode 100644 index 0000000000..f853e29244 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowServerApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml new file mode 100644 index 0000000000..a074fef88f --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + data-flow-shell + 0.0.1-SNAPSHOT + jar + + data-flow-shell + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-dataflow-shell + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dataflow-dependencies + 1.0.0.BUILD-SNAPSHOT + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + 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-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java b/spring-cloud-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java new file mode 100644 index 0000000000..36c421f5bf --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/main/java/org/baeldung/spring/cloud/DataFlowShellApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.spring.cloud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.dataflow.shell.EnableDataFlowShell; + +@EnableDataFlowShell +@SpringBootApplication +public class DataFlowShellApplication { + + public static void main(String[] args) { + SpringApplication.run(DataFlowShellApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java new file mode 100644 index 0000000000..7e2bc1cb37 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowShellApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml new file mode 100644 index 0000000000..8415d95373 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + log-sink + 0.0.1-SNAPSHOT + jar + + log-sink + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java b/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java new file mode 100644 index 0000000000..a2b9968539 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/main/java/org/baeldung/spring/cloud/LogSinkApplication.java @@ -0,0 +1,26 @@ +package org.baeldung.spring.cloud; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Sink; + +@EnableBinding(Sink.class) +@SpringBootApplication +public class LogSinkApplication { + + private static Logger logger = LoggerFactory.getLogger(LogSinkApplication.class); + + @StreamListener(Sink.INPUT) + public void loggerSink(String date) { + + logger.info("Received: " + date); + } + + public static void main(String[] args) { + SpringApplication.run(LogSinkApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java new file mode 100644 index 0000000000..9f88c7f632 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class LogSinkApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml new file mode 100644 index 0000000000..509c185d61 --- /dev/null +++ b/spring-cloud-data-flow/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + org.baeldung.spring.cloud + spring-cloud-data-flow + 0.0.1-SNAPSHOT + pom + + data-flow-server + data-flow-shell + time-source + time-processor + log-sink + batch-job + + diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml new file mode 100644 index 0000000000..bc2efe7754 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + time-processor + 0.0.1-SNAPSHOT + jar + + time-processor + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java b/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java new file mode 100644 index 0000000000..7a2763d436 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/main/java/org/baeldung/spring/cloud/TimeProcessorApplication.java @@ -0,0 +1,27 @@ +package org.baeldung.spring.cloud; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.integration.annotation.Transformer; + +@EnableBinding(Processor.class) +@SpringBootApplication +public class TimeProcessorApplication { + + @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) + public Object transform(Long timestamp) { + + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); + String date = dateFormat.format(timestamp); + return date; + } + + public static void main(String[] args) { + SpringApplication.run(TimeProcessorApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java new file mode 100644 index 0000000000..875346f9db --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeProcessorApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml new file mode 100644 index 0000000000..587b782227 --- /dev/null +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + time-source + 0.0.1-SNAPSHOT + jar + + time-source + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java b/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java new file mode 100644 index 0000000000..5bce39ebe0 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/main/java/org/baeldung/spring/cloud/TimeSourceApplication.java @@ -0,0 +1,29 @@ +package org.baeldung.spring.cloud; + +import java.util.Date; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Source; +import org.springframework.context.annotation.Bean; +import org.springframework.integration.annotation.InboundChannelAdapter; +import org.springframework.integration.annotation.Poller; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.support.MessageBuilder; + +@EnableBinding(Source.class) +@SpringBootApplication +public class TimeSourceApplication { + + @Bean + @InboundChannelAdapter(value = Source.OUTPUT, poller = @Poller(fixedDelay = "10000", maxMessagesPerPoll = "1")) + public MessageSource timeMessageSource() { + + return () -> MessageBuilder.withPayload(new Date().getTime()).build(); + } + + public static void main(String[] args) { + SpringApplication.run(TimeSourceApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java new file mode 100644 index 0000000000..61fd8323d2 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeSourceApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/README.md b/spring-cloud/README.md new file mode 100644 index 0000000000..86f67cf26e --- /dev/null +++ b/spring-cloud/README.md @@ -0,0 +1,8 @@ +## The Module Holds Sources for the Following Articles + +- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) +- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) +- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) + + diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml new file mode 100644 index 0000000000..340923cbdf --- /dev/null +++ b/spring-cloud/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + + spring-cloud-config + spring-cloud-eureka + spring-cloud-hystrix + spring-cloud-integration + + pom + + spring-cloud + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/spring-cloud/spring-cloud-config/client-config/config-client-development.properties b/spring-cloud/spring-cloud-config/client-config/config-client-development.properties new file mode 100644 index 0000000000..6401d1be7f --- /dev/null +++ b/spring-cloud/spring-cloud-config/client-config/config-client-development.properties @@ -0,0 +1,2 @@ +user.role=Developer +user.password=pass diff --git a/spring-cloud/spring-cloud-config/client-config/config-client-production.properties b/spring-cloud/spring-cloud-config/client-config/config-client-production.properties new file mode 100644 index 0000000000..cd2e14fcc3 --- /dev/null +++ b/spring-cloud/spring-cloud-config/client-config/config-client-production.properties @@ -0,0 +1 @@ +user.role=User diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml new file mode 100644 index 0000000000..0ef4b35581 --- /dev/null +++ b/spring-cloud/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/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java b/spring-cloud/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/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/spring-cloud-config/client/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..18982a93b5 --- /dev/null +++ b/spring-cloud/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/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud/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/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/spring-cloud-config/docker/Dockerfile b/spring-cloud/spring-cloud-config/docker/Dockerfile new file mode 100644 index 0000000000..bdb37abf80 --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/Dockerfile @@ -0,0 +1,4 @@ +FROM alpine:edge +MAINTAINER baeldung.com +RUN apk add --no-cache openjdk8 +COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/ diff --git a/spring-cloud/spring-cloud-config/docker/Dockerfile.client b/spring-cloud/spring-cloud-config/docker/Dockerfile.client new file mode 100644 index 0000000000..5fbc0b98c0 --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/Dockerfile.client @@ -0,0 +1,6 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +RUN apk --no-cache add netcat-openbsd +COPY files/config-client.jar /opt/spring-cloud/lib/ +COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/ +RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh diff --git a/spring-cloud/spring-cloud-config/docker/Dockerfile.server b/spring-cloud/spring-cloud-config/docker/Dockerfile.server new file mode 100644 index 0000000000..4f7bd751e8 --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/Dockerfile.server @@ -0,0 +1,9 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +COPY files/config-server.jar /opt/spring-cloud/lib/ +ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \ + {"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}' +ENTRYPOINT ["/usr/bin/java"] +CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"] +VOLUME /var/lib/spring-cloud/config-repo +EXPOSE 8888 diff --git a/spring-cloud/spring-cloud-config/docker/config-client-entrypoint.sh b/spring-cloud/spring-cloud-config/docker/config-client-entrypoint.sh new file mode 100644 index 0000000000..12352119fa --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/config-client-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +while ! nc -z config-server 8888 ; do + echo "Waiting for upcoming Config Server" + sleep 2 +done + +java -jar /opt/spring-cloud/lib/config-client.jar diff --git a/spring-cloud/spring-cloud-config/docker/docker-compose.scale.yml b/spring-cloud/spring-cloud-config/docker/docker-compose.scale.yml new file mode 100644 index 0000000000..f74153bea3 --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/docker-compose.scale.yml @@ -0,0 +1,41 @@ +version: '2' +services: + config-server: + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-cloud/spring-cloud-config/docker/docker-compose.yml b/spring-cloud/spring-cloud-config/docker/docker-compose.yml new file mode 100644 index 0000000000..74c71b651c --- /dev/null +++ b/spring-cloud/spring-cloud-config/docker/docker-compose.yml @@ -0,0 +1,43 @@ +version: '2' +services: + config-server: + container_name: config-server + build: + context: . + dockerfile: Dockerfile.server + image: config-server:latest + expose: + - 8888 + networks: + - spring-cloud-network + volumes: + - spring-cloud-config-repo:/var/lib/spring-cloud/config-repo + logging: + driver: json-file + config-client: + container_name: config-client + build: + context: . + dockerfile: Dockerfile.client + image: config-client:latest + entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh + environment: + SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}' + expose: + - 8080 + ports: + - 8080:8080 + networks: + - spring-cloud-network + links: + - config-server:config-server + depends_on: + - config-server + logging: + driver: json-file +networks: + spring-cloud-network: + driver: bridge +volumes: + spring-cloud-config-repo: + external: true diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml new file mode 100644 index 0000000000..8e0e4b8706 --- /dev/null +++ b/spring-cloud/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/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml new file mode 100644 index 0000000000..c3f68854bb --- /dev/null +++ b/spring-cloud/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/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java b/spring-cloud/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/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/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties new file mode 100644 index 0000000000..2131f3b249 --- /dev/null +++ b/spring-cloud/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/spring-cloud-config/server/src/main/resources/config-server.jks b/spring-cloud/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/spring-cloud-config/server/src/main/resources/config-server.jks differ diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java b/spring-cloud/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/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-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml new file mode 100644 index 0000000000..f02bf7ad9c --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + + spring-cloud-eureka-server + spring-cloud-eureka-client + spring-cloud-eureka-feign-client + + pom + + Spring Cloud Eureka + Spring Cloud Eureka Server and Sample Clients + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml new file mode 100644 index 0000000000..720b49ddc2 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + spring-cloud-eureka-client + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Client + Spring Cloud Eureka Sample Client + + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.cloud + spring-cloud-starter-eureka + 1.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-web + 1.4.0.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR4 + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java new file mode 100644 index 0000000000..48099eeaa2 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.eureka.client; + +import com.netflix.discovery.EurekaClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.context.annotation.Lazy; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@EnableEurekaClient +@RestController +public class EurekaClientApplication implements GreetingController { + @Autowired + @Lazy + private EurekaClient eurekaClient; + + @Value("${spring.application.name}") + private String appName; + + public static void main(String[] args) { + SpringApplication.run(EurekaClientApplication.class, args); + } + + @Override + public String greeting() { + return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName()); + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java new file mode 100644 index 0000000000..33ee2574b7 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.springframework.web.bind.annotation.RequestMapping; + +public interface GreetingController { + @RequestMapping("/greeting") + String greeting(); +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml new file mode 100644 index 0000000000..08624aa159 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + application: + name: spring-cloud-eureka-client + +server: + port: 0 + +eureka: + client: + serviceUrl: + defaultZone: ${EUREKA_URI:http://localhost:8761/eureka} + instance: + preferIpAddress: true \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml new file mode 100644 index 0000000000..9e639c666a --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + spring-cloud-eureka-feign-client + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Feign Client + Spring Cloud Eureka - Sample Feign Client + + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + .. + + + + + com.baeldung.spring.cloud + spring-cloud-eureka-client + 1.0.0-SNAPSHOT + + + org.springframework.cloud + spring-cloud-starter-feign + 1.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-web + 1.4.0.RELEASE + + + org.springframework.boot + spring-boot-starter-thymeleaf + 1.4.0.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR4 + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java new file mode 100644 index 0000000000..7beb51d1ac --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/FeignClientApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.feign.client; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@SpringBootApplication +@EnableEurekaClient +@EnableFeignClients +@Controller +public class FeignClientApplication { + @Autowired + private GreetingClient greetingClient; + + public static void main(String[] args) { + SpringApplication.run(FeignClientApplication.class, args); + } + + @RequestMapping("/get-greeting") + public String greeting(Model model) { + model.addAttribute("greeting", greetingClient.greeting()); + return "greeting-view"; + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java new file mode 100644 index 0000000000..6bd444b347 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/java/com/baeldung/spring/cloud/feign/client/GreetingClient.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.cloud.feign.client; + +import com.baeldung.spring.cloud.eureka.client.GreetingController; +import org.springframework.cloud.netflix.feign.FeignClient; + +@FeignClient("spring-cloud-eureka-client") +public interface GreetingClient extends GreetingController { +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml new file mode 100644 index 0000000000..d053ef7a7e --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + application: + name: spring-cloud-eureka-feign-client + +server: + port: 8080 + +eureka: + client: + serviceUrl: + defaultZone: ${EUREKA_URI:http://localhost:8761/eureka} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html new file mode 100644 index 0000000000..42cdadb487 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/templates/greeting-view.html @@ -0,0 +1,9 @@ + + + + Greeting Page + + +

+ + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml new file mode 100644 index 0000000000..f4d655f708 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + spring-cloud-eureka-server + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Server + Spring Cloud Eureka Server Demo + + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.cloud + spring-cloud-starter-eureka-server + 1.1.5.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR4 + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java new file mode 100644 index 0000000000..d55145448d --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class EurekaServerApplication { + public static void main(String[] args) { + SpringApplication.run(EurekaServerApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml new file mode 100644 index 0000000000..49c3179bb5 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: 8761 + +eureka: + client: + registerWithEureka: false + fetchRegistry: false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml new file mode 100644 index 0000000000..8209dc8c67 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + feign-rest-consumer + 1.0.0-SNAPSHOT + jar + + feign-rest-consumer + + + com.baeldung.spring.cloud + spring-cloud-hystrix + 1.0.0-SNAPSHOT + .. + + + + + com.baeldung.spring.cloud + rest-producer + 1.0.0-SNAPSHOT + + + org.springframework.cloud + spring-cloud-starter-hystrix + 1.1.5.RELEASE + + + org.springframework.cloud + spring-cloud-starter-hystrix-dashboard + 1.1.5.RELEASE + + + org.springframework.cloud + spring-cloud-starter-feign + 1.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-web + 1.4.0.RELEASE + + + org.springframework.boot + spring-boot-starter-thymeleaf + 1.4.0.RELEASE + + + org.springframework.boot + spring-boot-starter-actuator + 1.4.0.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR4 + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java new file mode 100644 index 0000000000..b715e8c052 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import com.baeldung.spring.cloud.hystrix.rest.producer.GreetingController; +import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.PathVariable; + +@FeignClient( + name = "rest-producer", + url = "http://localhost:9090", + fallback = GreetingClient.GreetingClientFallback.class +) +public interface GreetingClient extends GreetingController { + @Component + public static class GreetingClientFallback implements GreetingClient { + @Override + public String greeting(@PathVariable("username") String username) { + return "Hello User!"; + } + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java new file mode 100644 index 0000000000..62dbbdd608 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class GreetingController { + @Autowired + private GreetingClient greetingClient; + + @RequestMapping("/get-greeting/{username}") + public String getGreeting(Model model, @PathVariable("username") String username) { + model.addAttribute("greeting", greetingClient.greeting(username)); + return "greeting-view"; + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java new file mode 100644 index 0000000000..2fc54216fe --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerFeignApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; + +@SpringBootApplication +@EnableCircuitBreaker +@EnableHystrixDashboard +@EnableFeignClients +public class RestConsumerFeignApplication { + public static void main(String[] args) { + SpringApplication.run(RestConsumerFeignApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/application.properties new file mode 100644 index 0000000000..3cf12afeb9 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/templates/greeting-view.html new file mode 100644 index 0000000000..302390fde0 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/templates/greeting-view.html @@ -0,0 +1,9 @@ + + + + Greetings from Hystrix + + +

+ + diff --git a/spring-cloud/spring-cloud-hystrix/pom.xml b/spring-cloud/spring-cloud-hystrix/pom.xml new file mode 100644 index 0000000000..b992ce3846 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-hystrix + 1.0.0-SNAPSHOT + + rest-producer + rest-consumer + feign-rest-consumer + + pom + + spring-cloud-hystrix + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + + + diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml new file mode 100644 index 0000000000..649ca88eb3 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + rest-consumer + 1.0.0-SNAPSHOT + jar + + rest-consumer + + + com.baeldung.spring.cloud + spring-cloud-hystrix + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.cloud + spring-cloud-starter-hystrix + 1.1.5.RELEASE + + + org.springframework.cloud + spring-cloud-starter-hystrix-dashboard + 1.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-web + 1.4.0.RELEASE + + + org.springframework.boot + spring-boot-starter-thymeleaf + 1.4.0.RELEASE + + + org.springframework.boot + spring-boot-starter-actuator + 1.4.0.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR4 + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java new file mode 100644 index 0000000000..112ad167f6 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class GreetingController { + @Autowired + private GreetingService greetingService; + + @RequestMapping("/get-greeting/{username}") + public String getGreeting(Model model, @PathVariable("username") String username) { + model.addAttribute("greeting", greetingService.getGreeting(username)); + return "greeting-view"; + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java new file mode 100644 index 0000000000..2502e292df --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingService.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class GreetingService { + @HystrixCommand(fallbackMethod = "defaultGreeting") + public String getGreeting(String username) { + return new RestTemplate().getForObject("http://localhost:9090/greeting/{username}", String.class, username); + } + + private String defaultGreeting(String username) { + return "Hello User!"; + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java new file mode 100644 index 0000000000..113949c754 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/RestConsumerApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; +import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; + +@SpringBootApplication +@EnableCircuitBreaker +@EnableHystrixDashboard +public class RestConsumerApplication { + public static void main(String[] args) { + SpringApplication.run(RestConsumerApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/application.properties new file mode 100644 index 0000000000..4c00e40deb --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/templates/greeting-view.html b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/templates/greeting-view.html new file mode 100644 index 0000000000..302390fde0 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/templates/greeting-view.html @@ -0,0 +1,9 @@ + + + + Greetings from Hystrix + + +

+ + diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml new file mode 100644 index 0000000000..726d18d2c3 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + + rest-producer + 1.0.0-SNAPSHOT + jar + + rest-producer + + + com.baeldung.spring.cloud + spring-cloud-hystrix + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + 1.4.0.RELEASE + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java new file mode 100644 index 0000000000..e82220d27a --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingController.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +public interface GreetingController { + @RequestMapping("/greeting/{username}") + String greeting(@PathVariable("username") String username); +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java new file mode 100644 index 0000000000..3541035ba5 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/GreetingControllerImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GreetingControllerImpl implements GreetingController { + @Override + public String greeting(@PathVariable("username") String username) { + return String.format("Hello %s!\n", username); + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java new file mode 100644 index 0000000000..206a6a2d03 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/producer/RestProducerApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestProducerApplication { + public static void main(String[] args) { + SpringApplication.run(RestProducerApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/application.properties b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/application.properties new file mode 100644 index 0000000000..9ce9d88ffb --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.application.name=rest-producer +server.port=9090 diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties b/spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties new file mode 100644 index 0000000000..7f3df86c7e --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties @@ -0,0 +1,8 @@ +spring.application.name=discovery +server.port=8082 + +eureka.instance.hostname=localhost + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ +eureka.client.register-with-eureka=false +eureka.client.fetch-registry=false diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties b/spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties new file mode 100644 index 0000000000..77faec8421 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties @@ -0,0 +1,10 @@ +spring.application.name=gateway +server.port=8080 + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ + +zuul.routes.resource.path=/resource/** +hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds: 5000 + diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties b/spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties new file mode 100644 index 0000000000..4e6cf3817c --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties @@ -0,0 +1,8 @@ +spring.application.name=resource +server.port=8083 + +resource.returnString=hello cloud + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ diff --git a/spring-cloud/spring-cloud-integration/part-1/config/pom.xml b/spring-cloud/spring-cloud-integration/part-1/config/pom.xml new file mode 100644 index 0000000000..0cb217acfb --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/config/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + config + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-config-server + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java new file mode 100644 index 0000000000..ff6c093b8b --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.integration.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableConfigServer +@EnableEurekaClient +public class ConfigApplication { + public static void main(String[] args) { + SpringApplication.run(ConfigApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties new file mode 100644 index 0000000000..6f614d0690 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8081 +spring.application.name=config + +spring.cloud.config.server.git.uri=file:///${user.home}/application-config + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml b/spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml new file mode 100644 index 0000000000..ee7c589549 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + discovery + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka-server + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java new file mode 100644 index 0000000000..a21c65312f --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.integration.discovery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class DiscoveryApplication { + public static void main(String[] args) { + SpringApplication.run(DiscoveryApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..ca9d59c9ed --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties @@ -0,0 +1,2 @@ +spring.cloud.config.name=discovery +spring.cloud.config.uri=http://localhost:8081 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml b/spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml new file mode 100644 index 0000000000..8e56d0fd35 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + gateway + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java new file mode 100644 index 0000000000..66e7c36f2a --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.integration.resource; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +@EnableEurekaClient +public class GatewayApplication { + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..9610d72675 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties @@ -0,0 +1,5 @@ +spring.cloud.config.name=gateway +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/pom.xml b/spring-cloud/spring-cloud-integration/part-1/pom.xml new file mode 100644 index 0000000000..770e26bca2 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + + com.baeldung.spring.cloud + spring-cloud-integration + 1.0.0-SNAPSHOT + + + + config + discovery + gateway + resource + + + part-1 + 1.0.0-SNAPSHOT + pom + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/pom.xml b/spring-cloud/spring-cloud-integration/part-1/resource/pom.xml new file mode 100644 index 0000000000..78112fa3e0 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/resource/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + resource + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java new file mode 100644 index 0000000000..107a9d199f --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.cloud.integration.resource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@EnableEurekaClient +@RestController +public class ResourceApplication { + public static void main(String[] args) { + SpringApplication.run(ResourceApplication.class, args); + } + + @Value("${resource.returnString}") + private String returnString; + + @RequestMapping("/hello/cloud") + public String getString() { + return returnString; + } +} diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..3c88a0b520 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties @@ -0,0 +1,5 @@ +spring.cloud.config.name=resource +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true + +eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/pom.xml b/spring-cloud/spring-cloud-integration/pom.xml new file mode 100644 index 0000000000..1d56995009 --- /dev/null +++ b/spring-cloud/spring-cloud-integration/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-integration + 1.0.0-SNAPSHOT + pom + + + part-1 + + \ No newline at end of file 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-data-rest/pom.xml b/spring-data-rest/pom.xml index f7f28aa9f1..5ae694a04f 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -1,6 +1,6 @@ + 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 @@ -15,7 +15,7 @@ org.springframework.boot spring-boot-starter-parent 1.3.3.RELEASE - + diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java index 6e8e62f52c..94eddc5b3e 100644 --- a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java +++ b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringDataRestApplication { - public static void main(String[] args) { - SpringApplication.run(SpringDataRestApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(SpringDataRestApplication.class, args); + } } diff --git a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java deleted file mode 100644 index ebbf0d49ab..0000000000 --- a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung; - -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.data.rest.core.annotation.RepositoryRestResource; - -import java.util.List; - -@RepositoryRestResource(collectionResourceRel = "users", path = "users") -public interface UserRepository extends PagingAndSortingRepository { - List findByName(@Param("name") String name); -} diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java new file mode 100644 index 0000000000..89ab848e81 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java @@ -0,0 +1,30 @@ +package com.baeldung.config; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener; +import org.springframework.validation.Validator; + +@Configuration +public class ValidatorEventRegister implements InitializingBean { + + @Autowired + ValidatingRepositoryEventListener validatingRepositoryEventListener; + + @Autowired + private Map validators; + + @Override + public void afterPropertiesSet() throws Exception { + List events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); + + for (Map.Entry entry : validators.entrySet()) { + events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue())); + } + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java new file mode 100644 index 0000000000..ee84738e7a --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java @@ -0,0 +1,25 @@ +package com.baeldung.exception.handlers; + +import java.util.stream.Collectors; + +import org.springframework.data.rest.core.RepositoryConstraintViolationException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice +public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler({ RepositoryConstraintViolationException.class }) + public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { + RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; + + String errors = nevEx.getErrors().getAllErrors().stream().map(p -> p.toString()).collect(Collectors.joining("\n")); + return new ResponseEntity(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); + } + +} \ No newline at end of file diff --git a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java similarity index 96% rename from spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java rename to spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java index a7a35a2573..4eb9773e36 100644 --- a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java new file mode 100644 index 0000000000..0b55ac89b6 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.repositories; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import com.baeldung.models.WebsiteUser; + +@RepositoryRestResource(collectionResourceRel = "users", path = "users") +public interface UserRepository extends CrudRepository { + +} diff --git a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java b/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java new file mode 100644 index 0000000000..0380332708 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java @@ -0,0 +1,33 @@ +package com.baeldung.validators; + +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; + +import com.baeldung.models.WebsiteUser; + +@Component("beforeCreateWebsiteUserValidator") +public class WebsiteUserValidator implements Validator { + + @Override + public boolean supports(Class clazz) { + return WebsiteUser.class.equals(clazz); + } + + @Override + public void validate(Object obj, Errors errors) { + + WebsiteUser user = (WebsiteUser) obj; + if (checkInputString(user.getName())) { + errors.rejectValue("name", "name.empty"); + } + + if (checkInputString(user.getEmail())) { + errors.rejectValue("email", "email.empty"); + } + } + + private boolean checkInputString(String input) { + return (input == null || input.trim().length() == 0); + } +} diff --git a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java b/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java new file mode 100644 index 0000000000..b185c6d5ab --- /dev/null +++ b/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java @@ -0,0 +1,100 @@ +package com.baeldung.validator; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.http.MediaType; +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.ResultActions; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = SpringDataRestApplication.class) +@WebAppConfiguration +public class SpringDataRestValidatorTest { + public static final String URL = "http://localhost"; + + private MockMvc mockMvc; + + @Autowired + protected WebApplicationContext wac; + + @Before + public void setup() { + mockMvc = webAppContextSetup(wac).build(); + } + + @Test + public void whenStartingApplication_thenCorrectStatusCode() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); + }; + + @Test + public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().is2xxSuccessful()) + .andExpect(redirectedUrl("http://localhost/users/1")); + } + + @Test + public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + user.setEmail(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) + .andExpect(status().isNotAcceptable()) + .andExpect(redirectedUrl(null)); + } + +} 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..ec8dc32200 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; + +@Entity +@Table (name = "USER_ORDER") +public class OrderDetail implements Serializable{ + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="ORDER_ID") + private Long orderId; + + public OrderDetail(){ + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + public void setOrderId(Long orderId) { + this.orderId = orderId; + } +} + + diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java new file mode 100644 index 0000000000..22b4fdc76c --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserEager implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserEager() { + } + + public UserEager(final Long userId) { + super(); + this.userId = userId; + } + + @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 UserEager other = (UserEager) 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 Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java new file mode 100644 index 0000000000..5038fb90ef --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table (name = "USER") +public class UserLazy implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name="USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); + + public UserLazy() { + } + + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } + + @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 UserLazy other = (UserLazy) 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 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..bbd7729232 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.fetching.util; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateUtil { + + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + //two config files are there + //one with lazy loading enabled + //another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } + + public static Session getHibernateSession() { + return new Configuration() + .configure("fetching.cfg.xml") + .buildSessionFactory() + .openSession(); + } + +} 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..1a5142c5c2 --- /dev/null +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -0,0 +1,68 @@ +package com.baeldung.hibernate.fetching.view; + +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.model.UserEager; +import com.baeldung.hibernate.fetching.model.UserLazy; +import com.baeldung.hibernate.fetching.util.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import java.util.List; +import java.util.Set; + +public class FetchingAppView { + + public FetchingAppView() { + + } + + // lazily loaded + public Set lazyLoaded() { + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From UserLazy").list(); + UserLazy userLazyLoaded = users.get(3); + // since data is lazyloaded so data won't be initialized + return (userLazyLoaded.getOrderDetail()); + } + + // eagerly loaded + public Set eagerLoaded() { + final Session sessionEager = HibernateUtil.getHibernateSession(); + // data should be loaded in the following line + // also note the queries generated + List user = sessionEager.createQuery("From UserEager").list(); + UserEager userEagerLoaded = user.get(3); + return userEagerLoaded.getOrderDetail(); + } + + // creates test data + // call this method to create the data in the database + public void createTestData() { + + final Session session = HibernateUtil.getHibernateSession("lazy"); + Transaction tx = session.beginTransaction(); + final UserLazy user1 = new UserLazy(); + final UserLazy user2 = new UserLazy(); + final UserLazy user3 = new UserLazy(); + + session.save(user1); + session.save(user2); + 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(); + + session.saveOrUpdate(order1); + session.saveOrUpdate(order2); + session.saveOrUpdate(order3); + session.saveOrUpdate(order4); + session.saveOrUpdate(order5); + + 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..1b9a4a191c --- /dev/null +++ b/spring-hibernate4/src/main/resources/fetching.cfg.xml @@ -0,0 +1,20 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + validate + + + + + + \ 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..c5f608e1a7 --- /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..b36d9828f1 --- /dev/null +++ b/spring-hibernate4/src/main/resources/fetching_create_queries.sql @@ -0,0 +1,14 @@ +CREATE TABLE `user` ( + `user_id` int(10) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; + + +CREATE TABLE `user_order` ( + `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, + `USER_ID` int(10) NOT NULL DEFAULT '0', + 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..a650f8eb37 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.fetching; + +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.view.FetchingAppView; +import org.hibernate.Hibernate; +import org.junit.Before; +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class HibernateFetchingTest { + + + //this loads sample data in the database + @Before + public void addFecthingTestData(){ + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + //testLazyFetching() tests the lazy loading + //Since it lazily loaded so orderDetalSetLazy won't + //be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + //testEagerFetching() tests the eager loading + //Since it eagerly loaded so orderDetalSetLazy would + //be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } +} diff --git a/spring-hibernate4/src/test/java/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/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..acee7008ba --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -0,0 +1,18 @@ + + + + + + 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..1dc37d0cf8 --- /dev/null +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -0,0 +1,18 @@ + + + + + + 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-jndi/.gitignore b/spring-jpa-jndi/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-jpa-jndi/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-jpa-jndi/README.md b/spring-jpa-jndi/README.md new file mode 100644 index 0000000000..6a99253545 --- /dev/null +++ b/spring-jpa-jndi/README.md @@ -0,0 +1,7 @@ +========= + +## Spring JPA using JNDI Project + + +### Relevant Articles: +- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](http://www.baeldung.com/spring-jpa-fndi) \ No newline at end of file diff --git a/spring-jpa-jndi/pom.xml b/spring-jpa-jndi/pom.xml new file mode 100644 index 0000000000..f7042f2384 --- /dev/null +++ b/spring-jpa-jndi/pom.xml @@ -0,0 +1,145 @@ + + 4.0.0 + + com.baeldung + spring-jpa-jndi + 0.1-SNAPSHOT + war + + spring-jpa-jndi + + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + javax.servlet + jstl + ${javax.servlet.jstl.version} + + + javax.servlet + servlet-api + ${javax.servlet.servlet-api.version} + + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + xml-apis + xml-apis + 1.4.01 + + + org.javassist + javassist + ${javassist.version} + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + 2.2.5 + + + + + + spring-jpa-jndi + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + + + + + + 4.3.2.RELEASE + 3.20.0-GA + + + 1.2 + 2.5 + + + 4.3.11.Final + 1.8.2.RELEASE + 1.4.192 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 3.5.1 + 2.7 + 2.4 + + + + + \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java new file mode 100644 index 0000000000..7ea731d9d4 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java @@ -0,0 +1,76 @@ +package org.baeldung.config; + +import java.util.Properties; + +import javax.naming.NamingException; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +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.jndi.JndiTemplate; +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; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-jndi.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +public class PersistenceJNDIConfig { + + @Autowired + private Environment env; + + public PersistenceJNDIConfig() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + public DataSource dataSource() { + try { + return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url")); + } catch (NamingException e) { + throw new IllegalArgumentException("Error looking up JNDI datasource", e); + } + } + + @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", "false"); + return hibernateProperties; + } +} \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java b/spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java new file mode 100644 index 0000000000..6afb271b10 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/config/SpringWebConfig.java @@ -0,0 +1,24 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +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({ "org.baeldung.web" }) +public class SpringWebConfig extends WebMvcConfigurerAdapter { + + @Bean + public InternalResourceViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setViewClass(JstlView.class); + viewResolver.setPrefix("/WEB-INF/views/jsp/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } +} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java b/spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java new file mode 100644 index 0000000000..1c8ce5400f --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/config/WebInitializer.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { PersistenceJNDIConfig.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { SpringWebConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } +} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java new file mode 100644 index 0000000000..0133a36a14 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/dao/FooDao.java @@ -0,0 +1,22 @@ +package org.baeldung.persistence.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.baeldung.persistence.model.Foo; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao { + + @PersistenceContext + private EntityManager entityManager; + + @SuppressWarnings("unchecked") + public List findAll() { + return entityManager.createQuery("from " + Foo.class.getName()).getResultList(); + } + +} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..d351fc54b8 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/model/Foo.java @@ -0,0 +1,34 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private long id; + @Column(name = "NAME") + private String name; + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java new file mode 100644 index 0000000000..a3109f5042 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/persistence/service/FooService.java @@ -0,0 +1,22 @@ +package org.baeldung.persistence.service; + +import java.util.List; + +import org.baeldung.persistence.dao.FooDao; +import org.baeldung.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FooService { + + @Autowired + private FooDao dao; + + public List findAll() { + return dao.findAll(); + } + +} diff --git a/spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java b/spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java new file mode 100644 index 0000000000..6900482de8 --- /dev/null +++ b/spring-jpa-jndi/src/main/java/org/baeldung/web/MainController.java @@ -0,0 +1,21 @@ +package org.baeldung.web; + +import org.baeldung.persistence.service.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class MainController { + + @Autowired + private FooService fooService; + + @GetMapping("/") + public String main(Model model) { + model.addAttribute("foos", fooService.findAll()); + return "index"; + } + +} diff --git a/spring-jpa-jndi/src/main/resources/context.xml b/spring-jpa-jndi/src/main/resources/context.xml new file mode 100644 index 0000000000..a64dfe9a61 --- /dev/null +++ b/spring-jpa-jndi/src/main/resources/context.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/resources/logback.xml b/spring-jpa-jndi/src/main/resources/logback.xml new file mode 100644 index 0000000000..1146dade63 --- /dev/null +++ b/spring-jpa-jndi/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/resources/persistence-jndi.properties b/spring-jpa-jndi/src/main/resources/persistence-jndi.properties new file mode 100644 index 0000000000..16d750d7f8 --- /dev/null +++ b/spring-jpa-jndi/src/main/resources/persistence-jndi.properties @@ -0,0 +1,8 @@ +# jdbc.X +jdbc.url=java:comp/env/jdbc/BaeldungDatabase + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +hibernate.show_sql=false +#hibernate.hbm2ddl.auto=create +hibernate.hbm2ddl.auto=update \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/resources/server.xml b/spring-jpa-jndi/src/main/resources/server.xml new file mode 100644 index 0000000000..5c61659018 --- /dev/null +++ b/spring-jpa-jndi/src/main/resources/server.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp b/spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp new file mode 100644 index 0000000000..f2ec8e2bec --- /dev/null +++ b/spring-jpa-jndi/src/main/webapp/WEB-INF/views/jsp/index.jsp @@ -0,0 +1,14 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + +Baeldung - Spring JNA JNDI + + + +

+ +

+
+ + \ 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/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java new file mode 100644 index 0000000000..34913632d8 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.multiple.dao.user; + +import org.baeldung.persistence.multiple.model.user.Possession; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PossessionRepository extends JpaRepository { + +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java new file mode 100644 index 0000000000..97b5803d73 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java @@ -0,0 +1,86 @@ +package org.baeldung.persistence.multiple.model.user; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_jpa_user") +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.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; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java index 305568bad8..1c6399dc44 100644 --- a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ b/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java @@ -1,10 +1,13 @@ package org.baeldung.persistence.multiple.model.user; +import java.util.List; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @@ -22,6 +25,9 @@ public class User { private int age; + @OneToMany + List possessionList; + public User() { super(); } @@ -58,6 +64,14 @@ public class User { this.age = age; } + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + @Override public String toString() { final StringBuilder builder = new StringBuilder(); 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..f20af34057 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 @@ -1,13 +1,18 @@ package org.baeldung.persistence.service; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Arrays; import org.baeldung.config.ProductConfig; import org.baeldung.config.UserConfig; import org.baeldung.persistence.multiple.dao.product.ProductRepository; +import org.baeldung.persistence.multiple.dao.user.PossessionRepository; import org.baeldung.persistence.multiple.dao.user.UserRepository; import org.baeldung.persistence.multiple.model.product.Product; +import org.baeldung.persistence.multiple.model.user.Possession; import org.baeldung.persistence.multiple.model.user.User; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,15 +20,20 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) +@EnableTransactionManagement public class JpaMultipleDBIntegrationTest { @Autowired private UserRepository userRepository; + @Autowired + private PossessionRepository possessionRepository; + @Autowired private ProductRepository productRepository; @@ -36,9 +46,14 @@ public class JpaMultipleDBIntegrationTest { user.setName("John"); user.setEmail("john@test.com"); user.setAge(20); + Possession p = new Possession("sample"); + p = possessionRepository.save(p); + user.setPossessionList(Arrays.asList(p)); user = userRepository.save(user); - - assertNotNull(userRepository.findOne(user.getId())); + final User result = userRepository.findOne(user.getId()); + assertNotNull(result); + System.out.println(result.getPossessionList()); + assertTrue(result.getPossessionList().size() == 1); } @Test @@ -57,10 +72,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..098afffba4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung spring-mvc-java @@ -11,6 +12,12 @@ org.springframework spring-web ${org.springframework.version} + + + commons-logging + commons-logging + + org.springframework @@ -18,27 +25,27 @@ ${org.springframework.version} - org.springframework - spring-websocket - ${org.springframework.version} - - - org.springframework - spring-messaging - ${org.springframework.version} - - - - com.fasterxml.jackson.core - jackson-core - 2.7.3 - - - com.fasterxml.jackson.core - jackson-databind - 2.7.3 - - + org.springframework + spring-websocket + ${org.springframework.version} + + + org.springframework + spring-messaging + ${org.springframework.version} + + + + com.fasterxml.jackson.core + jackson-core + 2.7.3 + + + com.fasterxml.jackson.core + jackson-databind + 2.7.3 + + javax.servlet @@ -68,24 +75,62 @@ aspectjweaver ${aspectj.version} + + + + commons-fileupload + commons-fileupload + 1.3.1 + + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + + + + + com.fasterxml.jackson.core + jackson-core + 2.1.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.1.2 + + org.slf4j slf4j-api ${org.slf4j.version} + + ch.qos.logback + logback-classic + + ${logback.version} + org.slf4j - slf4j-log4j12 + jcl-over-slf4j + ${org.slf4j.version} - - - commons-fileupload - commons-fileupload - 1.3.1 - - + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + junit @@ -111,36 +156,19 @@ ${mockito.version} test + + com.jayway.jsonpath + json-path + 2.2.0 + test + org.springframework spring-test ${org.springframework.version} test - - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - - - - - com.fasterxml.jackson.core - jackson-core - 2.1.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.1.2 - - + @@ -210,7 +238,7 @@ - + 4.2.5.RELEASE @@ -220,8 +248,9 @@ 4.3.11.Final 5.1.38 - 1.7.13 - 1.1.3 + 1.7.21 + 1.1.5 + 5.2.2.Final @@ -240,9 +269,9 @@ 2.19.1 2.7 1.4.18 - + 1.8.7 - + \ No newline at end of file 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/resources/logback.xml b/spring-mvc-java/src/main/resources/logback.xml index 1146dade63..e0721aa890 100644 --- a/spring-mvc-java/src/main/resources/logback.xml +++ b/spring-mvc-java/src/main/resources/logback.xml @@ -2,7 +2,8 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + + %date [%thread] %-5level %logger{6} - %message%n 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 + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java new file mode 100644 index 0000000000..c1e79a2a63 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java @@ -0,0 +1,42 @@ +package com.baeldung.web.controller; + +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.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +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.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class EmployeeTest { + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); + } + + @Test + public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception { + mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print()); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java new file mode 100644 index 0000000000..19806e0559 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java @@ -0,0 +1,51 @@ +package com.baeldung.web.controller; + +import org.junit.Before; +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.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.model.Employee; +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class EmployeeTestWithoutMockMvc { + + @Autowired + private EmployeeController employeeController; + + @Before + public void setup() { + employeeController.initEmployees(); + } + + @Test + public void whenInitEmployees_thenVerifyValuesInitiation() { + + Employee employee1 = employeeController.employeeMap.get(1L); + Employee employee2 = employeeController.employeeMap.get(2L); + Employee employee3 = employeeController.employeeMap.get(3L); + + Assert.assertTrue(employee1.getId() == 1L); + Assert.assertTrue(employee1.getName().equals("John")); + Assert.assertTrue(employee1.getContactNumber().equals("223334411")); + Assert.assertTrue(employee1.getWorkingArea().equals("rh")); + + Assert.assertTrue(employee2.getId() == 2L); + Assert.assertTrue(employee2.getName().equals("Peter")); + Assert.assertTrue(employee2.getContactNumber().equals("22001543")); + Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); + + Assert.assertTrue(employee3.getId() == 3L); + Assert.assertTrue(employee3.getName().equals("Mike")); + Assert.assertTrue(employee3.getContactNumber().equals("223334411")); + Assert.assertTrue(employee3.getWorkingArea().equals("admin")); + } + +} 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..d1d1167369 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.web.controller; + + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +import javax.servlet.ServletContext; + +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 com.baeldung.spring.web.config.ApplicationConfig; + +@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-java/src/test/resources/log4j.properties b/spring-mvc-java/src/test/resources/log4j.properties deleted file mode 100644 index 6193d62fd8..0000000000 --- a/spring-mvc-java/src/test/resources/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=WARN, A1 - -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/spring-mvc-java/src/test/resources/logback-test.xml b/spring-mvc-java/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..e0721aa890 --- /dev/null +++ b/spring-mvc-java/src/test/resources/logback-test.xml @@ -0,0 +1,21 @@ + + + + + + %date [%thread] %-5level %logger{6} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file 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 @@ - - - - - - - diff --git a/spring-mvc-no-xml/.settings/.jsdtscope b/spring-mvc-no-xml/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-mvc-no-xml/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-mvc-no-xml/.settings/org.eclipse.jdt.core.prefs b/spring-mvc-no-xml/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 5ff04b9f96..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.jdt.ui.prefs b/spring-mvc-no-xml/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.m2e.core.prefs b/spring-mvc-no-xml/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.m2e.wtp.prefs b/spring-mvc-no-xml/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.wst.common.component b/spring-mvc-no-xml/.settings/org.eclipse.wst.common.component deleted file mode 100644 index a37385bf84..0000000000 --- a/spring-mvc-no-xml/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-mvc-no-xml/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-mvc-no-xml/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-mvc-no-xml/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-mvc-no-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-mvc-no-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-mvc-no-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.wst.validation.prefs b/spring-mvc-no-xml/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-mvc-no-xml/.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-no-xml/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-mvc-no-xml/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-mvc-no-xml/.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-web-vs-initializer/.gitignore b/spring-mvc-web-vs-initializer/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-web-vs-initializer/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/pom.xml b/spring-mvc-web-vs-initializer/pom.xml new file mode 100644 index 0000000000..0d735e7188 --- /dev/null +++ b/spring-mvc-web-vs-initializer/pom.xml @@ -0,0 +1,201 @@ + + 4.0.0 + com.baeldung + spring-mvc-web-vs-initializer + 0.1-SNAPSHOT + + spring-mvc-web-vs-initializer + war + + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-context + + + + + + javax.servlet + javax.servlet-api + provided + + + + javax.servlet + jstl + runtime + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + + + + + + org.springframework + spring-test + test + + + + junit + junit + test + + + + org.assertj + assertj-core + 3.5.1 + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.easymock + easymock + 3.4 + test + + + + + + + + + + org.springframework + spring-framework-bom + ${org.springframework.version} + pom + import + + + + org.springframework + spring-core + ${org.springframework.version} + + + + + + + + spring-mvc-web-vs-initializer + + + src/main/resources + true + + + + + + + + 4.3.1.RELEASE + 4.0.4.RELEASE + 3.20.0-GA + 1.2 + + + 4.3.11.Final + 5.1.38 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + + + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..21e33820ca --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/AppInitializer.java @@ -0,0 +1,26 @@ +package org.baeldung.config; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("org.baeldung.config"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("java-servlet", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/java-servlet/*"); + } + +} diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..d460113458 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,25 @@ +package org.baeldung.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.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.baeldung.controller.java") +public class MvcConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + + return viewResolver; + } + +} diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java new file mode 100644 index 0000000000..c979c88b34 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/java/JavaController.java @@ -0,0 +1,18 @@ +package org.baeldung.controller.java; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class JavaController { + + @RequestMapping(value = "/endpoint") + public ModelAndView handleRequestFromJavaConfiguredServlet() { + ModelAndView mv = new ModelAndView(); + mv.setViewName("from-java"); + + return mv; + } + +} \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java new file mode 100644 index 0000000000..bdefc1781c --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/java/org/baeldung/controller/xml/XmlController.java @@ -0,0 +1,18 @@ +package org.baeldung.controller.xml; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class XmlController { + + @RequestMapping(value = "/endpoint") + public ModelAndView handleRequestFromXmlConfiguredServlet() { + ModelAndView mv = new ModelAndView(); + mv.setViewName("from-xml"); + + return mv; + } + +} \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml b/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp new file mode 100644 index 0000000000..e54d7520dc --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-java.jsp @@ -0,0 +1,7 @@ + + + + +

Java

+ + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp new file mode 100644 index 0000000000..986010c183 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/view/from-xml.jsp @@ -0,0 +1,7 @@ + + + + +

XML

+ + \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..9bebc263be --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + xml-servlet + + org.springframework.web.servlet.DispatcherServlet + + 1 + + contextConfigLocation + classpath*:mvc-configuration.xml + + + + + xml-servlet + /xml-servlet/* + + + diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java new file mode 100644 index 0000000000..99b5ef8c2f --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java @@ -0,0 +1,45 @@ +package org.baeldung.controller; + +import org.baeldung.config.MvcConfig; +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(loader=AnnotationConfigWebContextLoader.class, classes = MvcConfig.class) +public class JavaServletTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void testJavaEndpoint() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/endpoint")) + .andReturn() + .getModelAndView(); + + // validate view name + Assert.assertSame(mv.getViewName(), "from-java"); + } + +} diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java new file mode 100644 index 0000000000..e7695e36c0 --- /dev/null +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java @@ -0,0 +1,44 @@ +package org.baeldung.controller; + +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.GenericXmlWebContextLoader; +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(loader=GenericXmlWebContextLoader.class, locations = "classpath*:mvc-configuration.xml") +public class XmlServletTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void testXmlEndpoint() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/endpoint")) + .andReturn() + .getModelAndView(); + + // validate view name + Assert.assertSame(mv.getViewName(), "from-xml"); + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java deleted file mode 100644 index df70780a87..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.mock; - -import java.util.ArrayList; -import java.util.List; - -import org.baeldung.web.vo.Student; - -public class MockStudentData { - - private static List studentList = new ArrayList<>(); - - static { - studentList.add(new Student("1", "Bryan", "Male", 20)); - studentList.add(new Student("2", "Ben", "Male", 22)); - studentList.add(new Student("3", "Lisa", "Female", 24)); - studentList.add(new Student("4", "Sarah", "Female", 26)); - studentList.add(new Student("5", "Jay", "Male", 20)); - studentList.add(new Student("6", "John", "Male", 22)); - studentList.add(new Student("7", "Jordan", "Male", 24)); - studentList.add(new Student("8", "Rob", "Male", 26)); - studentList.add(new Student("9", "Will", "Male", 20)); - studentList.add(new Student("10", "Shawn", "Male", 22)); - studentList.add(new Student("11", "Taylor", "Female", 24)); - studentList.add(new Student("12", "Venus", "Female", 26)); - studentList.add(new Student("13", "Vince", "Male", 20)); - studentList.add(new Student("14", "Carol", "Female", 22)); - studentList.add(new Student("15", "Joana", "Female", 24)); - studentList.add(new Student("16", "Dion", "Male", 26)); - studentList.add(new Student("17", "Evans", "Male", 20)); - studentList.add(new Student("18", "Bart", "Male", 22)); - studentList.add(new Student("19", "Jenny", "Female", 24)); - studentList.add(new Student("20", "Kristine", "Female", 26)); - } - - public static List getMockDataStudents(){ - return studentList; - } - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java deleted file mode 100644 index 5ff24ec0f2..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.web.rest; - -import org.baeldung.web.service.StudentService; -import org.baeldung.web.vo.Student; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class StudentDirectoryRestController { - - @Autowired - private StudentService service; - - @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET) - public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size){ - - Page resultPage = service.findPaginated(page, size); - - return resultPage; - } - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java deleted file mode 100644 index 5c4487254a..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.web.service; - -import org.baeldung.web.vo.Student; - -public interface StudentService extends IOperations{ - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java deleted file mode 100644 index 3b6dda6fb1..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.service; - -import java.util.List; - -import org.baeldung.mock.MockStudentData; -import org.baeldung.web.exception.MyResourceNotFoundException; -import org.baeldung.web.vo.Student; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Service; - -@Service -public class StudentServiceImpl implements StudentService { - - private List mockDataStudent = MockStudentData.getMockDataStudents(); - - @Override - public Page findPaginated(int page, int size){ - Page studentPage = getPage(page, size); - return studentPage; - } - - private Page getPage(int page, int size) { - page = page != 0?page - 1:page; - int from = Math.max(0, page * size); - int to = Math.min(mockDataStudent.size(), (page + 1) * size); - if(from > to){ - throw new MyResourceNotFoundException("page number is higher than total pages."); - } - return new PageImpl(mockDataStudent.subList(from, to), - new PageRequest(page,size), - mockDataStudent.size()); - } - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java deleted file mode 100644 index 11c503815d..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.baeldung.web.vo; - -import java.io.Serializable; - -public class Student implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public Student() { - } - - public Student(String studentId, String name, String gender, Integer age) { - super(); - this.studentId = studentId; - this.name = name; - this.gender = gender; - this.age = age; - } - - private String studentId; - private String name; - private String gender; - private Integer age; - - public String getStudentId() { - return studentId; - } - - public void setStudentId(String studentId) { - this.studentId = studentId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties b/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties deleted file mode 100644 index a9bf6ca218..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.contextPath=/StudentDirectory \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html deleted file mode 100644 index 56a1273588..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - -
-
-
- - \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java deleted file mode 100644 index 3e476bf0d0..0000000000 --- a/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.web.service; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.apache.commons.lang3.RandomStringUtils; -import org.baeldung.web.main.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import io.restassured.RestAssured; -import io.restassured.response.Response; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebAppConfiguration -@IntegrationTest("server.port:8080") -public class StudentServiceTest{ - - private String getURL() { - return "/StudentDirectory/student/get"; - } - - @Test - public void whenResourcesAreRetrievedPaged_then200IsReceived(){ - Response response = RestAssured.given().get(getURL()+ "?page=0&size=2").andReturn(); - - assertTrue(response.getStatusCode() == 200 ); - } - - @Test - public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived(){ - String url = getURL()+ "?page=" + RandomStringUtils.randomNumeric(5) + "&size=2"; - Response response = RestAssured.given().get(url); - - assertTrue(response.getStatusCode() == 500 ); - } - - @Test - public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources(){ - Response response = RestAssured.given().get(getURL() + "?page=1&size=2" ); - assertFalse(response.getBody().jsonPath().getList("content").isEmpty() ); - } - -} diff --git a/spring-rest-angular-pagination/StudentDirectory/pom.xml b/spring-rest-angular/pom.xml similarity index 87% rename from spring-rest-angular-pagination/StudentDirectory/pom.xml rename to spring-rest-angular/pom.xml index 8dab851ef2..331c9a644c 100644 --- a/spring-rest-angular-pagination/StudentDirectory/pom.xml +++ b/spring-rest-angular/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - angular-spring-rest-sample - angular-spring-rest-sample + spring-rest-angular + spring-rest-angular com.baeldung 1.0 war @@ -13,9 +13,6 @@ spring-boot-starter-parent 1.3.3.RELEASE - - 1.12.2.RELEASE - org.springframework.boot @@ -30,6 +27,15 @@ org.springframework.data spring-data-commons + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + org.springframework spring-test @@ -66,6 +72,7 @@ angular-spring-rest-sample + org.apache.maven.plugins maven-compiler-plugin @@ -74,6 +81,7 @@ 1.8 + org.apache.maven.plugins maven-war-plugin @@ -81,6 +89,7 @@ false +
diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java new file mode 100644 index 0000000000..b1aafb583a --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/dao/StudentRepository.java @@ -0,0 +1,8 @@ +package org.baeldung.web.dao; + +import org.baeldung.web.entity.Student; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentRepository extends JpaRepository { + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java new file mode 100644 index 0000000000..0a0b60d87d --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/entity/Student.java @@ -0,0 +1,69 @@ +package org.baeldung.web.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Student implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public Student() { + } + + public Student(long id, String name, String gender, Integer age) { + super(); + this.id = id; + this.name = name; + this.gender = gender; + this.age = age; + } + + @Id + private long id; + @Column(nullable = false) + private String name; + @Column(nullable = false) + private String gender; + @Column(nullable = false) + private Integer age; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java similarity index 77% rename from spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java rename to spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java index 3105d1cb11..740caec59e 100644 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java @@ -3,11 +3,11 @@ package org.baeldung.web.exception; public class MyResourceNotFoundException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 4088649120307193208L; + * + */ + private static final long serialVersionUID = 4088649120307193208L; - public MyResourceNotFoundException() { + public MyResourceNotFoundException() { super(); } @@ -23,5 +23,4 @@ public class MyResourceNotFoundException extends RuntimeException { super(cause); } - } diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java similarity index 88% rename from spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java rename to spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java index b3b0dad98a..d6fe719311 100644 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java @@ -4,16 +4,15 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; import org.springframework.web.filter.ShallowEtagHeaderFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@Import(PersistenceConfig.class) public class Application extends WebMvcConfigurerAdapter { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } @@ -22,5 +21,5 @@ public class Application extends WebMvcConfigurerAdapter { public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { return new ShallowEtagHeaderFilter(); } - + } diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java new file mode 100644 index 0000000000..df1240f270 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/PersistenceConfig.java @@ -0,0 +1,33 @@ +package org.baeldung.web.main; + +import javax.sql.DataSource; + +import org.springframework.boot.orm.jpa.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@EnableJpaRepositories("org.baeldung.web.dao") +@ComponentScan(basePackages = { "org.baeldung.web" }) +@EntityScan("org.baeldung.web.entity") +@Configuration +public class PersistenceConfig { + + @Bean + public JdbcTemplate getJdbcTemplate() { + return new JdbcTemplate(dataSource()); + } + + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).addScript("db/sql/data.sql").build(); + return db; + } + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java new file mode 100644 index 0000000000..dc295a3d97 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -0,0 +1,29 @@ +package org.baeldung.web.rest; + +import org.baeldung.web.entity.Student; +import org.baeldung.web.exception.MyResourceNotFoundException; +import org.baeldung.web.service.StudentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class StudentDirectoryRestController { + + @Autowired + private StudentService service; + + @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json") + public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) { + + Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + return resultPage; + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java similarity index 64% rename from spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java rename to spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java index 0b408106ce..2176c0bb70 100644 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - Page findPaginated(int page, int size); + public Page findPaginated(final int page, final int size); } diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java new file mode 100644 index 0000000000..1b194f76e2 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentService.java @@ -0,0 +1,7 @@ +package org.baeldung.web.service; + +import org.baeldung.web.entity.Student; + +public interface StudentService extends IOperations { + +} diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java new file mode 100644 index 0000000000..c7bcdc5bd5 --- /dev/null +++ b/spring-rest-angular/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -0,0 +1,21 @@ +package org.baeldung.web.service; + +import org.baeldung.web.dao.StudentRepository; +import org.baeldung.web.entity.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +public class StudentServiceImpl implements StudentService { + + @Autowired + private StudentRepository dao; + + @Override + public Page findPaginated(int page, int size) { + return dao.findAll(new PageRequest(page, size)); + } + +} diff --git a/spring-rest-angular/src/main/resources/application.properties b/spring-rest-angular/src/main/resources/application.properties new file mode 100644 index 0000000000..e24db89c8f --- /dev/null +++ b/spring-rest-angular/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.contextPath=/ +spring.h2.console.enabled=true +logging.level.org.hibernate.SQL=info +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-rest-angular/src/main/resources/db/sql/data.sql b/spring-rest-angular/src/main/resources/db/sql/data.sql new file mode 100644 index 0000000000..418381a681 --- /dev/null +++ b/spring-rest-angular/src/main/resources/db/sql/data.sql @@ -0,0 +1,47 @@ +CREATE TABLE student ( + id INTEGER PRIMARY KEY, + name VARCHAR(30), + gender VARCHAR(10), + age INTEGER +); + +INSERT INTO student (id,name,gender,age) +VALUES (1,'Bryan', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (2, 'Ben', 'Male', 22); +INSERT INTO student (id,name,gender,age) +VALUES (3,'Lisa', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (4,'Sarah', 'Female',20); +INSERT INTO student (id,name,gender,age) +VALUES (5,'Jay', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (6,'John', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (7,'Jordan', 'Male',24); +INSERT INTO student (id,name,gender,age) +VALUES (8,'Rob', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (9,'Will', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (10,'Shawn', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (11,'Taylor', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (12,'Venus', 'Female',26); +INSERT INTO student (id,name,gender,age) +VALUES (13,'Vince', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (14,'Carol', 'Female',22); +INSERT INTO student (id,name,gender,age) +VALUES (15,'Joana', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (16,'Dion', 'Male',26); +INSERT INTO student (id,name,gender,age) +VALUES (17,'Evans', 'Male',20); +INSERT INTO student (id,name,gender,age) +VALUES (18,'Bart', 'Male',22); +INSERT INTO student (id,name,gender,age) +VALUES (19,'Jenny', 'Female',24); +INSERT INTO student (id,name,gender,age) +VALUES (20,'Kristine', 'Female',26); \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml similarity index 99% rename from spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml rename to spring-rest-angular/src/main/webapp/WEB-INF/web.xml index ff65bd6b96..6adf31503f 100644 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest-angular/src/main/webapp/WEB-INF/web.xml @@ -3,7 +3,7 @@ xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> - + index.html diff --git a/spring-rest-angular/src/main/webapp/index.html b/spring-rest-angular/src/main/webapp/index.html new file mode 100644 index 0000000000..49e0d6393d --- /dev/null +++ b/spring-rest-angular/src/main/webapp/index.html @@ -0,0 +1,17 @@ + + + + + + + + + +
+
+
+ + \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js b/spring-rest-angular/src/main/webapp/view/app.js similarity index 93% rename from spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js rename to spring-rest-angular/src/main/webapp/view/app.js index 522c49c8cb..a41026d2c3 100644 --- a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js +++ b/spring-rest-angular/src/main/webapp/view/app.js @@ -17,8 +17,9 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude paginationPageSizes: [5, 10, 20], paginationPageSize: paginationOptions.pageSize, enableColumnMenus:false, + useExternalPagination: true, columnDefs: [ - { name: 'studentId' }, + { name: 'id' }, { name: 'name' }, { name: 'gender' }, { name: 'age' } @@ -41,6 +42,7 @@ app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,Stude app.service('StudentService',['$http', function ($http) { function getStudents(pageNumber,size) { + pageNumber = pageNumber > 0?pageNumber - 1:0; return $http({ method: 'GET', url: 'student/get?page='+pageNumber+'&size='+size diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java new file mode 100644 index 0000000000..1199f15ab3 --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java @@ -0,0 +1,65 @@ +package org.baeldung.web.service; + +import org.apache.commons.lang3.RandomStringUtils; +import org.baeldung.web.main.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import static io.restassured.RestAssured.*; +import static org.hamcrest.core.IsCollectionContaining.*; +import static org.hamcrest.core.Is.*; +import static org.hamcrest.core.IsEqual.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest("server.port:8888") +public class StudentServiceTest { + + private static final String ENDPOINT = "http://localhost:8888/student/get"; + + @Test + public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("content.name", hasItems("Bryan", "Ben")); + } + + @Test + public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); + } + + @Test + public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); + } + + @Test + public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { + given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); + } + + @Test + public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { + given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); + } + + @Test + public void givenRequestForStudents_whenPageNotValid_thenExpect500() { + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); + } + + @Test + public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { + given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); + } + + @Test + public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); + } + +} diff --git a/spring-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-rest/.settings/.jsdtscope b/spring-rest/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-rest/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-rest/.settings/org.eclipse.jdt.core.prefs b/spring-rest/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/spring-rest/.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/spring-rest/.settings/org.eclipse.jdt.ui.prefs b/spring-rest/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-rest/.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-rest/.settings/org.eclipse.m2e.core.prefs b/spring-rest/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-rest/.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-rest/.settings/org.eclipse.m2e.wtp.prefs b/spring-rest/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-rest/.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-rest/.settings/org.eclipse.wst.common.component b/spring-rest/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 8bb4ef127a..0000000000 --- a/spring-rest/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 8a1c189419..0000000000 --- a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-rest/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-rest/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-rest/.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-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-rest/.settings/org.eclipse.wst.validation.prefs b/spring-rest/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-rest/.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-rest/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-rest/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-rest/.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-rest/pom.xml b/spring-rest/pom.xml index e28f7e7e33..0c0d6219dd 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -15,10 +15,7 @@ - - org.springframework.boot - spring-boot-starter-security - + org.springframework.boot spring-boot-starter-thymeleaf @@ -74,6 +71,11 @@ com.fasterxml.jackson.core jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.thoughtworks.xstream @@ -146,11 +148,19 @@ spring-test + + com.jayway.restassured + rest-assured + ${rest-assured.version} + + + com.google.protobuf protobuf-java 2.6.1 + com.esotericsoftware kryo @@ -231,10 +241,6 @@ 4.3.11.Final 5.1.39 - - - 2.7.2 - 5.2.2.Final diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index 120f1b272a..d116148f09 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -1,53 +1,58 @@ -package org.baeldung.config; - -import java.text.SimpleDateFormat; -import java.util.List; - -import org.baeldung.config.converter.KryoHttpMessageConverter; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; -import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; -import org.springframework.oxm.xstream.XStreamMarshaller; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) -public class WebConfig extends WebMvcConfigurerAdapter { - - public WebConfig() { - super(); - } - - // - - @Override - public void configureMessageConverters(final List> messageConverters) { - messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); - - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); - builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); - messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); - // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); - messageConverters.add(new ProtobufHttpMessageConverter()); - messageConverters.add(new KryoHttpMessageConverter()); - super.configureMessageConverters(messageConverters); - } - - private HttpMessageConverter createXmlHttpMessageConverter() { - final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - - final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); - xmlConverter.setMarshaller(xstreamMarshaller); - xmlConverter.setUnmarshaller(xstreamMarshaller); - - return xmlConverter; - } - -} +package org.baeldung.config; + +import java.text.SimpleDateFormat; +import java.util.List; + +import org.baeldung.config.converter.KryoHttpMessageConverter; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; +import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; +import org.springframework.oxm.xstream.XStreamMarshaller; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/* + * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml + * + */ + +@Configuration +@EnableWebMvc +@ComponentScan({ "org.baeldung.web" }) +public class WebConfig extends WebMvcConfigurerAdapter { + + public WebConfig() { + super(); + } + + // + + @Override + public void configureMessageConverters(final List> messageConverters) { + messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + + final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); + builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); + messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); + // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + messageConverters.add(new ProtobufHttpMessageConverter()); + messageConverters.add(new KryoHttpMessageConverter()); + super.configureMessageConverters(messageConverters); + } + + private HttpMessageConverter createXmlHttpMessageConverter() { + final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); + + final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); + xmlConverter.setMarshaller(xstreamMarshaller); + xmlConverter.setUnmarshaller(xstreamMarshaller); + + return xmlConverter; + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java new file mode 100644 index 0000000000..d640ac671d --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java @@ -0,0 +1,16 @@ +package org.baeldung.web.controller; + +import org.baeldung.web.dto.Company; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CompanyController { + + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index 386c64bb09..dd1e3ca222 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -35,7 +35,6 @@ public class FooController { @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { - System.out.println(foo); return foo; } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java new file mode 100644 index 0000000000..7d62cc0c66 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -0,0 +1,13 @@ +package org.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-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java index 1d4aff2ebf..348ee6d596 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java @@ -5,5 +5,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message") public class ForbiddenException extends RuntimeException { + private static final long serialVersionUID = 6826605655586311552L; } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java new file mode 100644 index 0000000000..c7d0718140 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java @@ -0,0 +1,38 @@ +package org.baeldung.web.dto; + +public class Company { + + private long id; + private String name; + + public Company() { + super(); + } + + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 5afc637ece..21136b62c6 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -8,7 +8,24 @@ - + + + + + + + + + + + diff --git a/spring-rest/src/main/webapp/WEB-INF/company.html b/spring-rest/src/main/webapp/WEB-INF/company.html new file mode 100644 index 0000000000..d2072bfd3c --- /dev/null +++ b/spring-rest/src/main/webapp/WEB-INF/company.html @@ -0,0 +1,44 @@ + + + + + Company Data + + + + + + + +
+ + + \ No newline at end of file diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index 01e7620c44..a439de8a05 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -8,7 +8,7 @@ Spring MVC Application - + contextClass org.springframework.web.context.support.AnnotationConfigWebApplicationContext @@ -18,7 +18,7 @@ contextConfigLocation org.baeldung.config - + org.springframework.web.context.ContextLoaderListener diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java new file mode 100644 index 0000000000..fd349f1e44 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java @@ -0,0 +1,62 @@ +package org.baeldung.web.test; + +import static org.hamcrest.Matchers.equalTo; + +import org.junit.Test; + +import com.jayway.restassured.RestAssured; + +public class RequestMappingLiveTest { + private static String BASE_URI = "http://localhost:8080/spring-rest/ex/"; + + @Test + public void givenSimplePath_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos").then().assertThat().body(equalTo("Simple Get some Foos")); + } + + @Test + public void whenPostFoos_thenOk() { + RestAssured.given().accept("text/html").post(BASE_URI + "foos").then().assertThat().body(equalTo("Post some Foos")); + } + + @Test + public void givenOneHeader_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").header("key", "val").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header")); + } + + @Test + public void givenMultipleHeaders_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").headers("key1", "val1", "key2", "val2").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header")); + } + + @Test + public void givenAcceptHeader_whenGetFoos_thenOk() { + RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New")); + } + + @Test + public void givenPathVariable_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos/1").then().assertThat().body(equalTo("Get a specific Foo with id=1")); + } + + @Test + public void givenMultiplePathVariable_whenGetFoos_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "foos/1/bar/2").then().assertThat().body(equalTo("Get a specific Bar with id=2 from a Foo with id=1")); + } + + @Test + public void givenPathVariable_whenGetBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "bars/1").then().assertThat().body(equalTo("Get a specific Bar with id=1")); + } + + @Test + public void givenParams_whenGetBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "bars?id=100&second=something").then().assertThat().body(equalTo("Get a specific Bar with id=100")); + } + + @Test + public void whenGetFoosOrBars_thenOk() { + RestAssured.given().accept("text/html").get(BASE_URI + "advanced/foos").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars")); + RestAssured.given().accept("text/html").get(BASE_URI + "advanced/bars").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars")); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java index 1536f14bc8..1dfe509c09 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java @@ -3,9 +3,7 @@ package org.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import org.baeldung.config.converter.KryoHttpMessageConverter; import org.baeldung.web.dto.Foo; @@ -17,11 +15,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; -import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; -import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.client.RestTemplate; /** @@ -50,7 +44,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); @@ -67,7 +60,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @@ -83,7 +75,6 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { public void givenConsumingXml_whenWritingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(getMessageConverters()); final Foo resource = new Foo(4, "jason"); final HttpHeaders headers = new HttpHeaders(); @@ -129,20 +120,4 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { assertThat(resource, notNullValue()); } - // UTIL - - private List> getMessageConverters() { - final List> converters = new ArrayList>(); - - final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); - xmlConverter.setMarshaller(xstreamMarshaller); - xmlConverter.setUnmarshaller(xstreamMarshaller); - - converters.add(xmlConverter); - converters.add(new MappingJackson2HttpMessageConverter()); - - return converters; - } - } diff --git a/spring-security-basic-auth/README.md b/spring-security-basic-auth/README.md index f3c29e1777..37ea545a9b 100644 --- a/spring-security-basic-auth/README.md +++ b/spring-security-basic-auth/README.md @@ -3,7 +3,7 @@ ## Spring Security with Basic Authentication Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD index 2a87b46021..5ac974203b 100644 --- a/spring-security-client/README.MD +++ b/spring-security-client/README.MD @@ -1,2 +1,2 @@ ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 2a87b46021..5ac974203b 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -1,2 +1,2 @@ ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java index 86b81cdcee..112d502105 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -1,8 +1,5 @@ package org.baeldung.persistence.model; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; import java.util.Set; import javax.persistence.Column; @@ -16,14 +13,8 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - @Entity -public class User implements UserDetails { - - private static final long serialVersionUID = 1L; +public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -57,7 +48,6 @@ public class User implements UserDetails { this.id = id; } - @Override public String getUsername() { return username; } @@ -66,7 +56,6 @@ public class User implements UserDetails { this.username = username; } - @Override public String getPassword() { return password; } @@ -93,37 +82,6 @@ public class User implements UserDetails { // - @Override - public Collection getAuthorities() { - final List authorities = new ArrayList(); - for (final Privilege privilege : this.getPrivileges()) { - authorities.add(new SimpleGrantedAuthority(privilege.getName())); - } - return authorities; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } - - // - @Override public String toString() { final StringBuilder builder = new StringBuilder(); diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java index a3f4644592..2d84536a14 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java @@ -16,7 +16,7 @@ public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot i // public boolean isMember(Long OrganizationId) { - final User user = (User) this.getPrincipal(); + final User user = ((MyUserPrincipal) this.getPrincipal()).getUser(); return user.getOrganization().getId().longValue() == OrganizationId.longValue(); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java index e81f9f8939..5d96673a8f 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java @@ -10,17 +10,10 @@ public class CustomPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { - System.out.println(auth); if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) { return false; } - String targetType = ""; - if (targetDomainObject instanceof String) { - targetType = targetDomainObject.toString().toUpperCase(); - } else { - targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); - System.out.println(targetType); - } + final String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); return hasPrivilege(auth, targetType, permission.toString().toUpperCase()); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java index a09d166798..4d3561b325 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java @@ -47,6 +47,14 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati throw new RuntimeException("method hasAuthority() not allowed"); } + // + public boolean isMember(Long OrganizationId) { + final User user = ((MyUserPrincipal) this.getPrincipal()).getUser(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + @Override public final boolean hasAnyAuthority(String... authorities) { return hasAnyAuthorityName(null, authorities); @@ -168,14 +176,6 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati return defaultRolePrefix + role; } - // - public boolean isMember(Long OrganizationId) { - final User user = (User) this.getPrincipal(); - return user.getOrganization().getId().longValue() == OrganizationId.longValue(); - } - - // - @Override public Object getFilterObject() { return this.filterObject; diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java index 19276a906e..685219728f 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -26,6 +26,6 @@ public class MyUserDetailsService implements UserDetailsService { if (user == null) { throw new UsernameNotFoundException(username); } - return user; + return new MyUserPrincipal(user); } } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java new file mode 100644 index 0000000000..437bb02cdb --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java @@ -0,0 +1,72 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.baeldung.persistence.model.Privilege; +import org.baeldung.persistence.model.User; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +public class MyUserPrincipal implements UserDetails { + + private static final long serialVersionUID = 1L; + + private final User user; + + // + + public MyUserPrincipal(User user) { + this.user = user; + } + + // + + @Override + public String getUsername() { + return user.getUsername(); + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public Collection getAuthorities() { + final List authorities = new ArrayList(); + for (final Privilege privilege : user.getPrivileges()) { + authorities.add(new SimpleGrantedAuthority(privilege.getName())); + } + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + // + + public User getUser() { + return user; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java index 7e279907c6..4752f7bdd9 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java @@ -21,7 +21,8 @@ public class MainController { @Autowired private OrganizationRepository organizationRepository; - @PreAuthorize("hasPermission('Foo', 'read')") + // @PostAuthorize("hasPermission(returnObject, 'read')") + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { diff --git a/spring-security-mvc-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-mvc-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-mvc-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-mvc-custom/.settings/.jsdtscope b/spring-security-mvc-custom/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-mvc-custom/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-custom/.settings/org.eclipse.jdt.core.prefs b/spring-security-mvc-custom/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/spring-security-mvc-custom/.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/spring-security-mvc-custom/.settings/org.eclipse.jdt.ui.prefs b/spring-security-mvc-custom/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/.settings/org.eclipse.m2e.core.prefs b/spring-security-mvc-custom/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-mvc-custom/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/.settings/org.eclipse.wst.common.component b/spring-security-mvc-custom/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 0a268a3d82..0000000000 --- a/spring-security-mvc-custom/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-mvc-custom/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-mvc-custom/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-mvc-custom/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-custom/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-mvc-custom/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-mvc-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-mvc-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-mvc-custom/.settings/org.eclipse.wst.validation.prefs b/spring-security-mvc-custom/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-mvc-custom/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-mvc-custom/.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-security-mvc-custom/README.md b/spring-security-mvc-custom/README.md index cbf5fc6a97..14bac6c454 100644 --- a/spring-security-mvc-custom/README.md +++ b/spring-security-mvc-custom/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) diff --git a/spring-security-mvc-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-mvc-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-mvc-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-mvc-digest-auth/.settings/.jsdtscope b/spring-security-mvc-digest-auth/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-mvc-digest-auth/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-digest-auth/.settings/org.eclipse.jdt.core.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index f78b9bf1c1..0000000000 --- a/spring-security-mvc-digest-auth/.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=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-security-mvc-digest-auth/.settings/org.eclipse.jdt.ui.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/.settings/org.eclipse.m2e.core.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/.settings/org.eclipse.wst.common.component b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 0d189e36cd..0000000000 --- a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.validation.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-mvc-digest-auth/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-mvc-digest-auth/.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-security-mvc-digest-auth/README.md b/spring-security-mvc-digest-auth/README.md index 21835266bf..8b79b6b113 100644 --- a/spring-security-mvc-digest-auth/README.md +++ b/spring-security-mvc-digest-auth/README.md @@ -3,7 +3,7 @@ ## Spring Security with Digest Authentication Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication) diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index 1eb3b75405..fe6a667c40 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -2,7 +2,7 @@ ## Spring Security with LDAP Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) diff --git a/spring-security-mvc-login/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-mvc-login/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-mvc-login/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-mvc-login/.settings/.jsdtscope b/spring-security-mvc-login/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-mvc-login/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-login/.settings/org.eclipse.jdt.core.prefs b/spring-security-mvc-login/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/spring-security-mvc-login/.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/spring-security-mvc-login/.settings/org.eclipse.jdt.ui.prefs b/spring-security-mvc-login/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/.settings/org.eclipse.m2e.core.prefs b/spring-security-mvc-login/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-mvc-login/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/.settings/org.eclipse.wst.common.component b/spring-security-mvc-login/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 8b704170f8..0000000000 --- a/spring-security-mvc-login/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-mvc-login/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-mvc-login/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-mvc-login/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-login/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-mvc-login/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-mvc-login/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-mvc-login/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-mvc-login/.settings/org.eclipse.wst.validation.prefs b/spring-security-mvc-login/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-mvc-login/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-mvc-login/.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-security-mvc-login/README.md b/spring-security-mvc-login/README.md index 448c25d27b..7cddc42e1d 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Form Login](http://www.baeldung.com/spring-security-login) diff --git a/spring-security-mvc-persisted-remember-me/README.md b/spring-security-mvc-persisted-remember-me/README.md index 0d5f4f5f0e..f910c3f62b 100644 --- a/spring-security-mvc-persisted-remember-me/README.md +++ b/spring-security-mvc-persisted-remember-me/README.md @@ -3,7 +3,7 @@ ## Spring Security Persisted Remember Me Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) diff --git a/spring-security-mvc-session/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-mvc-session/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-mvc-session/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-mvc-session/.settings/.jsdtscope b/spring-security-mvc-session/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-mvc-session/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-session/.settings/org.eclipse.jdt.core.prefs b/spring-security-mvc-session/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/spring-security-mvc-session/.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/spring-security-mvc-session/.settings/org.eclipse.jdt.ui.prefs b/spring-security-mvc-session/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/.settings/org.eclipse.m2e.core.prefs b/spring-security-mvc-session/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-mvc-session/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/.settings/org.eclipse.wst.common.component b/spring-security-mvc-session/.settings/org.eclipse.wst.common.component deleted file mode 100644 index db01b7dfe4..0000000000 --- a/spring-security-mvc-session/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-mvc-session/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-mvc-session/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-mvc-session/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-mvc-session/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-mvc-session/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-mvc-session/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-mvc-session/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-mvc-session/.settings/org.eclipse.wst.validation.prefs b/spring-security-mvc-session/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-mvc-session/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-mvc-session/.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-security-mvc-session/README.md b/spring-security-mvc-session/README.md index 28f216c130..fc44209640 100644 --- a/spring-security-mvc-session/README.md +++ b/spring-security-mvc-session/README.md @@ -3,7 +3,7 @@ ## Spring Security Login Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) diff --git a/spring-security-rest-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-rest-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-rest-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-rest-basic-auth/.settings/.jsdtscope b/spring-security-rest-basic-auth/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-rest-basic-auth/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-basic-auth/.settings/org.eclipse.jdt.core.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.jdt.ui.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.m2e.core.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.wst.common.component b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.common.component deleted file mode 100644 index d852102ca2..0000000000 --- a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-rest-basic-auth/.settings/org.eclipse.wst.validation.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-rest-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-rest-basic-auth/.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-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 9621773d91..3bd46bdd2a 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -3,7 +3,7 @@ ## REST API with Basic Authentication - Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1) diff --git a/spring-security-rest-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-rest-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-rest-custom/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-rest-custom/.settings/.jsdtscope b/spring-security-rest-custom/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-rest-custom/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-custom/.settings/org.eclipse.jdt.core.prefs b/spring-security-rest-custom/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.jdt.ui.prefs b/spring-security-rest-custom/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.m2e.core.prefs b/spring-security-rest-custom/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-rest-custom/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.wst.common.component b/spring-security-rest-custom/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 3b22cb60bb..0000000000 --- a/spring-security-rest-custom/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-rest-custom/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-custom/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index c5c0da6037..0000000000 --- a/spring-security-rest-custom/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-custom/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-rest-custom/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-rest-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-rest-custom/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-rest-custom/.settings/org.eclipse.wst.validation.prefs b/spring-security-rest-custom/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-rest-custom/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-rest-custom/.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-security-rest-custom/README.md b/spring-security-rest-custom/README.md index 38dc638e8d..85f2b7532c 100644 --- a/spring-security-rest-custom/README.md +++ b/spring-security-rest-custom/README.md @@ -3,7 +3,7 @@ ## Spring Security for REST Example Project ###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring +The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider) diff --git a/spring-security-rest-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-rest-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-rest-digest-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-rest-digest-auth/.settings/.jsdtscope b/spring-security-rest-digest-auth/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-rest-digest-auth/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.jdt.core.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.jdt.ui.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.m2e.core.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.wst.common.component b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 128f61d711..0000000000 --- a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 8a1c189419..0000000000 --- a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.validation.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-rest-digest-auth/.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-security-rest-digest-auth/README.md b/spring-security-rest-digest-auth/README.md index 4fdc934fe5..3328bcb2e3 100644 --- a/spring-security-rest-digest-auth/README.md +++ b/spring-security-rest-digest-auth/README.md @@ -3,7 +3,7 @@ ## REST API with Digest Authentication - Example Project ###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication) diff --git a/spring-security-rest-full/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-rest-full/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-rest-full/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-rest-full/.settings/.jsdtscope b/spring-security-rest-full/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-rest-full/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-full/.settings/org.eclipse.jdt.core.prefs b/spring-security-rest-full/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 361cd318f6..0000000000 --- a/spring-security-rest-full/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,96 +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.methodParameters=do not generate -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-security-rest-full/.settings/org.eclipse.jdt.ui.prefs b/spring-security-rest-full/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/.settings/org.eclipse.m2e.core.prefs b/spring-security-rest-full/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-rest-full/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/.settings/org.eclipse.wst.common.component b/spring-security-rest-full/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 3b942952f2..0000000000 --- a/spring-security-rest-full/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/spring-security-rest-full/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-full/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-rest-full/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-rest-full/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-rest-full/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-rest-full/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-rest-full/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-rest-full/.settings/org.eclipse.wst.validation.prefs b/spring-security-rest-full/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-rest-full/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-rest-full/.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-security-rest-full/README.md b/spring-security-rest-full/README.md index 947d32e87c..1cbe1191a8 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -5,7 +5,7 @@ ### Courses The "REST With Spring" Classes: http://bit.ly/restwithspring -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index bc415d0455..77b11f1cb1 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -248,11 +248,11 @@ test - - org.hamcrest - hamcrest-core - test - + + + + + org.hamcrest hamcrest-library diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java new file mode 100644 index 0000000000..80af01aeeb --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.spring; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.request.RequestContextListener; + +public class ListenerConfig implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } +} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index 3e5d6435b3..57e9b32a62 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -1,10 +1,14 @@ package org.baeldung.spring; +import org.baeldung.web.interceptor.LoggerInterceptor; +import org.baeldung.web.interceptor.SessionTimerInterceptor; +import org.baeldung.web.interceptor.UserInterceptor; 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.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -12,27 +16,34 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("org.baeldung.web") @EnableWebMvc -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig extends WebMvcConfigurerAdapter{ - public WebConfig() { - super(); - } + public WebConfig() { + super(); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + // API + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/graph.html"); + registry.addViewController("/csrfHome.html"); + registry.addViewController("/homepage.html"); + } - // API @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/graph.html"); - registry.addViewController("/csrfHome.html"); - registry.addViewController("/homepage.html"); + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java index 64a29f20d3..e87d5f3dd4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java @@ -14,20 +14,20 @@ import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping(value = "/auth/") public class BankController { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @RequestMapping(value = "/transfer", method = RequestMethod.GET) - @ResponseBody - public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); - return amount; - } + @RequestMapping(value = "/transfer", method = RequestMethod.GET) + @ResponseBody + public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); + return amount; + } - // write - just for test - @RequestMapping(value = "/transfer", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.OK) - public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); + // write - just for test + @RequestMapping(value = "/transfer", method = RequestMethod.POST) + @ResponseStatus(HttpStatus.OK) + public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); - } + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 1e00d6350b..c50e80bec2 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -32,90 +32,90 @@ import com.google.common.base.Preconditions; @RequestMapping(value = "/auth/foos") public class FooController { - @Autowired - private ApplicationEventPublisher eventPublisher; + @Autowired + private ApplicationEventPublisher eventPublisher; - @Autowired - private IFooService service; + @Autowired + private IFooService service; - public FooController() { - super(); - } + public FooController() { + super(); + } - // API + // API - @RequestMapping(method = RequestMethod.GET, value = "/count") - @ResponseBody - @ResponseStatus(value = HttpStatus.OK) - public long count() { - return 2l; - } + @RequestMapping(method = RequestMethod.GET, value = "/count") + @ResponseBody + @ResponseStatus(value = HttpStatus.OK) + public long count() { + return 2l; + } - // read - one + // read - one - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); - return resourceById; - } + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } - // read - all + // read - all - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return service.findAll(); - } + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return service.findAll(); + } - @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) - @ResponseBody - public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - final Page resultPage = service.findPaginated(page, size); - if (page > resultPage.getTotalPages()) { - throw new MyResourceNotFoundException(); - } - eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); + @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) + @ResponseBody + public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { + final Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); - return resultPage.getContent(); - } + return resultPage.getContent(); + } - // write + // write - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Foo foo = service.create(resource); - final Long idOfCreatedResource = foo.getId(); + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + Preconditions.checkNotNull(resource); + final Foo foo = service.create(resource); + final Long idOfCreatedResource = foo.getId(); - eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); + eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); - return foo; - } + return foo; + } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { - Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); - service.update(resource); - } + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + Preconditions.checkNotNull(resource); + RestPreconditions.checkFound(service.findOne(resource.getId())); + service.update(resource); + } - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - public void delete(@PathVariable("id") final Long id) { - service.deleteById(id); - } + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + service.deleteById(id); + } - @RequestMapping(method = RequestMethod.HEAD) - @ResponseStatus(HttpStatus.OK) - public void head(final HttpServletResponse resp) { - resp.setContentType(MediaType.APPLICATION_JSON_VALUE); - resp.setHeader("bar", "baz"); - } + @RequestMapping(method = RequestMethod.HEAD) + @ResponseStatus(HttpStatus.OK) + public void head(final HttpServletResponse resp) { + resp.setContentType(MediaType.APPLICATION_JSON_VALUE); + resp.setHeader("bar", "baz"); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java index 3e6a6627df..9c4d14cae3 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java @@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value = "/") public class HomeController { - public String index() { - return "homepage"; - } + public String index() { + return "homepage"; + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java index bcf0ceb5e6..8b63275b66 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java @@ -23,63 +23,63 @@ import org.springframework.web.util.UriTemplate; @RequestMapping(value = "/auth/") public class RootController { - @Autowired - private IMetricService metricService; + @Autowired + private IMetricService metricService; - @Autowired - private IActuatorMetricService actMetricService; + @Autowired + private IActuatorMetricService actMetricService; - public RootController() { - super(); - } + public RootController() { + super(); + } - // API + // API - // discover + // discover - @RequestMapping(value = "admin", method = RequestMethod.GET) - @ResponseStatus(value = HttpStatus.NO_CONTENT) - public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { - final String rootUri = request.getRequestURL().toString(); + @RequestMapping(value = "admin", method = RequestMethod.GET) + @ResponseStatus(value = HttpStatus.NO_CONTENT) + public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { + final String rootUri = request.getRequestURL().toString(); - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); - } + final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); + final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); + response.addHeader("Link", linkToFoo); + } - @RequestMapping(value = "/metric", method = RequestMethod.GET) - @ResponseBody - public Map getMetric() { - return metricService.getFullMetric(); - } + @RequestMapping(value = "/metric", method = RequestMethod.GET) + @ResponseBody + public Map getMetric() { + return metricService.getFullMetric(); + } - @PreAuthorize("hasRole('ROLE_ADMIN')") - @RequestMapping(value = "/status-metric", method = RequestMethod.GET) - @ResponseBody - public Map getStatusMetric() { - return metricService.getStatusMetric(); - } + @PreAuthorize("hasRole('ROLE_ADMIN')") + @RequestMapping(value = "/status-metric", method = RequestMethod.GET) + @ResponseBody + public Map getStatusMetric() { + return metricService.getStatusMetric(); + } - @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) - @ResponseBody - public Object[][] drawMetric() { - final Object[][] result = metricService.getGraphData(); - for (int i = 1; i < result[0].length; i++) { - result[0][i] = result[0][i].toString(); - } - return result; - } + @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) + @ResponseBody + public Object[][] drawMetric() { + final Object[][] result = metricService.getGraphData(); + for (int i = 1; i < result[0].length; i++) { + result[0][i] = result[0][i].toString(); + } + return result; + } - @RequestMapping(value = "/admin/x", method = RequestMethod.GET) - @ResponseBody - public String sampleAdminPage() { - return "Hello"; - } + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) + @ResponseBody + public String sampleAdminPage() { + return "Hello"; + } - @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) - @ResponseBody - public String sampleErrorPage() { - return "Error Occurred"; - } + @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) + @ResponseBody + public String sampleErrorPage() { + return "Error Occurred"; + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index 2228287f4d..cf46e35e57 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -40,94 +40,94 @@ import cz.jirutka.rsql.parser.ast.Node; @RequestMapping(value = "/auth/") public class UserController { - @Autowired - private IUserDAO service; + @Autowired + private IUserDAO service; - @Autowired - private UserRepository dao; + @Autowired + private UserRepository dao; - @Autowired - private MyUserRepository myUserRepository; + @Autowired + private MyUserRepository myUserRepository; - public UserController() { - super(); - } + public UserController() { + super(); + } - // API - READ + // API - READ - @RequestMapping(method = RequestMethod.GET, value = "/users") - @ResponseBody - public List findAll(@RequestParam(value = "search", required = false) final String search) { - final List params = new ArrayList(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); - } - } - return service.searchUser(params); - } + @RequestMapping(method = RequestMethod.GET, value = "/users") + @ResponseBody + public List findAll(@RequestParam(value = "search", required = false) final String search) { + final List params = new ArrayList(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); + } + } + return service.searchUser(params); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/spec") - @ResponseBody - public List findAllBySpecification(@RequestParam(value = "search") final String search) { - final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); - final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); - final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/spec") + @ResponseBody + public List findAllBySpecification(@RequestParam(value = "search") final String search) { + final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); + final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); + final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); + } - final Specification spec = builder.build(); - return dao.findAll(spec); - } + final Specification spec = builder.build(); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/myusers") - @ResponseBody - public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); - } - } - final BooleanExpression exp = builder.build(); - return myUserRepository.findAll(exp); - } + @RequestMapping(method = RequestMethod.GET, value = "/myusers") + @ResponseBody + public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); + } + } + final BooleanExpression exp = builder.build(); + return myUserRepository.findAll(exp); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") - @ResponseBody - public List findAllByRsql(@RequestParam(value = "search") final String search) { - final Node rootNode = new RSQLParser().parse(search); - final Specification spec = rootNode.accept(new CustomRsqlVisitor()); - return dao.findAll(spec); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") + @ResponseBody + public List findAllByRsql(@RequestParam(value = "search") final String search) { + final Node rootNode = new RSQLParser().parse(search); + final Specification spec = rootNode.accept(new CustomRsqlVisitor()); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") - @ResponseBody - public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { - return myUserRepository.findAll(predicate); - } + @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") + @ResponseBody + public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { + return myUserRepository.findAll(predicate); + } - // API - WRITE + // API - WRITE - @RequestMapping(method = RequestMethod.POST, value = "/users") - @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final User resource) { - Preconditions.checkNotNull(resource); - dao.save(resource); - } + @RequestMapping(method = RequestMethod.POST, value = "/users") + @ResponseStatus(HttpStatus.CREATED) + public void create(@RequestBody final User resource) { + Preconditions.checkNotNull(resource); + dao.save(resource); + } - @RequestMapping(method = RequestMethod.POST, value = "/myusers") - @ResponseStatus(HttpStatus.CREATED) - public void addMyUser(@RequestBody final MyUser resource) { - Preconditions.checkNotNull(resource); - myUserRepository.save(resource); + @RequestMapping(method = RequestMethod.POST, value = "/myusers") + @ResponseStatus(HttpStatus.CREATED) + public void addMyUser(@RequestBody final MyUser resource) { + Preconditions.checkNotNull(resource); + myUserRepository.save(resource); - } + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java new file mode 100644 index 0000000000..7c68d3e9c7 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java @@ -0,0 +1,76 @@ +package org.baeldung.web.interceptor; + +import com.google.common.base.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Enumeration; + +public class LoggerInterceptor extends HandlerInterceptorAdapter { + + private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class); + + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); + return true; + } + + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { + log.info("[postHandle][" + request + "]"); + } + + /** + * Executed after complete request is finished + **/ + @Override + public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception { + if (ex != null) + ex.printStackTrace(); + log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); + } + + private String getParameters(final HttpServletRequest request) { + final StringBuffer posted = new StringBuffer(); + final Enumeration e = request.getParameterNames(); + if (e != null) + posted.append("?"); + while (e != null && e.hasMoreElements()) { + if (posted.length() > 1) + posted.append("&"); + final String curr = (String) e.nextElement(); + posted.append(curr).append("="); + if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) { + posted.append("*****"); + } else { + posted.append(request.getParameter(curr)); + } + } + + final String ip = request.getHeader("X-FORWARDED-FOR"); + final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip; + if (!Strings.isNullOrEmpty(ipAddr)) + posted.append("&_psip=" + ipAddr); + return posted.toString(); + } + + private String getRemoteAddr(final HttpServletRequest request) { + final String ipFromHeader = request.getHeader("X-FORWARDED-FOR"); + if (ipFromHeader != null && ipFromHeader.length() > 0) { + log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader); + return ipFromHeader; + } + return request.getRemoteAddr(); + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java new file mode 100644 index 0000000000..8d967ed1ef --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -0,0 +1,57 @@ +package org.baeldung.web.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimerInterceptor extends HandlerInterceptorAdapter { + + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); + + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; + + @Autowired + private HttpSession session; + + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) + throws Exception { + log.info("Pre handle method - check handling start time"); + long startTime = System.currentTimeMillis(); + request.setAttribute("executionTime", startTime); + if (UserInterceptor.isUserLogged()) { + session = request.getSession(); + log.info("Who is logged in: " + SecurityContextHolder.getContext().getAuthentication().getName()); + log.info("Time since last request in this session: " + + (System.currentTimeMillis() - request.getSession().getLastAccessedTime()) + " ms"); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + request.logout(); + response.sendRedirect("/spring-security-rest-full/logout"); + } + } + return true; + } + + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, + final ModelAndView model) throws Exception { + log.info("Post handle method - check execution time of handling"); + long startTime = (Long) request.getAttribute("executionTime"); + log.info("Execution time for handling the request was: " + (System.currentTimeMillis() - startTime) + " ms"); + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java new file mode 100644 index 0000000000..4ba12d0138 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java @@ -0,0 +1,85 @@ +package org.baeldung.web.interceptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.SmartView; +import org.springframework.web.servlet.View; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class UserInterceptor extends HandlerInterceptorAdapter { + + private static Logger log = LoggerFactory.getLogger(UserInterceptor.class); + + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { + if (isUserLogged()) { + addToModelUserDetails(request.getSession()); + } + return true; + } + + /** + * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle + **/ + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) + throws Exception { + if (model != null && !isRedirectView(model)) { + if (isUserLogged()) { + addToModelUserDetails(model); + } + } + } + + /** + * Used before model is generated, based on session + */ + private void addToModelUserDetails(HttpSession session) { + log.info("================= addToModelUserDetails ============================"); + String loggedUsername = SecurityContextHolder.getContext().getAuthentication().getName(); + session.setAttribute("username", loggedUsername); + log.info("user(" + loggedUsername + ") session : " + session); + log.info("================= addToModelUserDetails ============================"); + + } + + /** + * Used when model is available + */ + private void addToModelUserDetails(ModelAndView model) { + log.info("================= addToModelUserDetails ============================"); + String loggedUsername = SecurityContextHolder.getContext().getAuthentication().getName(); + model.addObject("loggedUsername", loggedUsername); + log.trace("session : " + model.getModel()); + log.info("================= addToModelUserDetails ============================"); + + } + + public static boolean isRedirectView(ModelAndView mv) { + + String viewName = mv.getViewName(); + if (viewName.startsWith("redirect:/")) { + return true; + } + + View view = mv.getView(); + return (view != null && view instanceof SmartView && ((SmartView) view).isRedirectView()); + } + + public static boolean isUserLogged() { + try { + return !SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser"); + } catch (Exception e) { + return false; + } + } +} diff --git a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml index d6ba952dfd..be6b4d0c27 100644 --- a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml @@ -32,5 +32,9 @@ + + \ No newline at end of file diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java index 5b19d9fbcc..8b754a03ff 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/SecurityTestSuite.java @@ -1,6 +1,5 @@ package org.baeldung.security; - import org.baeldung.security.csrf.CsrfDisabledIntegrationTest; import org.baeldung.security.csrf.CsrfEnabledIntegrationTest; import org.junit.runner.RunWith; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 35b840a649..1b5f7cd894 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -23,30 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper; @WebAppConfiguration public class CsrfAbstractIntegrationTest { - @Autowired - private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired - private Filter springSecurityFilterChain; + @Autowired + private Filter springSecurityFilterChain; - protected MockMvc mvc; + protected MockMvc mvc; - // + // - @Before - public void setup() { - mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); - } + @Before + public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); + } - protected RequestPostProcessor testUser() { - return user("user").password("userPass").roles("USER"); - } + protected RequestPostProcessor testUser() { + return user("user").password("userPass").roles("USER"); + } - protected RequestPostProcessor testAdmin() { - return user("admin").password("adminPass").roles("USER", "ADMIN"); - } + protected RequestPostProcessor testAdmin() { + return user("admin").password("adminPass").roles("USER", "ADMIN"); + } - protected String createFoo() throws JsonProcessingException { - return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); - } + protected String createFoo() throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 1f5cf078f3..63efd870cd 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -14,33 +14,31 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest { - @Test - public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { - mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); - } + @Test + public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); + } - @Test - public void givenAuth_whenAddFoo_thenCreated() throws Exception { - mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); - } + @Test + public void givenAuth_whenAddFoo_thenCreated() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); + } - @Test - public void accessMainPageWithoutAuthorization() throws Exception { - mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); - } + @Test + public void accessMainPageWithoutAuthorization() throws Exception { + mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + } - @Test - public void accessOtherPages() throws Exception { - mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")) - .andExpect(status().isUnauthorized()); // without authorization - mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())) - .andExpect(status().isOk()); // with authorization - } + @Test + public void accessOtherPages() throws Exception { + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")).andExpect(status().isUnauthorized()); // without authorization + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())).andExpect(status().isOk()); // with authorization + } - @Test - public void accessAdminPage() throws Exception { - mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization - mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization - } + @Test + public void accessAdminPage() throws Exception { + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); // without authorization + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); // with authorization + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java new file mode 100644 index 0000000000..930ab20262 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java @@ -0,0 +1,51 @@ +package org.baeldung.web.interceptor; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +public class LoggerInterceptorTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + * + * @throws Exception + */ + @Test + public void testInterceptors() throws Exception { + mockMvc.perform(get("/graph.html")).andExpect(status().isOk()); + } + +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java new file mode 100644 index 0000000000..a29de04bb4 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java @@ -0,0 +1,56 @@ +package org.baeldung.web.interceptor; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.http.HttpSession; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) +public class SessionTimerInterceptorTest { + + @Autowired + WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn() + .getRequest().getSession(); + Thread.sleep(51000); + mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); + } + +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java new file mode 100644 index 0000000000..0b65311203 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java @@ -0,0 +1,53 @@ +package org.baeldung.web.interceptor; + +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityWithoutCsrfConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@Transactional +@ContextConfiguration(classes = {SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class}) +@WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) +public class UserInterceptorTest { + + @Autowired + WebApplicationContext wac; + + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + mockMvc.perform(get("/auth/admin")) + .andExpect(status().is2xxSuccessful()); + } + +} diff --git a/spring-security-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-rest/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-rest/.settings/.jsdtscope b/spring-security-rest/.settings/.jsdtscope deleted file mode 100644 index facca273ec..0000000000 --- a/spring-security-rest/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-security-rest/.settings/org.eclipse.jdt.core.prefs b/spring-security-rest/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.jdt.ui.prefs b/spring-security-rest/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.m2e.core.prefs b/spring-security-rest/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-rest/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.wst.common.component b/spring-security-rest/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 6782a0c5c7..0000000000 --- a/spring-security-rest/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-rest/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9b82a337c7..0000000000 --- a/spring-security-rest/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-security-rest/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-rest/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-rest/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-rest/.settings/org.eclipse.wst.validation.prefs b/spring-security-rest/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-rest/.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-security-rest/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-rest/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-rest/.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-security-rest/README.md b/spring-security-rest/README.md index 87f14a9047..bea417a800 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -5,7 +5,7 @@ ### Courses The "REST With Spring" Classes: http://bit.ly/restwithspring -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) diff --git a/spring-security-x509/keystore/Makefile b/spring-security-x509/keystore/Makefile new file mode 100644 index 0000000000..5321be9de3 --- /dev/null +++ b/spring-security-x509/keystore/Makefile @@ -0,0 +1,88 @@ +PASSWORD=changeit +KEYSTORE=keystore.jks +HOSTNAME=localhost +CLIENTNAME=cid + +# CN = Common Name +# OU = Organization Unit +# O = Organization Name +# L = Locality Name +# ST = State Name +# C = Country (2-letter Country Code) +# E = Email +DNAME_CA='CN=Baeldung CA,OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' +# For server certificates, the Common Name (CN) must be the hostname +DNAME_HOST='CN=$(HOSTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' +DNAME_CLIENT='CN=$(CLIENTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' +TRUSTSTORE=truststore.jks + +all: clean create-keystore add-host create-truststore add-client + +create-keystore: + # Generate a certificate authority (CA) + keytool -genkey -alias ca -ext BC=ca:true \ + -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ + -validity 3650 -dname $(DNAME_CA) \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + +add-host: + # Generate a host certificate + keytool -genkey -alias $(HOSTNAME) \ + -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ + -validity 3650 -dname $(DNAME_HOST) \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + # Generate a host certificate signing request + keytool -certreq -alias $(HOSTNAME) -ext BC=ca:true \ + -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ + -validity 3650 -file "$(HOSTNAME).csr" \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + # Generate signed certificate with the certificate authority + keytool -gencert -alias ca \ + -validity 3650 -sigalg SHA512withRSA \ + -infile "$(HOSTNAME).csr" -outfile "$(HOSTNAME).crt" -rfc \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + # Import signed certificate into the keystore + keytool -import -trustcacerts -alias $(HOSTNAME) \ + -file "$(HOSTNAME).crt" \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + +export-authority: + # Export certificate authority + keytool -export -alias ca -file ca.crt -rfc \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + + +create-truststore: export-authority + # Import certificate authority into a new truststore + keytool -import -trustcacerts -noprompt -alias ca -file ca.crt \ + -keystore $(TRUSTSTORE) -storepass $(PASSWORD) + +add-client: + # Generate client certificate + keytool -genkey -alias $(CLIENTNAME) \ + -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ + -validity 3650 -dname $(DNAME_CLIENT) \ + -keystore $(TRUSTSTORE) -storepass $(PASSWORD) + # Generate a host certificate signing request + keytool -certreq -alias $(CLIENTNAME) -ext BC=ca:true \ + -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ + -validity 3650 -file "$(CLIENTNAME).csr" \ + -keystore $(TRUSTSTORE) -storepass $(PASSWORD) + # Generate signed certificate with the certificate authority + keytool -gencert -alias ca \ + -validity 3650 -sigalg SHA512withRSA \ + -infile "$(CLIENTNAME).csr" -outfile "$(CLIENTNAME).crt" -rfc \ + -keystore $(KEYSTORE) -storepass $(PASSWORD) + # Import signed certificate into the truststore + keytool -import -trustcacerts -alias $(CLIENTNAME) \ + -file "$(CLIENTNAME).crt" \ + -keystore $(TRUSTSTORE) -storepass $(PASSWORD) + # Export private certificate for importing into a browser + keytool -importkeystore -srcalias $(CLIENTNAME) \ + -srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \ + -destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \ + -deststoretype PKCS12 + +clean: + # Remove generated artifacts + find . ! -name Makefile -type f -exec rm -f {} \; diff --git a/spring-security-x509/keystore/keystore.jks b/spring-security-x509/keystore/keystore.jks new file mode 100644 index 0000000000..044a820c39 Binary files /dev/null and b/spring-security-x509/keystore/keystore.jks differ diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml new file mode 100644 index 0000000000..953af761b5 --- /dev/null +++ b/spring-security-x509/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung + spring-security-x509 + 0.0.1-SNAPSHOT + pom + + + spring-security-x509-basic-auth + spring-security-x509-client-auth + + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml new file mode 100644 index 0000000000..87fdd64727 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + basic-secured-server + 0.0.1-SNAPSHOT + jar + + basic-secured-server + Spring x.509 Authentication Demo + + + com.baeldung + spring-security-x509 + 0.0.1-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java new file mode 100644 index 0000000000..d4616dd5a6 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.security.x509; + +import java.security.Principal; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class UserController { + @PreAuthorize("hasAuthority('ROLE_USER')") + @RequestMapping(value = "/user") + public String user(Model model, Principal principal) { + UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); + model.addAttribute("username", currentUser.getUsername()); + return "user"; + } +} diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java new file mode 100644 index 0000000000..b99c242408 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.security.x509; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@SpringBootApplication +@EnableWebSecurity +public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { + + public static void main(String[] args) { + SpringApplication.run(X509AuthenticationServer.class, args); + } + +} diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties new file mode 100644 index 0000000000..f293d6712d --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store-password=changeit +server.ssl.key-alias=localhost +server.ssl.key-password=changeit +server.ssl.enabled=true +server.port=8443 +security.user.name=Admin +security.user.password=admin \ No newline at end of file diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/templates/user.html b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/templates/user.html new file mode 100644 index 0000000000..3e36d7b644 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/templates/user.html @@ -0,0 +1,9 @@ + + + + X.509 Authentication Demo + + +

Hello !

+ + diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java new file mode 100644 index 0000000000..0b9a11552a --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.security.x509; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class X509AuthenticationServerTests { + @Test + public void contextLoads() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml new file mode 100644 index 0000000000..56cef8ea07 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + client-auth-server + 0.0.1-SNAPSHOT + jar + + client-auth-server + Spring x.509 Client Authentication Demo + + + com.baeldung + spring-security-x509 + 0.0.1-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java new file mode 100644 index 0000000000..d4616dd5a6 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/UserController.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.security.x509; + +import java.security.Principal; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class UserController { + @PreAuthorize("hasAuthority('ROLE_USER')") + @RequestMapping(value = "/user") + public String user(Model model, Principal principal) { + UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); + model.addAttribute("username", currentUser.getUsername()); + return "user"; + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java new file mode 100644 index 0000000000..050423238e --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.security.x509; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +@SpringBootApplication +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { + public static void main(String[] args) { + SpringApplication.run(X509AuthenticationServer.class, args); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); + } + + @Bean + public UserDetailsService userDetailsService() { + return new UserDetailsService() { + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + if (username.equals("cid")) { + return new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); + } + throw new UsernameNotFoundException("User not found!"); + } + }; + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties new file mode 100644 index 0000000000..174eba9f98 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties @@ -0,0 +1,11 @@ +server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store-password=changeit +server.ssl.key-alias=localhost +server.ssl.key-password=changeit +server.ssl.enabled=true +server.port=8443 +security.user.name=Admin +security.user.password=admin +server.ssl.trust-store=../keystore/truststore.jks +server.ssl.trust-store-password=changeit +server.ssl.client-auth=need \ No newline at end of file diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks new file mode 100644 index 0000000000..044a820c39 Binary files /dev/null and b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks differ diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/resources/templates/user.html b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/templates/user.html new file mode 100644 index 0000000000..a35b18bacc --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/templates/user.html @@ -0,0 +1,9 @@ + + + + X.509 Authentication Demo + + +

Hello !

+ + diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java new file mode 100644 index 0000000000..0b9a11552a --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.security.x509; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class X509AuthenticationServerTests { + @Test + public void contextLoads() { + } +} diff --git a/webjars/pom.xml b/webjars/pom.xml deleted file mode 100644 index 80e4f0a42a..0000000000 --- a/webjars/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - - com.baeldung - webjarsdemo - 0.0.1-SNAPSHOT - jar - - webjarsdemo - Demo project for webjars using Spring Boot - - - org.springframework.boot - spring-boot-starter-parent - 1.3.5.RELEASE - - - - - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.webjars - bootstrap - 3.3.4 - - - org.webjars - jquery - 2.1.4 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -