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/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml new file mode 100644 index 0000000000..6d07394b87 --- /dev/null +++ b/annotations/annotation-processing/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + com.baeldung + 1.0.0-SNAPSHOT + annotations + ../ + + + annotation-processing + + + 1.0-rc2 + 3.5.1 + + + + + + com.google.auto.service + auto-service + ${auto-service.version} + provided + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java new file mode 100644 index 0000000000..0883e108e7 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -0,0 +1,132 @@ +package com.baeldung.annotation.processor; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ExecutableType; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.google.auto.service.AutoService; + +@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") +@SupportedSourceVersion(SourceVersion.RELEASE_8) +@AutoService(Processor.class) +public class BuilderProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + + Map> annotatedMethods = annotatedElements.stream() + .collect(Collectors.partitioningBy(element -> + ((ExecutableType) element.asType()).getParameterTypes().size() == 1 + && element.getSimpleName().toString().startsWith("set"))); + + List setters = annotatedMethods.get(true); + List otherMethods = annotatedMethods.get(false); + + otherMethods.forEach(element -> + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + + if (setters.isEmpty()) { + continue; + } + + String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); + + Map setterMap = setters.stream().collect(Collectors.toMap( + setter -> setter.getSimpleName().toString(), + setter -> ((ExecutableType) setter.asType()) + .getParameterTypes().get(0).toString() + )); + + try { + writeBuilderFile(className, setterMap); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return true; + } + + private void writeBuilderFile(String className, Map setterMap) throws IOException { + + String packageName = null; + int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + packageName = className.substring(0, lastDot); + } + + String simpleClassName = className.substring(lastDot + 1); + String builderClassName = className + "Builder"; + String builderSimpleClassName = builderClassName.substring(lastDot + 1); + + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); + try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { + + if (packageName != null) { + out.print("package "); + out.print(packageName); + out.println(";"); + out.println(); + } + + out.print("public class "); + out.print(builderSimpleClassName); + out.println(" {"); + out.println(); + + out.print(" private "); + out.print(simpleClassName); + out.print(" object = new "); + out.print(simpleClassName); + out.println("();"); + out.println(); + + out.print(" public "); + out.print(simpleClassName); + out.println(" build() {"); + out.println(" return object;"); + out.println(" }"); + out.println(); + + setterMap.entrySet().forEach(setter -> { + String methodName = setter.getKey(); + String argumentType = setter.getValue(); + + out.print(" public "); + out.print(builderSimpleClassName); + out.print(" "); + out.print(methodName); + + out.print("("); + + out.print(argumentType); + out.println(" value) {"); + out.print(" object."); + out.print(methodName); + out.println("(value);"); + out.println(" return this;"); + out.println(" }"); + out.println(); + }); + + out.println("}"); + + } + } + +} diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java new file mode 100644 index 0000000000..84fcc73850 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation.processor; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.SOURCE) +public @interface BuilderProperty { +} diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml new file mode 100644 index 0000000000..f76f691f93 --- /dev/null +++ b/annotations/annotation-user/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + + annotations + com.baeldung + 1.0.0-SNAPSHOT + ../ + + + annotation-user + + + + + com.baeldung + annotation-processing + ${project.parent.version} + + + + junit + junit + 4.12 + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java new file mode 100644 index 0000000000..23787ba4f4 --- /dev/null +++ b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java @@ -0,0 +1,29 @@ +package com.baeldung.annotation; + +import com.baeldung.annotation.processor.BuilderProperty; + +public class Person { + + private int age; + + private String name; + + public int getAge() { + return age; + } + + @BuilderProperty + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + @BuilderProperty + public void setName(String name) { + this.name = name; + } + +} diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java new file mode 100644 index 0000000000..72f9ac8bc7 --- /dev/null +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -0,0 +1,22 @@ +package com.baeldung.annotation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PersonBuilderTest { + + @Test + public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { + + Person person = new PersonBuilder() + .setAge(25) + .setName("John") + .build(); + + assertEquals(25, person.getAge()); + assertEquals("John", person.getName()); + + } + +} diff --git a/annotations/pom.xml b/annotations/pom.xml new file mode 100644 index 0000000000..f691674cf1 --- /dev/null +++ b/annotations/pom.xml @@ -0,0 +1,20 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + annotations + pom + + + annotation-processing + annotation-user + + + \ No newline at end of file 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/README.md b/core-java-8/README.md index e6bac2a4c9..c130e6bd41 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,4 +11,14 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) +- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 63df0e1b95..566eb4e43a 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,9 +1,10 @@ 4.0.0 + com.baeldung + 1.0.0-SNAPSHOT core-java8 - 0.1-SNAPSHOT core-java8 @@ -111,6 +112,9 @@ + + UTF-8 + 1.7.13 1.0.13 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/main/resources/fileTest.txt b/core-java-8/src/main/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-8/src/main/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file 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/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java new file mode 100644 index 0000000000..b1476b6360 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -0,0 +1,78 @@ +package com.baeldung.file; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; + +import static org.hamcrest.CoreMatchers.containsString; + +public class FileOperationsTest { + + @Test + public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); +} + + @Test + public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Class clazz = FileOperationsTest.class; + InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + @Test + public void givenURLName_whenUsingURL_thenFileData() throws IOException { + String expectedData = "Baeldung"; + + URL urlObject = new URL("http://www.baeldung.com/"); + URLConnection urlConnection = urlObject.openConnection(); + + InputStream inputStream = urlConnection.getInputStream(); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + @Test + public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { + String expectedData = "BSD License"; + + Class clazz = Matchers.class; + InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data, containsString(expectedData)); + } + + private String readFromInputStream(InputStream inputStream) throws IOException { + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + StringBuilder resultStringBuilder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line); + resultStringBuilder.append("\n"); + } + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + return resultStringBuilder.toString(); + } +} \ 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/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index efd548a4b1..f2e7452137 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -21,7 +21,7 @@ public class JavaFolderSizeTest { @Before public void init() { final String separator = File.separator; - path = "src" + separator + "test" + separator + "resources"; + path = String.format("src%stest%sresources", separator, separator); } @Test @@ -79,7 +79,9 @@ public class JavaFolderSizeTest { final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length).sum(); assertEquals(expectedSize, size); } @@ -101,13 +103,11 @@ public class JavaFolderSizeTest { long length = 0; final File[] files = folder.listFiles(); - final int count = files.length; - - for (int i = 0; i < count; i++) { - if (files[i].isFile()) { - length += files[i].length(); + for (File file : files) { + if (file.isFile()) { + length += file.length(); } else { - length += getFolderSize(files[i]); + length += getFolderSize(file); } } return length; diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java new file mode 100644 index 0000000000..df336f4a93 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java @@ -0,0 +1,146 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CoreThreadPoolTest { + + @Test(timeout = 1000) + public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(1); + + Executor executor = Executors.newSingleThreadExecutor(); + executor.execute(() -> { + System.out.println("Hello World"); + lock.countDown(); + }); + + lock.await(1000, TimeUnit.MILLISECONDS); + } + + @Test + public void whenUsingExecutorServiceAndFuture_thenCanWaitOnFutureResult() throws InterruptedException, ExecutionException { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + Future future = executorService.submit(() -> "Hello World"); + String result = future.get(); + + assertEquals("Hello World", result); + + } + + @Test + public void whenUsingFixedThreadPool_thenCoreAndMaximumThreadSizeAreTheSame() { + + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + + assertEquals(2, executor.getPoolSize()); + assertEquals(1, executor.getQueue().size()); + + } + + @Test + public void whenUsingCachedThreadPool_thenPoolSizeGrowsUnbounded() { + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + executor.submit(() -> { + Thread.sleep(1000); + return null; + }); + + assertEquals(3, executor.getPoolSize()); + assertEquals(0, executor.getQueue().size()); + + } + + @Test(timeout = 1000) + public void whenUsingSingleThreadPool_thenTasksExecuteSequentially() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(2); + AtomicInteger counter = new AtomicInteger(); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + executor.submit(() -> { + counter.set(1); + lock.countDown(); + }); + executor.submit(() -> { + counter.compareAndSet(1, 2); + lock.countDown(); + }); + + lock.await(1000, TimeUnit.MILLISECONDS); + assertEquals(2, counter.get()); + + } + + @Test(timeout = 1000) + public void whenSchedulingTask_thenTaskExecutesWithinGivenPeriod() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(1); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); + executor.schedule(() -> { + System.out.println("Hello World"); + lock.countDown(); + }, 500, TimeUnit.MILLISECONDS); + + lock.await(1000, TimeUnit.MILLISECONDS); + + } + + @Test(timeout = 1000) + public void whenSchedulingTaskWithFixedPeriod_thenTaskExecutesMultipleTimes() throws InterruptedException { + + CountDownLatch lock = new CountDownLatch(3); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); + ScheduledFuture future = executor.scheduleAtFixedRate(() -> { + System.out.println("Hello World"); + lock.countDown(); + }, 500, 100, TimeUnit.MILLISECONDS); + + lock.await(); + future.cancel(true); + + } + + @Test + public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() { + + TreeNode tree = new TreeNode(5, + new TreeNode(3), new TreeNode(2, + new TreeNode(2), new TreeNode(8))); + + ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + int sum = forkJoinPool.invoke(new CountingTask(tree)); + + assertEquals(20, sum); + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java new file mode 100644 index 0000000000..92e0f9a8cb --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java @@ -0,0 +1,56 @@ +package com.baeldung.threadpool; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class GuavaThreadPoolTest { + + @Test + public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() { + + Executor executor = MoreExecutors.directExecutor(); + + AtomicBoolean executed = new AtomicBoolean(); + + executor.execute(() -> { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + executed.set(true); + }); + + assertTrue(executed.get()); + } + + @Test + public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException { + + ExecutorService executorService = Executors.newCachedThreadPool(); + ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); + + ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello"); + ListenableFuture future2 = listeningExecutorService.submit(() -> "World"); + + String greeting = Futures.allAsList(future1, future2).get() + .stream() + .collect(Collectors.joining(" ")); + assertEquals("Hello World", greeting); + + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java new file mode 100644 index 0000000000..06d9394a5e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -0,0 +1,47 @@ +package com.baeldung.util; + +import static org.junit.Assert.assertEquals; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.GregorianCalendar; + +import org.junit.Test; + +public class CurrentDateTimeTest { + + @Test + public void shouldReturnCurrentDate() { + + final LocalDate now = LocalDate.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals("10-10-2010".length(), now.toString().length()); + assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); + assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR)); + } + + @Test + public void shouldReturnCurrentTime() { + + final LocalTime now = LocalTime.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); + } + + @Test + public void shouldReturnCurrentTimestamp() { + + final Instant now = Instant.now(); + final Calendar calendar = GregorianCalendar.getInstance(); + + assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); + } +} diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt new file mode 100644 index 0000000000..652d70630f --- /dev/null +++ b/core-java-8/src/test/resources/test.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/core-java-8/src/test/resources/.gitignore b/core-java-9/.gitignore similarity index 100% rename from core-java-8/src/test/resources/.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..844ad6a782 --- /dev/null +++ b/core-java-9/pom.xml @@ -0,0 +1,93 @@ + + 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/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java new file mode 100644 index 0000000000..b0684a94f8 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -0,0 +1,71 @@ +package com.baeldung.java8; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +public class Java9OptionalsStreamTest { + + private static List> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar")); + + @Test + public void filterOutPresentOptionalsWithFilter() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + + assertEquals(2, filteredList.size()); + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithFlatMap() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); + + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithFlatMap2() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); + + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + + @Test + public void filterOutPresentOptionalsWithJava9() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(Optional::stream) + .collect(Collectors.toList()); + + assertEquals(2, filteredList.size()); + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + +} 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..a00646e4db --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -0,0 +1,47 @@ +package com.baeldung.java9; + +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/OptionalToStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java new file mode 100644 index 0000000000..56b4bb7b8c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java @@ -0,0 +1,21 @@ +package com.baeldung.java9; + +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class OptionalToStreamTest { + + @Test + public void testOptionalToStream() { + Optional op = Optional.ofNullable("String value"); + Stream strOptionalStream = op.stream(); + Stream filteredStream = strOptionalStream.filter((str) -> { + return str != null && str.startsWith("String"); + }); + assertEquals(1, filteredStream.count()); + + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java new file mode 100644 index 0000000000..0f8db83d9c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java @@ -0,0 +1,26 @@ +package com.baeldung.java9; + +import java.util.Set; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SetExamplesTest { + + @Test + public void testUnmutableSet() { + Set strKeySet = Set.of("key1", "key2", "key3"); + try { + strKeySet.add("newKey"); + } catch (UnsupportedOperationException uoe) { + } + assertEquals(strKeySet.size(), 3); + } + + @Test + public void testArrayToSet() { + Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; + Set intSet = Set.of(intArray); + assertEquals(intSet.size(), intArray.length); + } +} 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/pom.xml b/core-java/pom.xml index bc533607e7..bce97d1148 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -123,6 +123,12 @@ ${mockito.version} test + + + commons-codec + commons-codec + 1.10 + diff --git a/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java b/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java new file mode 100644 index 0000000000..2ac4e49869 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/core/exceptions/FileNotFoundExceptionExample.java @@ -0,0 +1,20 @@ +package com.baeldung.core.exceptions; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +public class FileNotFoundExceptionExample { + + public static void main(String[] args) throws IOException { + BufferedReader rd = null; + try { + rd = new BufferedReader(new FileReader(new File("notExisting"))); + rd.readLine(); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + } +} \ 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/java/com/baeldung/java/regex/Result.java b/core-java/src/main/java/com/baeldung/java/regex/Result.java new file mode 100644 index 0000000000..d47c94ad2e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/regex/Result.java @@ -0,0 +1,27 @@ +package com.baeldung.java.regex; + +public class Result { + private boolean found = false; + private int count = 0; + + public Result() { + + } + + public boolean isFound() { + return found; + } + + public void setFound(boolean found) { + this.found = found; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java new file mode 100644 index 0000000000..d4a6a0f42e --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java @@ -0,0 +1,65 @@ +package org.baeldung.equalshashcode.entities; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ComplexClass { + + private List genericList; + private Set integerSet; + + public ComplexClass(ArrayList genericArrayList, HashSet integerHashSet) { + super(); + this.genericList = genericArrayList; + this.integerSet = integerHashSet; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((genericList == null) ? 0 : genericList.hashCode()); + result = prime * result + ((integerSet == null) ? 0 : integerSet.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 (genericList == null) { + if (other.genericList != null) + return false; + } else if (!genericList.equals(other.genericList)) + return false; + if (integerSet == null) { + if (other.integerSet != null) + return false; + } else if (!integerSet.equals(other.integerSet)) + return false; + return true; + } + + protected List getGenericList() { + return genericList; + } + + protected void setGenericArrayList(List genericList) { + this.genericList = genericList; + } + + protected Set getIntegerSet() { + return integerSet; + } + + protected void setIntegerSet(Set integerSet) { + this.integerSet = integerSet; + } +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java new file mode 100644 index 0000000000..ebe005688c --- /dev/null +++ b/core-java/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/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java new file mode 100644 index 0000000000..1e1423f0b3 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java @@ -0,0 +1,58 @@ +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() { + return width * length; + } + + @Override + public double perimeter() { + 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/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java new file mode 100644 index 0000000000..3bfc81da8f --- /dev/null +++ b/core-java/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/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java new file mode 100644 index 0000000000..f11e34f0ba --- /dev/null +++ b/core-java/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/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/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java new file mode 100644 index 0000000000..257e486600 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java @@ -0,0 +1,503 @@ +package com.baeldung.java.regex; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class RegexTest { + private static Pattern pattern; + private static Matcher matcher; + + @Test + public void givenText_whenSimpleRegexMatches_thenCorrect() { + Result result = runTest("foo", "foo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + + } + + @Test + public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() { + Result result = runTest("foo", "foofoo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + + } + + @Test + public void givenText_whenMatchesWithDotMetach_thenCorrect() { + Result result = runTest(".", "foo"); + assertTrue(result.isFound()); + } + + @Test + public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() { + Result result = runTest("foo.", "foofoo"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenORSet_whenMatchesAny_thenCorrect() { + Result result = runTest("[abc]", "b"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenORSet_whenMatchesAnyAndAll_thenCorrect() { + Result result = runTest("[abc]", "cab"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenORSet_whenMatchesAllCombinations_thenCorrect() { + Result result = runTest("[bcr]at", "bat cat rat"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenNORSet_whenMatchesNon_thenCorrect() { + Result result = runTest("[^abc]", "g"); + assertTrue(result.isFound()); + } + + @Test + public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() { + Result result = runTest("[^bcr]at", "sat mat eat"); + assertTrue(result.isFound()); + } + + @Test + public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() { + Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() { + Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 26); + } + + @Test + public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() { + Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 28); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect() { + Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect2() { + Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenTwoSets_whenMatchesUnion_thenCorrect() { + Result result = runTest("[1-3[7-9]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 6); + } + + @Test + public void givenTwoSets_whenMatchesIntersection_thenCorrect() { + Result result = runTest("[1-6&&[3-9]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 4); + } + + @Test + public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() { + Result result = runTest("[0-9&&[^2468]]", "123456789"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 5); + } + + @Test + public void givenDigits_whenMatches_thenCorrect() { + Result result = runTest("\\d", "123"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenNonDigits_whenMatches_thenCorrect() { + Result result = runTest("\\D", "a6c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenWhiteSpace_whenMatches_thenCorrect() { + Result result = runTest("\\s", "a c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenNonWhiteSpace_whenMatches_thenCorrect() { + Result result = runTest("\\S", "a c"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenWordCharacter_whenMatches_thenCorrect() { + Result result = runTest("\\w", "hi!"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenNonWordCharacter_whenMatches_thenCorrect() { + Result result = runTest("\\W", "hi!"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a?", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{0,1}", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a*", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{0,}", "hi"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 3); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect() { + Result result = runTest("\\a+", "hi"); + assertFalse(result.isFound()); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() { + Result result = runTest("\\a{1,}", "hi"); + assertFalse(result.isFound()); + } + + @Test + public void givenBraceQuantifier_whenMatches_thenCorrect() { + Result result = runTest("a{3}", "aaaaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() { + Result result = runTest("a{3}", "aa"); + assertFalse(result.isFound()); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() { + Result result = runTest("a{2,3}", "aaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() { + Result result = runTest("a{2,3}?", "aaaa"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect() { + Result result = runTest("(\\d\\d)", "12"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect2() { + Result result = runTest("(\\d\\d)", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect3() { + Result result = runTest("(\\d\\d)(\\d\\d)", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() { + Result result = runTest("(\\d\\d)\\1", "1212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() { + Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212"); + assertTrue(result.isFound()); + assertEquals(result.getCount(), 1); + } + + @Test + public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() { + Result result = runTest("(\\d\\d)\\1", "1213"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtBeginning_thenCorrect() { + Result result = runTest("^dog", "dogs are friendly"); + assertTrue(result.isFound()); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() { + Result result = runTest("^dog", "are dogs are friendly?"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtEnd_thenCorrect() { + Result result = runTest("dog$", "Man's best friend is a dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() { + Result result = runTest("dog$", "is a dog man's best friend?"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect() { + Result result = runTest("\\bdog\\b", "a dog is friendly"); + assertTrue(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect2() { + Result result = runTest("\\bdog\\b", "dog is man's best friend"); + assertTrue(result.isFound()); + } + + @Test + public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() { + Result result = runTest("\\bdog\\b", "snoop dogg is a rapper"); + assertFalse(result.isFound()); + } + + @Test + public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() { + Result result = runTest("\\bdog\\B", "snoop dogg is a rapper"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() { + Result result = runTest("\u00E9", "\u0065\u0301"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() { + Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() { + Result result = runTest("dog", "This is a Dog"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + Result result = runTest("(?i)dog", "This is a Dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() { + Result result = runTest("dog$ #check for word dog at end of text", "This is a dog"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() { + Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() { + Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(?s)(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text"); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text", Pattern.LITERAL); + assertFalse(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() { + Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() { + Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertFalse(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() { + Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE); + assertTrue(result.isFound()); + } + + @Test + public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() { + Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertTrue(result.isFound()); + } + + @Test + public void givenMatch_whenGetsIndices_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("This dog is mine"); + matcher.find(); + assertEquals(5, matcher.start()); + assertEquals(8, matcher.end()); + } + + @Test + public void whenStudyMethodsWork_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are friendly"); + assertTrue(matcher.lookingAt()); + assertFalse(matcher.matches()); + + } + + @Test + public void whenMatchesStudyMethodWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dog"); + assertTrue(matcher.matches()); + + } + + @Test + public void whenReplaceFirstWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceFirst("cat"); + assertEquals("cats are domestic animals, dogs are friendly", newStr); + + } + + @Test + public void whenReplaceAllWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceAll("cat"); + assertEquals("cats are domestic animals, cats are friendly", newStr); + + } + + public synchronized static Result runTest(String regex, String text) { + pattern = Pattern.compile(regex); + matcher = pattern.matcher(text); + Result result = new Result(); + while (matcher.find()) + result.setCount(result.getCount() + 1); + if (result.getCount() > 0) + result.setFound(true); + return result; + } + + public synchronized static Result runTest(String regex, String text, int flags) { + pattern = Pattern.compile(regex, flags); + matcher = pattern.matcher(text); + Result result = new Result(); + while (matcher.find()) + result.setCount(result.getCount() + 1); + if (result.getCount() > 0) + result.setFound(true); + return result; + } +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java new file mode 100644 index 0000000000..75d96e5989 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java @@ -0,0 +1,33 @@ +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)); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java new file mode 100644 index 0000000000..16f25ae021 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java @@ -0,0 +1,23 @@ +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); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java new file mode 100644 index 0000000000..52d024a696 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java @@ -0,0 +1,26 @@ +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); + + Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); + + Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); + + Assert.assertFalse(aObject.equals(dObject)); + Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); + } + +} 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..30b0111555 --- /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 list = LongStream.range(0, 16) + .boxed() + .map(Long::toHexString) + .collect(toCollection(ArrayList::new)); + stringsToSearch = new ArrayList<>(list); + stringsToSearch.addAll(list); + } + + @Test + public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() { + List list = new ArrayList<>(); + assertTrue(list.isEmpty()); + } + + @Test + public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { + Collection numbers = + IntStream.range(0, 10).boxed().collect(toSet()); + + List list = new ArrayList<>(numbers); + assertEquals(10, list.size()); + assertTrue(numbers.containsAll(list)); + } + + @Test + public void givenElement_whenAddToArrayList_thenIsAdded() { + List list = new ArrayList<>(); + + list.add(1L); + list.add(2L); + list.add(1, 3L); + + assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list)); + } + + @Test + public void givenCollection_whenAddToArrayList_thenIsAdded() { + List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); + LongStream.range(4, 10).boxed() + .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); + + assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list)); + } + + @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 list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + Collections.reverse(list); + + list.remove(0); + assertThat(list.get(0), equalTo(8)); + + list.remove(Integer.valueOf(0)); + assertFalse(list.contains(0)); + } + + @Test + public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() { + List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new)); + ListIterator it = list.listIterator(list.size()); + List result = new ArrayList<>(list.size()); + while (it.hasPrevious()) { + result.add(it.previous()); + } + + Collections.reverse(list); + assertThat(result, equalTo(list)); + } + + @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/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/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java new file mode 100644 index 0000000000..83f1fb33b6 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java @@ -0,0 +1,90 @@ +package org.baeldung.java.md5; + +import static org.junit.Assert.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +import java.io.File; +import java.io.IOException; +import java.nio.*; +import static org.assertj.core.api.Assertions.assertThat; + + +public class JavaMD5Test { + + + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + + + @Test + public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(password.getBytes()); + byte[] digest = md.digest(); + String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myHash.equals(hash)).isTrue(); + } + + @Test + public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter + .printHexBinary(digest).toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + @Test + public void givenPassword_whenHashingUsingCommons_thenVerifying() { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + String md5Hex = DigestUtils + .md5Hex(password).toUpperCase(); + + assertThat(md5Hex.equals(hash)).isTrue(); + } + + + @Test + public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + HashCode hash = com.google.common.io.Files + .hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString() + .toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + +} 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/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/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/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/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/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java deleted file mode 100644 index 3efd579d84..0000000000 --- a/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.hystrix; - - -public class RemoteServiceSimulator { - - public String checkSomething(final long timeout) throws InterruptedException { - - System.out.print(String.format("Waiting %sms. ", timeout)); - - // to simulate a real world delay in processing. - Thread.sleep(timeout); - - return "Done waiting."; - } -} 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/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/log4j/pom.xml b/log4j/pom.xml index 76c05b36c1..586769aa71 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -15,7 +15,13 @@ log4j 1.2.17 - + @@ -28,22 +34,34 @@ log4j-core 2.6 - - + com.lmax disruptor 3.3.4 - + - ch.qos.logback logback-classic 1.1.7 + + diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java new file mode 100644 index 0000000000..6ecc7b887a --- /dev/null +++ b/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java @@ -0,0 +1,20 @@ +package com.baeldung.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml + */ +public class Slf4jExample { + private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class); + + public static void main(String[] args) { + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + + String variable = "Hello John"; + logger.debug("Printing variable value {} ", variable); + } +} 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/patterns/pom.xml b/patterns/pom.xml new file mode 100644 index 0000000000..7c23b6f55d --- /dev/null +++ b/patterns/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + patterns + war + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.0.M1 + + + /front-controller + + + + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java new file mode 100644 index 0000000000..a8962f5108 --- /dev/null +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java @@ -0,0 +1,38 @@ +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 { + Class type = Class.forName( + String.format( + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + request.getParameter("command") + ) + ); + return (FrontCommand) type + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + return new UnknownCommand(); + } + } +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java new file mode 100644 index 0000000000..12a008faeb --- /dev/null +++ b/patterns/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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java new file mode 100644 index 0000000000..0c5bd64bbc --- /dev/null +++ b/patterns/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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java new file mode 100644 index 0000000000..90103c8f42 --- /dev/null +++ b/patterns/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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..634e05c3a0 --- /dev/null +++ b/patterns/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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..524e000bd9 --- /dev/null +++ b/patterns/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/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java new file mode 100644 index 0000000000..3862418857 --- /dev/null +++ b/patterns/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/patterns/src/main/resources/front controller.png b/patterns/src/main/resources/front controller.png new file mode 100644 index 0000000000..af22a38e37 Binary files /dev/null and b/patterns/src/main/resources/front controller.png differ diff --git a/patterns/src/main/resources/front controller.puml b/patterns/src/main/resources/front controller.puml new file mode 100644 index 0000000000..cbc2dc8bd9 --- /dev/null +++ b/patterns/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml +scale 1.5 +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/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..42e08b4a46 --- /dev/null +++ b/patterns/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/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..2f8ac01755 --- /dev/null +++ b/patterns/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/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..b52b2de8d5 --- /dev/null +++ b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1,9 @@ + + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + diff --git a/patterns/src/main/webapp/WEB-INF/web.xml b/patterns/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..77113db09b --- /dev/null +++ b/patterns/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/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 7b4711361c..07d1d2bf65 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -8,30 +9,41 @@ pom - + UTF-8 - + assertj apache-cxf - apache-fop + autovalue-tutorial + + cdi core-java core-java-8 couchbase-sdk + + dozer dependency-injection - gatling + deltaspike + + patterns + feign-client + gson gson-jackson-performance guava guava18 guava19 + handling-spring-static-resources httpclient + immutables + jackson javaxval jjwt @@ -40,16 +52,23 @@ json json-path junit5 - mockito - mocks jee7schedule + + log4j + + mockito + mocks + mutation-testing + + orika + querydsl + rest-assured rest-testing resteasy - log4j spring-all spring-akka @@ -75,13 +94,16 @@ spring-mvc-java spring-mvc-no-xml spring-mvc-xml + spring-mvc-tiles spring-openid spring-protobuf spring-quartz spring-spel spring-rest + spring-rest-angular spring-rest-docs - spring-cloud-config + spring-cloud + spring-cloud-data-flow spring-security-basic-auth spring-security-custom-permission @@ -96,19 +118,20 @@ 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 - mutation-testing - spring-mvc-velocity + wicket xstream - dozer - orika + java-cassandra + annotations diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml new file mode 100644 index 0000000000..c6bd2b042c --- /dev/null +++ b/selenium-junit-testng/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.baeldung + selenium-junit-testng + 0.0.1-SNAPSHOT + + src + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + + + + org.seleniumhq.selenium + selenium-java + 2.53.1 + + + junit + junit + 4.8.1 + + + org.testng + testng + 6.9.10 + + + \ No newline at end of file diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java new file mode 100644 index 0000000000..6020b6bd2c --- /dev/null +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -0,0 +1,29 @@ +package main.java.com.baeldung.selenium; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; + +public class SeleniumExample { + + private WebDriver webDriver; + private final String url = "http://www.baeldung.com/"; + private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; + + public SeleniumExample() { + webDriver = new FirefoxDriver(); + webDriver.get(url); + } + + public void closeWindow() { + webDriver.close(); + } + + public String getActualTitle() { + return webDriver.getTitle(); + } + + public String getExpectedTitle() { + return expectedTitle; + } + +} diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java new file mode 100644 index 0000000000..371f730eb9 --- /dev/null +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java @@ -0,0 +1,30 @@ +package test.java.com.baeldung.selenium.junit; + +import static org.testng.Assert.assertEquals; +import main.java.com.baeldung.selenium.SeleniumExample; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TestSeleniumWithJUnit { + + private SeleniumExample seleniumExample; + + @Before + public void setUp() { + seleniumExample = new SeleniumExample(); + } + + @After + public void tearDown() { + seleniumExample.closeWindow(); + } + + @Test + public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { + String expectedTitle = seleniumExample.getExpectedTitle(); + String actualTitle = seleniumExample.getActualTitle(); + assertEquals(actualTitle, expectedTitle); + } +} diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java new file mode 100644 index 0000000000..ec10f9ca82 --- /dev/null +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java @@ -0,0 +1,30 @@ +package test.java.com.baeldung.selenium.testng; + +import static org.testng.Assert.assertEquals; +import main.java.com.baeldung.selenium.SeleniumExample; + +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +public class TestSeleniumWithTestNG { + + private SeleniumExample seleniumExample; + + @BeforeSuite + public void setUp() { + seleniumExample = new SeleniumExample(); + } + + @AfterSuite + public void tearDown() { + seleniumExample.closeWindow(); + } + + @Test + public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { + String expectedTitle = seleniumExample.getExpectedTitle(); + String actualTitle = seleniumExample.getActualTitle(); + assertEquals(actualTitle, expectedTitle); + } +} diff --git a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java new file mode 100644 index 0000000000..dcdfafc4f1 --- /dev/null +++ b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java @@ -0,0 +1,34 @@ +package com.baeldun.selenium.testng; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +public class TestSeleniumWithTestNG { + + private WebDriver webDriver; + private final String url = "http://www.baeldung.com/"; + private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; + + @BeforeSuite + public void setUp() { + webDriver = new FirefoxDriver(); + webDriver.get(url); + } + + @AfterSuite + public void tearDown() { + webDriver.close(); + } + + @Test + public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { + String actualTitleReturned = webDriver.getTitle(); + assertNotNull(actualTitleReturned); + assertEquals(expectedTitle, actualTitleReturned); + } +} diff --git a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java new file mode 100644 index 0000000000..a7b36c4e4e --- /dev/null +++ b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java @@ -0,0 +1,34 @@ +package com.baeldung.selenium.junit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; + +public class TestSeleniumWithJUnit { + + private WebDriver webDriver; + private final String url = "http://www.baeldung.com/"; + private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; + + @Before + public void setUp() { + webDriver = new FirefoxDriver(); + webDriver.get(url); + } + + @After + public void tearDown() { + webDriver.close(); + } + + @Test + public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { + String actualTitleReturned = webDriver.getTitle(); + assertNotNull(actualTitleReturned); + assertEquals(expectedTitle, actualTitleReturned); + } +} 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-all/pom.xml b/spring-all/pom.xml index 25a45d9bae..c70d9d75fc 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -130,6 +130,13 @@ test + + org.assertj + assertj-core + 3.5.1 + test + + org.hamcrest hamcrest-core diff --git a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java index 2946ab0aa1..8503f75c8f 100644 --- a/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java +++ b/spring-all/src/main/java/org/baeldung/async/AsyncComponent.java @@ -1,11 +1,11 @@ package org.baeldung.async; -import java.util.concurrent.Future; - import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; +import java.util.concurrent.Future; + @Component public class AsyncComponent { @@ -19,7 +19,7 @@ public class AsyncComponent { System.out.println("Execute method asynchronously " + Thread.currentThread().getName()); try { Thread.sleep(5000); - return new AsyncResult("hello world !!!!"); + return new AsyncResult<>("hello world !!!!"); } catch (final InterruptedException e) { } diff --git a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java index 80cb060c7e..8fde925fd8 100644 --- a/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java +++ b/spring-all/src/main/java/org/baeldung/profiles/DatasourceConfig.java @@ -1,5 +1,5 @@ package org.baeldung.profiles; public interface DatasourceConfig { - public void setup(); + void setup(); } diff --git a/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java new file mode 100644 index 0000000000..d4334437f7 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/AllStrategiesExampleBean.java @@ -0,0 +1,33 @@ +package org.baeldung.startup; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +@Scope(value = "prototype") +public class AllStrategiesExampleBean implements InitializingBean { + + private static final Logger LOG = Logger.getLogger(AllStrategiesExampleBean.class); + + public AllStrategiesExampleBean() { + LOG.info("Constructor"); + } + + @Override + public void afterPropertiesSet() throws Exception { + LOG.info("InitializingBean"); + } + + @PostConstruct + public void postConstruct() { + LOG.info("PostConstruct"); + } + + public void init() { + LOG.info("init-method"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/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/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java new file mode 100644 index 0000000000..523a27c2c4 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java @@ -0,0 +1,44 @@ +package org.baeldung.startup; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringStartupTest { + + @Autowired + private ApplicationContext ctx; + + @Test(expected = BeanCreationException.class) + public void whenInstantiating_shouldThrowBCE() throws Exception { + ctx.getBean(InvalidInitExampleBean.class); + } + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(PostConstructExampleBean.class); + } + + @Test + public void whenConstructorInjection_shouldLogEnv() throws Exception { + ctx.getBean(LogicInConstructorExampleBean.class); + } + + @Test + public void whenInitializingBean_shouldLogEnv() throws Exception { + ctx.getBean(InitializingBeanExampleBean.class); + } + + @Test + public void whenApplicationListener_shouldRunOnce() throws Exception { + Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java new file mode 100644 index 0000000000..19a35bb92b --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java @@ -0,0 +1,26 @@ +package org.baeldung.startup; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:startupConfig.xml") +public class SpringStartupXMLConfigTest { + + @Autowired + private ApplicationContext ctx; + + @Test + public void whenPostConstruct_shouldLogEnv() throws Exception { + ctx.getBean(InitMethodExampleBean.class); + } + + @Test + public void whenAllStrategies_shouldLogOrder() throws Exception { + ctx.getBean(AllStrategiesExampleBean.class); + } +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2c5304dbf3..5a20ff5602 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,7 +24,11 @@ 4.3.1.RELEASE
- + + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot spring-boot-starter-web @@ -80,6 +84,17 @@ 3.1.7 test + + + org.webjars + bootstrap + 3.3.4 + + + org.webjars + jquery + 2.1.4 + @@ -112,7 +127,13 @@ maven-war-plugin - + + pl.project13.maven + git-commit-id-plugin + 2.2.1 + + + 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/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-cloud-config/README.md b/spring-cloud-config/README.md new file mode 100644 index 0000000000..b8ebb2bfe9 --- /dev/null +++ b/spring-cloud-config/README.md @@ -0,0 +1,27 @@ +## Spring Cloud Config ## + +To get this example working, you have to initialize a new *Git* repository in +the ```client-config``` directory first *and* you have to set the environment variable +```CONFIG_REPO``` to an absolute path of that directory. + +``` +$> cd client-config +$> git init +$> git add . +$> git commit -m 'Initial commit' +$> export CONFIG_REPO=$(pwd) +``` + +Then you're able to run the examples with ```mvn install spring-boot:run```. + +### Docker ### + +To get the *Docker* examples working, you have to repackage the ```spring-cloud-config-server``` +and ```spring-cloud-config-client``` modules first: + +``` +$> mvn install spring-boot:repackage +``` + +Don't forget to download the *Java JCE* package from +(Oracle)[http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html]. diff --git a/spring-cloud-config/docker/Dockerfile.client b/spring-cloud-config/docker/Dockerfile.client new file mode 100644 index 0000000000..0f9293bd22 --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.client @@ -0,0 +1,6 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +RUN apk --no-cache add netcat-openbsd +COPY files/spring-cloud-config-client-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-client.jar +COPY files/config-client-entrypoint.sh /opt/spring-cloud/bin/ +RUN chmod 755 /opt/spring-cloud/bin/config-client-entrypoint.sh diff --git a/spring-cloud-config/docker/Dockerfile.server b/spring-cloud-config/docker/Dockerfile.server new file mode 100644 index 0000000000..90d7e2a7cf --- /dev/null +++ b/spring-cloud-config/docker/Dockerfile.server @@ -0,0 +1,9 @@ +FROM alpine-java:base +MAINTAINER baeldung.com +COPY files/spring-cloud-config-server-1.0.0-SNAPSHOT.jar /opt/spring-cloud/lib/config-server.jar +ENV SPRING_APPLICATION_JSON='{"spring": {"cloud": {"config": {"server": \ + {"git": {"uri": "/var/lib/spring-cloud/config-repo", "clone-on-start": true}}}}}}' +ENTRYPOINT ["/usr/bin/java"] +CMD ["-jar", "/opt/spring-cloud/lib/config-server.jar"] +VOLUME /var/lib/spring-cloud/config-repo +EXPOSE 8888 diff --git a/spring-cloud-config/docker/files/.gitignore b/spring-cloud-config/docker/files/.gitignore new file mode 100644 index 0000000000..28ffcbffdb --- /dev/null +++ b/spring-cloud-config/docker/files/.gitignore @@ -0,0 +1,2 @@ +/UnlimitedJCEPolicyJDK8 +/*.jar diff --git a/spring-cloud-config/docker/files/config-client-entrypoint.sh b/spring-cloud-config/docker/files/config-client-entrypoint.sh new file mode 100644 index 0000000000..12352119fa --- /dev/null +++ b/spring-cloud-config/docker/files/config-client-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +while ! nc -z config-server 8888 ; do + echo "Waiting for upcoming Config Server" + sleep 2 +done + +java -jar /opt/spring-cloud/lib/config-client.jar diff --git a/spring-cloud-config/pom.xml b/spring-cloud-config/pom.xml index 8e0e4b8706..3b1b59b037 100644 --- a/spring-cloud-config/pom.xml +++ b/spring-cloud-config/pom.xml @@ -5,38 +5,48 @@ com.baeldung.spring.cloud spring-cloud-config - 0.0.1-SNAPSHOT pom - server - client + spring-cloud-config-server + spring-cloud-config-client - org.springframework.boot - spring-boot-starter-parent - 1.3.5.RELEASE + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + org.springframework.boot + spring-boot-parent + 1.4.0.RELEASE + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR4 + pom + import + + + + - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*LiveTest.java - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.0.RELEASE + + + - - - 1.3.5.RELEASE - 2.19.1 -
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..3e8cd21b82 --- /dev/null +++ b/spring-cloud/README.md @@ -0,0 +1,18 @@ +## The Module Holds Sources for the Following Articles + +- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) + + Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. + + In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. + +- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) + + In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. + + Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. + +- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) + + diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml new file mode 100644 index 0000000000..2349613def --- /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-bootstrap + + 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-bootstrap/application-config/discovery.properties b/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties new file mode 100644 index 0000000000..7f3df86c7e --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/application-config/gateway.properties b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties new file mode 100644 index 0000000000..77faec8421 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/application-config/resource.properties b/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties new file mode 100644 index 0000000000..4e6cf3817c --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml new file mode 100644 index 0000000000..0cb217acfb --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/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-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties new file mode 100644 index 0000000000..6f614d0690 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml new file mode 100644 index 0000000000..ee7c589549 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/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-bootstrap/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..ca9d59c9ed --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml new file mode 100644 index 0000000000..8e56d0fd35 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/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-bootstrap/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..9610d72675 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml new file mode 100644 index 0000000000..c14c277d7f --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + + + + config + discovery + gateway + resource + + + + spring-cloud-integration + 1.0.0-SNAPSHOT + pom + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/resource/pom.xml b/spring-cloud/spring-cloud-bootstrap/resource/pom.xml new file mode 100644 index 0000000000..78112fa3e0 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/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-bootstrap/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-bootstrap/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..3c88a0b520 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/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-config/client-config/config-client-development.properties b/spring-cloud/spring-cloud-config/client-config/config-client-development.properties similarity index 100% rename from spring-cloud-config/client-config/config-client-development.properties rename to spring-cloud/spring-cloud-config/client-config/config-client-development.properties diff --git a/spring-cloud-config/client-config/config-client-production.properties b/spring-cloud/spring-cloud-config/client-config/config-client-production.properties similarity index 100% rename from spring-cloud-config/client-config/config-client-production.properties rename to spring-cloud/spring-cloud-config/client-config/config-client-production.properties diff --git a/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml similarity index 100% rename from spring-cloud-config/client/pom.xml rename to spring-cloud/spring-cloud-config/client/pom.xml diff --git a/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 similarity index 100% rename from spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java rename to spring-cloud/spring-cloud-config/client/src/main/java/com/baeldung/spring/cloud/config/client/ConfigClient.java diff --git a/spring-cloud-config/client/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud-config/client/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties diff --git a/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 similarity index 100% rename from spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java rename to spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java 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-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml similarity index 100% rename from spring-cloud-config/server/pom.xml rename to spring-cloud/spring-cloud-config/server/pom.xml diff --git a/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 similarity index 100% rename from spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java rename to spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java diff --git a/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties similarity index 100% rename from spring-cloud-config/server/src/main/resources/application.properties rename to spring-cloud/spring-cloud-config/server/src/main/resources/application.properties diff --git a/spring-cloud-config/server/src/main/resources/config-server.jks b/spring-cloud/spring-cloud-config/server/src/main/resources/config-server.jks similarity index 100% rename from spring-cloud-config/server/src/main/resources/config-server.jks rename to spring-cloud/spring-cloud-config/server/src/main/resources/config-server.jks diff --git a/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 similarity index 100% rename from spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java rename to spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListTest.java 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-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 3a6e330564..084695c2f3 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -69,6 +69,17 @@ log4j-over-slf4j ${org.slf4j.version} + + + org.elasticsearch + elasticsearch + 2.3.5 + + + com.alibaba + fastjson + 1.2.13 + diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java new file mode 100644 index 0000000000..b8ad59e2e2 --- /dev/null +++ b/spring-data-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/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java new file mode 100644 index 0000000000..db304ee78d --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -0,0 +1,127 @@ +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.Arrays; +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(); + List searchHits = Arrays.asList(response.getHits().getHits()); + final List results = new ArrayList(); + searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class))); + } 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/spring-data-neo4j/README.md b/spring-data-neo4j/README.md index e62c69f8b9..0f13d9dbc9 100644 --- a/spring-data-neo4j/README.md +++ b/spring-data-neo4j/README.md @@ -1,7 +1,7 @@ ## Spring Data Neo4j ### Relevant Articles: -- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-tutorial) +- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro) ### Build the Project with Tests Running ``` 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/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-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 32897e9e35..0000000000 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.ex.nontransientdataaccessexception; - -import java.util.logging.Level; -import java.util.logging.Logger; - -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.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 { - - private static final Logger LOG = Logger.getLogger(CleanupFailureExceptionTest.class.getName()); - - @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 CleanupFailureDataAccessException exc) { - LOG.log(Level.SEVERE, exc.getMessage()); - } - } - } -} 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-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/pom.xml b/spring-jpa/pom.xml index 25dd960435..ebb9c5bc83 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -4,6 +4,7 @@ com.baeldung spring-jpa 0.1-SNAPSHOT + war spring-jpa @@ -21,6 +22,11 @@ spring-context ${org.springframework.version} + + org.springframework + spring-webmvc + ${org.springframework.version} + @@ -29,6 +35,11 @@ hibernate-entitymanager ${hibernate.version} + + org.hibernate + hibernate-ehcache + ${hibernate.version} + xml-apis xml-apis @@ -50,6 +61,11 @@ spring-data-jpa ${spring-data-jpa.version} + + com.h2database + h2 + ${h2.version} + @@ -63,6 +79,18 @@ javax.el-api 2.2.5 + + + + javax.servlet + jstl + ${javax.servlet.jstl.version} + + + javax.servlet + servlet-api + ${javax.servlet.servlet-api.version} + @@ -137,6 +165,16 @@ 1.8 + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + org.apache.maven.plugins @@ -179,13 +217,18 @@ - 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.2 + 2.5 1.7.13 @@ -213,6 +256,7 @@ 2.19.1 2.7 1.4.18 + 2.4 diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java new file mode 100644 index 0000000000..7f28c958f1 --- /dev/null +++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java @@ -0,0 +1,72 @@ +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() throws NamingException { + 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() throws NamingException { + return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url")); + } + + @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/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/config/SpringWebConfig.java b/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java new file mode 100644 index 0000000000..6afb271b10 --- /dev/null +++ b/spring-jpa/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/src/main/java/org/baeldung/config/WebInitializer.java b/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java new file mode 100644 index 0000000000..1c8ce5400f --- /dev/null +++ b/spring-jpa/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/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/java/org/baeldung/web/MainController.java b/spring-jpa/src/main/java/org/baeldung/web/MainController.java new file mode 100644 index 0000000000..6900482de8 --- /dev/null +++ b/spring-jpa/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/src/main/resources/context.xml b/spring-jpa/src/main/resources/context.xml new file mode 100644 index 0000000000..a64dfe9a61 --- /dev/null +++ b/spring-jpa/src/main/resources/context.xml @@ -0,0 +1 @@ + \ No newline at end of file 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-jndi.properties b/spring-jpa/src/main/resources/persistence-jndi.properties new file mode 100644 index 0000000000..16d750d7f8 --- /dev/null +++ b/spring-jpa/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/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/main/resources/server.xml b/spring-jpa/src/main/resources/server.xml new file mode 100644 index 0000000000..5c61659018 --- /dev/null +++ b/spring-jpa/src/main/resources/server.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp b/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp new file mode 100644 index 0000000000..f2ec8e2bec --- /dev/null +++ b/spring-jpa/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/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/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/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/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/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-tiles/pom.xml b/spring-mvc-tiles/pom.xml new file mode 100644 index 0000000000..1a72549e70 --- /dev/null +++ b/spring-mvc-tiles/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + com.baeldung + spring-mvc-tiles + 0.0.1-SNAPSHOT + war + spring-mvc-tiles + Integrating Spring MVC with Apache Tiles + + + 4.3.2.RELEASE + 3.0.5 + + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.tiles + tiles-jsp + ${apachetiles.version} + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-mvc-tiles + false + + + + + spring-mvc-tiles + + diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java new file mode 100644 index 0000000000..d2e90a4f53 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java @@ -0,0 +1,47 @@ +package com.baeldung.tiles.springmvc; + +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.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") +public class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java new file mode 100644 index 0000000000..1a348d1c26 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java @@ -0,0 +1,26 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class ApplicationController { + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java new file mode 100644 index 0000000000..79583dbe83 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java @@ -0,0 +1,22 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { ApplicationConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp new file mode 100644 index 0000000000..9936957c04 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

Tiles with Spring MVC Demo

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp new file mode 100644 index 0000000000..b501d4968e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

Welcome to Apache Tiles integration with Spring MVC

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp new file mode 100644 index 0000000000..209b1004de --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

Spring MVC configured to work with Apache Tiles

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp new file mode 100644 index 0000000000..2370ad4ab1 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
+ + +
+ +
+ +
+ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp new file mode 100644 index 0000000000..3849cc5230 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -0,0 +1,2 @@ + +
copyright © Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp new file mode 100644 index 0000000000..8a878c857d --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -0,0 +1,3 @@ +
+

Welcome to Spring MVC integration with Apache Tiles

+
\ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp new file mode 100644 index 0000000000..2c91eace85 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -0,0 +1,8 @@ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml new file mode 100644 index 0000000000..789fbd809a --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-tiles/src/main/webapp/static/css/app.css new file mode 100644 index 0000000000..9976e5406e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/static/css/app.css @@ -0,0 +1,36 @@ +.flex-container { + display: -webkit-flex; + display: flex; + -webkit-flex-flow: row wrap; + flex-flow: row wrap; + text-align: center; +} + +.flex-container > * { + padding: 15px; + -webkit-flex: 1 100%; + flex: 1 100%; +} + +.article { + text-align: left; +} + +header {background: black;color:white;} +footer {background: #aaa;color:white;} +.nav {background:#eee;} + +.nav ul { + list-style-type: none; + padding: 0; +} + +.nav ul a { + text-decoration: none; +} + +@media all and (min-width: 768px) { + .nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;} + .article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;} + footer {-webkit-order:3;order:3;} +} \ No newline at end of file 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/pom.xml b/spring-rest/pom.xml index e28f7e7e33..18cb1dc72a 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 @@ -172,7 +182,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -182,16 +191,14 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} - + **/*LiveTest.java @@ -206,7 +213,7 @@ true - jetty8x + tomcat8x embedded @@ -224,6 +231,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + @@ -231,10 +293,6 @@ 4.3.11.Final 5.1.39 - - - 2.7.2 - 5.2.2.Final @@ -260,7 +318,7 @@ 3.5.1 2.6 2.19.1 - 1.4.18 + 1.6.0 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 d5cd6e1eae..d116148f09 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -15,6 +15,11 @@ 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" }) 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/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/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/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..3155b5cda9 --- /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:8082/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/SpringHttpMessageConvertersLiveTest.java similarity index 78% rename from spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java rename to spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java index 1536f14bc8..7f250653ab 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.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,19 +15,15 @@ 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; /** * Integration Test class. Tests methods hits the server's rest services. */ -public class SpringHttpMessageConvertersIntegrationTestsCase { +public class SpringHttpMessageConvertersLiveTest { - private static String BASE_URI = "http://localhost:8080/spring-rest/"; + private static String BASE_URI = "http://localhost:8082/spring-rest/"; /** * Without specifying Accept Header, uses the default response from the @@ -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-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/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/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-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index 2baf88a62d..c662c32738 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -1,11 +1,5 @@ package org.baeldung.service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.baeldung.security.SecurityRole; @@ -17,9 +11,9 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -/** - * User Details Service - hard coded to two users for the example. - */ +import java.util.*; +import java.util.stream.Collectors; + @Service public class MyUserDetailsService implements UserDetailsService { @@ -28,24 +22,19 @@ public class MyUserDetailsService implements UserDetailsService { private final Map availableUsers = new HashMap(); public MyUserDetailsService() { - populateDemoUsers(); - } - // - @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { - throw new UsernameNotFoundException("Username not found"); - } else { - return availableUsers.get(username); + throw new UsernameNotFoundException(username); } + return user; } /** @@ -59,24 +48,13 @@ public class MyUserDetailsService implements UserDetailsService { availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } - /** - * Create a demo User. - * - * @param username - * Username - * @param password - * Password - * @param roles - * Role names user is assigned to - * @return User - */ private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = new ArrayList(); - for (final SecurityRole role : roles) { - authorities.add(new SimpleGrantedAuthority(role.toString())); - } + final List authorities = roles.stream() + .map(role -> new SimpleGrantedAuthority(role.toString())) + .collect(Collectors.toList()); + return new User(username, password, true, true, true, true, authorities); } } 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/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/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/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/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..f5c1626989 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -0,0 +1,56 @@ +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("Time since last request in this session: {} ms", + System.currentTimeMillis() - request.getSession().getLastAccessedTime()); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + 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: {} ms", System.currentTimeMillis() - startTime); + } +} 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..13cb92a745 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 @@ -14,6 +14,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.core.JsonProcessingException; @@ -21,32 +22,33 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration +@Transactional 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/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/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 51e26fdfdd..a13f1de4c7 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,59 +5,69 @@ spring-thymeleaf 0.1-SNAPSHOT war - - 1.7 - - 4.1.8.RELEASE - 3.0.1 - + + 1.8 + + 4.3.3.RELEASE + 3.0.1 + 1.7.12 1.1.3 - - 2.1.4.RELEASE - - 1.1.0.Final - 5.1.2.Final - - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 - - - - - - org.springframework - spring-context - ${org.springframework-version} - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - ${org.springframework-version} - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - + + 3.0.1.RELEASE + + 1.1.0.Final + 5.1.2.Final + + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + + + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.springframework.security + spring-security-web + 4.1.3.RELEASE + + + org.springframework.security + spring-security-config + 4.1.3.RELEASE + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + org.slf4j slf4j-api @@ -80,55 +90,81 @@ log4j-over-slf4j ${org.slf4j.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-version} - provided - - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${org.hibernate-version} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-version} - ${java-version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + + + + org.springframework + spring-test + 4.1.3.RELEASE + test + + + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + + + + + junit + junit + 4.12 + test + + +
+ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + org.codehaus.cargo cargo-maven2-plugin @@ -148,6 +184,7 @@ - - + + + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java new file mode 100644 index 0000000000..956db4a0e5 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class InitSecurity extends AbstractSecurityWebApplicationInitializer { + + public InitSecurity() { + super(WebMVCSecurity.class); + + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java index 89ad7e601e..3104f45ab5 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java @@ -9,28 +9,28 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche */ public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { - public WebApp() { - super(); - } + public WebApp() { + super(); + } - @Override - protected Class[] getRootConfigClasses() { - return null; - } + @Override + protected Class[] getRootConfigClasses() { + return null; + } - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { WebMVCConfig.class }; - } + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }; + } - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } - @Override - protected void customizeRegistration(final Dynamic registration) { - super.customizeRegistration(registration); - } + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 51c60247a1..444b780673 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -1,18 +1,27 @@ package com.baeldung.thymeleaf.config; -import com.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.TemplateEngine; import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import com.baeldung.thymeleaf.formatter.NameFormatter; +import com.baeldung.thymeleaf.utils.ArrayUtil; + @Configuration @EnableWebMvc @@ -21,36 +30,76 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; * Java configuration file that is used for Spring MVC and Thymeleaf * configurations */ -public class WebMVCConfig extends WebMvcConfigurerAdapter { +public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { - @Bean - @Description("Thymeleaf Template Resolver") - public ServletContextTemplateResolver templateResolver() { - ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/views/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); + private ApplicationContext applicationContext; - return templateResolver; + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; } @Bean - @Description("Thymeleaf Template Engine") - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - - return templateEngine; + public ViewResolver htmlViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); + resolver.setContentType("text/html"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.html")); + return resolver; } - + @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + public ViewResolver javascriptViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver())); + resolver.setContentType("application/javascript"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.js")); + return resolver; + } + + @Bean + public ViewResolver plainViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(plainTemplateResolver())); + resolver.setContentType("text/plain"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.txt")); + return resolver; + } + + private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setTemplateResolver(templateResolver); + return engine; + } + + private ITemplateResolver htmlTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } + + private ITemplateResolver javascriptTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/js/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.JAVASCRIPT); + return resolver; + } + + private ITemplateResolver plainTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/txt/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.TEXT); + return resolver; + } @Bean @Description("Spring Message Resolver") diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java new file mode 100644 index 0000000000..37844a2976 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -0,0 +1,49 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) +public class WebMVCSecurity extends WebSecurityConfigurerAdapter { + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + public WebMVCSecurity() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER"); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .httpBasic() + ; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index a28d059acc..f1a394cac4 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -21,7 +21,7 @@ public class HomeController { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); model.addAttribute("serverTime", dateFormat.format(new Date())); - return "home"; + return "home.html"; } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java new file mode 100644 index 0000000000..9e3f14ac8e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java @@ -0,0 +1,33 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.thymeleaf.utils.StudentUtils; + +@Controller +public class InliningController { + + @RequestMapping(value = "/html", method = RequestMethod.GET) + public String getExampleHTML(Model model) { + model.addAttribute("title", "Baeldung"); + model.addAttribute("description", "Thymeleaf tutorial"); + return "inliningExample.html"; + } + + @RequestMapping(value = "/js", method = RequestMethod.GET) + public String getExampleJS(Model model) { + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentCheck.js"; + } + + @RequestMapping(value = "/plain", method = RequestMethod.GET) + public String getExamplePlain(Model model) { + model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName()); + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentsList.txt"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 912eb521f4..1f40046caa 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,11 +1,9 @@ package com.baeldung.thymeleaf.controller; -import java.util.ArrayList; import java.util.List; import javax.validation.Valid; -import com.baeldung.thymeleaf.model.Student; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -13,6 +11,9 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.thymeleaf.model.Student; +import com.baeldung.thymeleaf.utils.StudentUtils; + /** * Handles requests for the student model. * @@ -24,46 +25,26 @@ public class StudentController { public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { if (!errors.hasErrors()) { // get mock objects - List students = buildStudents(); + List students = StudentUtils.buildStudents(); // add current student students.add(student); model.addAttribute("students", students); } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html"); } @RequestMapping(value = "/addStudent", method = RequestMethod.GET) public String addStudent(Model model) { model.addAttribute("student", new Student()); - return "addStudent"; + return "addStudent.html"; } @RequestMapping(value = "/listStudents", method = RequestMethod.GET) public String listStudent(Model model) { - model.addAttribute("students", buildStudents()); + model.addAttribute("students", StudentUtils.buildStudents()); - return "listStudents"; + return "listStudents.html"; } - private List buildStudents() { - List students = new ArrayList(); - - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); - - students.add(student1); - - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); - - students.add(student2); - return students; - } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java index bce99f286c..202c04358a 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java @@ -12,49 +12,49 @@ import javax.validation.constraints.NotNull; */ public class Student implements Serializable { - private static final long serialVersionUID = -8582553475226281591L; + private static final long serialVersionUID = -8582553475226281591L; - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be at least 4 digits.") - private Integer id; + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") + private Integer id; - @NotNull(message = "Student name is required.") - private String name; + @NotNull(message = "Student name is required.") + private String name; - @NotNull(message = "Student gender is required.") - private Character gender; + @NotNull(message = "Student gender is required.") + private Character gender; - private Float percentage; + private Float percentage; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Character getGender() { - return gender; - } + public Character getGender() { + return gender; + } - public void setGender(Character gender) { - this.gender = gender; - } + public void setGender(Character gender) { + this.gender = gender; + } - public Float getPercentage() { - return percentage; - } + public Float getPercentage() { + return percentage; + } - public void setPercentage(Float percentage) { - this.percentage = percentage; - } + public void setPercentage(Float percentage) { + this.percentage = percentage; + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java new file mode 100644 index 0000000000..d85c70c1b7 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java @@ -0,0 +1,8 @@ +package com.baeldung.thymeleaf.utils; + +public class ArrayUtil { + + public static String[] array(String... args) { + return args; + } +} \ No newline at end of file diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java new file mode 100644 index 0000000000..f7ed254641 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.thymeleaf.model.Student; + +public class StudentUtils { + + private static List students = new ArrayList(); + + public static List buildStudents() { + if (students.isEmpty()){ + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + } + + return students; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js new file mode 100644 index 0000000000..625e0b37e5 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js @@ -0,0 +1,2 @@ +var count = [[${students.size()}]]; +alert("Number of students in group: " + count); diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt new file mode 100644 index 0000000000..b27796c6ab --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt @@ -0,0 +1,8 @@ +Dear [(${username})], + +This is the list of our students: +[# th:each="s : ${students}"] + - [(${s.name})]. ID: [(${s.id})] +[/] +Thanks, +The Baeldung University \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html new file mode 100644 index 0000000000..7674caa854 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html @@ -0,0 +1,12 @@ + + + + + + +
+ + +
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html new file mode 100644 index 0000000000..cd20746c3a --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html @@ -0,0 +1,12 @@ + + + + +Inlining example + + +

Title of tutorial: [[${title}]]

+

Description: [(${description})]

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html index c25de9eb17..a894e41e88 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -4,6 +4,15 @@ Student List + +

Student List

diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java new file mode 100644 index 0000000000..3542571bbc --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -0,0 +1,78 @@ +package org.baeldung.security.csrf; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +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.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class CsrfEnabledIntegrationTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void addStudentWithoutCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden()); + } + + @Test + public void addStudentWithCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); + } + + @Test + public void htmlInliningTest() throws Exception { + mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); + } + + @Test + public void jsInliningTest() throws Exception { + mockMvc.perform(get("/js").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentCheck.js")); + } + + @Test + public void plainInliningTest() throws Exception { + mockMvc.perform(get("/plain").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentsList.txt")); + } + +} diff --git a/spring-userservice/.springBeans b/spring-userservice/.springBeans new file mode 100644 index 0000000000..ff32b84d3b --- /dev/null +++ b/spring-userservice/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/spring-userservice/README.md b/spring-userservice/README.md new file mode 100644 index 0000000000..097afc5fc1 --- /dev/null +++ b/spring-userservice/README.md @@ -0,0 +1 @@ +spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml new file mode 100644 index 0000000000..93b01ee49c --- /dev/null +++ b/spring-userservice/pom.xml @@ -0,0 +1,320 @@ + + 4.0.0 + spring-userservice + spring-userservice + 0.0.1-SNAPSHOT + war + + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + org.hibernate + hibernate-ehcache + ${hibernate.version} + + + xml-apis + xml-apis + 1.4.01 + + + org.javassist + javassist + ${javassist.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + runtime + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + com.h2database + h2 + ${h2.version} + + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + 2.2.5 + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + + 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 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + + org.springframework.boot + spring-boot-test + 1.4.1.RELEASE + + + org.springframework.boot + spring-boot + 1.4.1.RELEASE + + + javax.servlet + javax.servlet-api + 3.1.0 + + + + + spring-userservice + + + 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} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + + 4.1.3.RELEASE + 4.3.2.RELEASE + 3.20.0-GA + + + 5.2.2.Final + 5.1.38 + 1.10.2.RELEASE + 1.4.192 + + + 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-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java new file mode 100644 index 0000000000..4a9e737a92 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.custom.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 = { "org.baeldung.security" }) +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/"); + registry.addViewController("/index"); + registry.addViewController("/login"); + registry.addViewController("/register"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java new file mode 100644 index 0000000000..6be7053b78 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -0,0 +1,89 @@ +package org.baeldung.custom.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +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.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 com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceDerbyJPAConfig { + + @Autowired + private Environment env; + + public PersistenceDerbyJPAConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + 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"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + 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.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public MyUserDAO myUserDAO() { + final MyUserDAO myUserDAO = new MyUserDAO(); + return myUserDAO; + } +} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java new file mode 100644 index 0000000000..44df02980f --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.custom.config; + +import org.baeldung.security.MyUserDetailsService; +import org.baeldung.user.service.MyUserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.authenticationProvider(authenticationProvider()); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/*").permitAll() + .and() + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .defaultSuccessUrl("/",true) + .failureUrl("/login?error=true") + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/"); + // @formatter:on + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(myUserDetailsService()); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public MyUserDetailsService myUserDetailsService() { + return new MyUserDetailsService(); + } + + @Bean + public MyUserService myUserService() { + return new MyUserService(); + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java new file mode 100644 index 0000000000..804d391641 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -0,0 +1,50 @@ +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; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_custom_user_service") +public class MyUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + public MyUser() { + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..fe97984af8 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,35 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +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; +import org.springframework.stereotype.Service; + +@Service("userDetailsService") +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + MyUserDAO myUserDAO; + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final MyUser user = myUserDAO.findByUsername(username); + + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + username); + } + return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java new file mode 100644 index 0000000000..b1c96e72c0 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/UserController.java @@ -0,0 +1,52 @@ +package org.baeldung.security; + +import javax.annotation.Resource; + +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class UserController { + + @Resource + MyUserService myUserService; + + @RequestMapping(value = "/register", method = RequestMethod.POST) + public String registerUserAccount(final MyUserDto accountDto, final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + try { + myUserService.registerNewUserAccount(accountDto); + model.addAttribute("message", "Registration successful"); + return "index"; + } + catch(final Exception exc){ + model.addAttribute("message", "Registration failed"); + + return "index"; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHomepage(final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + return "index"; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String getRegister() { + return "register"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String getLogin() { + return "login"; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java new file mode 100644 index 0000000000..4cc9f61b4a --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -0,0 +1,46 @@ +package org.baeldung.user.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.MyUser; +import org.springframework.stereotype.Repository; + +@Repository +public class MyUserDAO { + + @PersistenceContext + private EntityManager entityManager; + + public MyUser findByUsername(final String username) { + final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); + query.setParameter("username", username); + final List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public MyUser save(final MyUser user) { + entityManager.persist(user); + return user; + } + + public void removeUserByUsername(String username) { + final Query query = entityManager.createQuery("delete from MyUser where username=:username"); + query.setParameter("username", username); + query.executeUpdate(); + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(final EntityManager entityManager) { + this.entityManager = entityManager; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java new file mode 100644 index 0000000000..1e05541998 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -0,0 +1,49 @@ +package org.baeldung.user.service; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.baeldung.web.MyUserDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class MyUserService { + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + MyUserDAO myUserDAO; + + public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { + if (usernameExists(accountDto.getUsername())) { + throw new Exception("There is an account with that username: " + accountDto.getUsername()); + } + final MyUser user = new MyUser(); + + user.setUsername(accountDto.getUsername()); + user.setPassword(passwordEncoder.encode(accountDto.getPassword())); + return myUserDAO.save(user); + } + + public MyUser getUserByUsername(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + return user; + } + + public void removeUserByUsername(String username){ + myUserDAO.removeUserByUsername(username); + } + + private boolean usernameExists(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + if (user != null) { + return true; + } + return false; + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java new file mode 100644 index 0000000000..c572208913 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java @@ -0,0 +1,29 @@ +package org.baeldung.web; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class MyUserDto { + @NotNull + @Size(min = 1) + private String username; + + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + +} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-userservice/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml new file mode 100644 index 0000000000..25d1d4d22f --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} + + + + + + + + + + + + + + + + + + + diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000000..0c89257cd2 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + +Welcome! + + + + + + + +Register +

+ +Login + +

+${message } +

+ +Hello, ${name }! +
+
+Logout +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..29431f426d --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,29 @@ +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + + +

Login

+ +
+ +
+ + + + + + + + + + + +
User:
Password:
+ + + Username or password invalid! + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp new file mode 100644 index 0000000000..e6e9d373a0 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Welcome! + + + + + +Register here:

+
+Username:
+Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b526774179 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + Spring MVC Application + + + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + index.jsp + + + \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..6e1cd67e06 --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java @@ -0,0 +1,85 @@ +package org.baeldung.userservice; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +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.dao.DuplicateKeyException; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; + + @Autowired + MyUserService myUserService; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Test + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + myUserService.registerNewUserAccount(userDTO); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + + } catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } finally { + myUserService.removeUserByUsername(USERNAME); + } + } + + @Test (expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + try { + myUserService.registerNewUserAccount(userDTO); + } + catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + } + finally { + myUserService.removeUserByUsername(USERNAME); + } + } + +} 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 - - - - - - diff --git a/wicket/README.md b/wicket/README.md new file mode 100644 index 0000000000..614446e7ba --- /dev/null +++ b/wicket/README.md @@ -0,0 +1,4 @@ + +From the same directory where pom.xml is, execute the following command to run the project: + +mvn jetty:run diff --git a/wicket/pom.xml b/wicket/pom.xml new file mode 100644 index 0000000000..929f723c2c --- /dev/null +++ b/wicket/pom.xml @@ -0,0 +1,106 @@ + + + + 4.0.0 + com.baeldung.wicket.examples + wicket-intro + war + 1.0-SNAPSHOT + WicketIntro + + 7.4.0 + 9.2.13.v20150730 + 2.5 + 4.12 + 3.5.1 + 2.6 + UTF-8 + + + + + org.apache.wicket + wicket-core + ${wicket.version} + + + + + junit + junit + ${junit.version} + test + + + + + org.eclipse.jetty.aggregate + jetty-all + ${jetty9.version} + test + + + + + + false + src/main/resources + + + false + src/main/java + + ** + + + **/*.java + + + + + + false + src/test/resources + + + false + src/test/java + + ** + + + **/*.java + + + + + + true + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + UTF-8 + true + true + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty9.version} + + + + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.html b/wicket/src/main/java/com/baeldung/wicket/examples/Examples.html new file mode 100644 index 0000000000..497e98e01a --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/Examples.html @@ -0,0 +1,52 @@ + + + + +Wicket Intro Examples + + + +
+
+
+

Wicket Introduction Examples:

+ + Hello World! +
+
+ Cafes +
+
+
+
+ + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java b/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java new file mode 100644 index 0000000000..358e4f7b19 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java @@ -0,0 +1,9 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.markup.html.WebPage; + +public class Examples extends WebPage { + + private static final long serialVersionUID = 1L; + +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java b/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java new file mode 100644 index 0000000000..711e8f01fd --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java @@ -0,0 +1,27 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.protocol.http.WebApplication; + +import com.baeldung.wicket.examples.cafeaddress.CafeAddress; +import com.baeldung.wicket.examples.helloworld.HelloWorld; + +public class ExamplesApplication extends WebApplication { + /** + * @see org.apache.wicket.Application#getHomePage() + */ + @Override + public Class getHomePage() { + return Examples.class; + } + + /** + * @see org.apache.wicket.Application#init() + */ + @Override + public void init() { + super.init(); + mountPage("/examples/helloworld", HelloWorld.class); + mountPage("/examples/cafes", CafeAddress.class); + } +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html new file mode 100644 index 0000000000..c5ada2323d --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html @@ -0,0 +1,15 @@ + + + + +Cafes + + +
+ +

+ Address: address +

+
+ + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java new file mode 100644 index 0000000000..ce26c5a1ad --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java @@ -0,0 +1,72 @@ +package com.baeldung.wicket.examples.cafeaddress; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +public class CafeAddress extends WebPage { + + private static final long serialVersionUID = 1L; + + String selectedCafe; + Address address; + Map cafeNamesAndAddresses = new HashMap<>(); + + public CafeAddress(final PageParameters parameters) { + super(parameters); + initCafes(); + + ArrayList cafeNames = new ArrayList<>(this.cafeNamesAndAddresses.keySet()); + this.selectedCafe = cafeNames.get(0); + this.address = new Address(this.cafeNamesAndAddresses.get(this.selectedCafe).getAddress()); + + final Label addressLabel = new Label("address", new PropertyModel(this.address, "address")); + addressLabel.setOutputMarkupId(true); + + final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel(this, "selectedCafe"), cafeNames); + cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") { + private static final long serialVersionUID = 1L; + + @Override + protected void onUpdate(AjaxRequestTarget target) { + String name = (String) cafeDropdown.getDefaultModel().getObject(); + address.setAddress(cafeNamesAndAddresses.get(name).getAddress()); + target.add(addressLabel); + } + }); + + add(addressLabel); + add(cafeDropdown); + + } + + private void initCafes() { + this.cafeNamesAndAddresses.put("Linda's Cafe", new Address("35 Bower St.")); + this.cafeNamesAndAddresses.put("Old Tree", new Address("2 Edgware Rd.")); + } + + class Address implements Serializable { + private String sAddress = ""; + + public Address(String address) { + this.sAddress = address; + } + + public String getAddress() { + return this.sAddress; + } + + public void setAddress(String address) { + this.sAddress = address; + } + } +} diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html new file mode 100644 index 0000000000..c56d07fc10 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.html @@ -0,0 +1,5 @@ + + + + + diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java new file mode 100644 index 0000000000..f819e05be6 --- /dev/null +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java @@ -0,0 +1,13 @@ +package com.baeldung.wicket.examples.helloworld; + +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.basic.Label; + +public class HelloWorld extends WebPage { + + private static final long serialVersionUID = 1L; + + public HelloWorld() { + add(new Label("hello", "Hello World!")); + } +} diff --git a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java new file mode 100644 index 0000000000..a393f1d178 --- /dev/null +++ b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java @@ -0,0 +1,23 @@ +package com.baeldung.wicket.examples; + +import org.apache.wicket.util.tester.WicketTester; +import org.junit.Before; +import org.junit.Test; + +public class TestHomePage { + private WicketTester tester; + + @Before + public void setUp() { + tester = new WicketTester(new ExamplesApplication()); + } + + @Test + public void whenPageInvoked_thanRenderedOK() { + //start and render the test page + tester.startPage(Examples.class); + + //assert rendered page class + tester.assertRenderedPage(Examples.class); + } +} diff --git a/wicket/src/main/webapp/WEB-INF/web.xml b/wicket/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..8a4451c80e --- /dev/null +++ b/wicket/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,32 @@ + + + + CafeAddress + + + + + wicket.examples + org.apache.wicket.protocol.http.WicketFilter + + applicationClassName + com.baeldung.wicket.examples.ExamplesApplication + + + + + wicket.examples + /* + + \ No newline at end of file