diff --git a/README.md b/README.md index 62d2d5b55e..1d916c8409 100644 --- a/README.md +++ b/README.md @@ -39,3 +39,4 @@ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloud - [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) - [Apache Maven Tutorial](http://www.baeldung.com/maven) +- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) diff --git a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java similarity index 97% rename from core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java rename to algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java index 4cfa0d411b..7e25e0456b 100644 --- a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java @@ -1,10 +1,8 @@ -package com.baeldung.linkedlist; +package com.baeldung.algorithms.middleelementlookup; import java.util.LinkedList; import java.util.Optional; -import com.baeldung.linkedlist.Node; - public class MiddleElementLookup { public static Optional findMiddleElementLinkedList(LinkedList linkedList) { diff --git a/core-java/src/main/java/com/baeldung/linkedlist/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java similarity index 90% rename from core-java/src/main/java/com/baeldung/linkedlist/Node.java rename to algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java index daceaffdcd..2a594937e3 100644 --- a/core-java/src/main/java/com/baeldung/linkedlist/Node.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java @@ -1,4 +1,4 @@ -package com.baeldung.linkedlist; +package com.baeldung.algorithms.middleelementlookup; public class Node { private Node next; diff --git a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java rename to algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java index 2801bbfc9e..01f9ca2f76 100644 --- a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java +++ b/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java @@ -1,11 +1,13 @@ -package com.baeldung.linkedlist; +package algorithms; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; +import com.baeldung.algorithms.middleelementlookup.Node; +import org.junit.Test; import java.util.LinkedList; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; public class MiddleElementLookupUnitTest { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java new file mode 100644 index 0000000000..1e9188f726 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.algorithms.analysis; + +import org.junit.Test; + +public class AnalysisRunnerLiveTest { + + int n = 10; + int total = 0; + + @Test + public void whenConstantComplexity_thenConstantRuntime() { + + System.out.println("**** n = " + n + " ****"); + System.out.println(); + + // Constant Time + System.out.println("**** Constant time ****"); + + System.out.println("Hey - your input is: " + n); + System.out.println("Running time not dependent on input size!"); + System.out.println(); + } + + @Test + public void whenLogarithmicComplexity_thenLogarithmicRuntime() { + // Logarithmic Time + System.out.println("**** Logarithmic Time ****"); + for (int i = 1; i < n; i = i * 2) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenLinearComplexity_thenLinearRuntime() { + // Linear Time + System.out.println("**** Linear Time ****"); + for (int i = 0; i < n; i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + + } + + @Test + public void whenNLogNComplexity_thenNLogNRuntime() { + // N Log N Time + System.out.println("**** nlogn Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j < n; j = j * 2) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenQuadraticComplexity_thenQuadraticRuntime() { + // Quadratic Time + System.out.println("**** Quadratic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenCubicComplexity_thenCubicRuntime() { + // Cubic Time + System.out.println("**** Cubic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + for (int k = 1; k <= n; k++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k); + total++; + } + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenExponentialComplexity_thenExponentialRuntime() { + // Exponential Time + System.out.println("**** Exponential Time ****"); + total = 0; + for ( + + int i = 1; i <= Math.pow(2, n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenFactorialComplexity_thenFactorialRuntime() { + // Factorial Time + System.out.println("**** Factorial Time ****"); + total = 0; + for ( + + int i = 1; i <= + + factorial(n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + } + + static int factorial(int n) { + if (n == 0 || n == 1) + return 1; + else + return n * factorial(n - 1); + } +} diff --git a/core-java-8/README.md b/core-java-8/README.md index df6d50ad30..2eb8d49983 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -52,4 +52,4 @@ - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) - +- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java index e79c90b684..4f1e54ec2c 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java @@ -38,7 +38,7 @@ public class UnsignedArithmeticUnitTest { assertEquals(1, Integer.divideUnsigned(negative, positive)); assertEquals(-1, negative % positive); - assertEquals(1, Integer.divideUnsigned(negative, positive)); + assertEquals(1, Integer.remainderUnsigned(negative, positive)); } @Test diff --git a/core-java-9/README.md b/core-java-9/README.md index 4223e57d4b..a76dcefc69 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -25,3 +25,4 @@ - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) +- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) diff --git a/core-java/README.md b/core-java/README.md index 79f7b4169e..fa2d7e4cf0 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -156,3 +156,7 @@ - [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) - [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) - [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) +- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) +- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java new file mode 100644 index 0000000000..9a64c1d4c4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class Public { + public Public() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java new file mode 100644 index 0000000000..545f48c9ca --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class SubClass extends SuperPublic { + public SubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java new file mode 100644 index 0000000000..7c9554f2c7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java @@ -0,0 +1,39 @@ +package com.baeldung.accessmodifiers; + +//Only public or default access modifiers are permitted +public class SuperPublic { + // Always available from anywhere + static public void publicMethod() { + System.out.println(SuperPublic.class.getName() + " publicMethod()"); + } + + // Available within the same package + static void defaultMethod() { + System.out.println(SuperPublic.class.getName() + " defaultMethod()"); + } + + // Available within the same package and subclasses + static protected void protectedMethod() { + System.out.println(SuperPublic.class.getName() + " protectedMethod()"); + } + + // Available within the same class only + static private void privateMethod() { + System.out.println(SuperPublic.class.getName() + " privateMethod()"); + } + + // Method in the same class = has access to all members within the same class + private void anotherPrivateMethod() { + privateMethod(); + defaultMethod(); + protectedMethod(); + publicMethod(); // Available in the same class only. + } +} + +// Only public or default access modifiers are permitted +class SuperDefault { + public void publicMethod() { + System.out.println(this.getClass().getName() + " publicMethod()"); + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java new file mode 100644 index 0000000000..32eea36854 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherPublic { + public AnotherPublic() { + SuperPublic.publicMethod(); // Available everywhere. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java new file mode 100644 index 0000000000..3d9dc3f119 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java @@ -0,0 +1,10 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSubClass extends SuperPublic { + public AnotherSubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in subclass. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java new file mode 100644 index 0000000000..3932e6f990 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSuperPublic { + public AnotherSuperPublic() { + SuperPublic.publicMethod(); // Available everywhere. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/extension/Extension.java b/core-java/src/main/java/com/baeldung/extension/Extension.java index 4045af8b30..e30084f1cb 100644 --- a/core-java/src/main/java/com/baeldung/extension/Extension.java +++ b/core-java/src/main/java/com/baeldung/extension/Extension.java @@ -3,18 +3,18 @@ package com.baeldung.extension; import com.google.common.io.Files; import org.apache.commons.io.FilenameUtils; +import java.util.Optional; + public class Extension { //Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java public String getExtensionByApacheCommonLib(String filename) { return FilenameUtils.getExtension(filename); } - public String getExtensionByStringHandling(String filename) { - String fileExtension = ""; - if (filename.contains(".") && filename.lastIndexOf(".") != 0) { - fileExtension = filename.substring(filename.lastIndexOf(".") + 1); - } - return fileExtension; + public Optional getExtensionByStringHandling(String filename) { + return Optional.ofNullable(filename) + .filter(f -> f.contains(".")) + .map(f -> f.substring(filename.lastIndexOf(".") + 1)); } public String getExtensionByGuava(String filename) { diff --git a/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java index 8c6e261c91..14e05d6b95 100644 --- a/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java +++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.extension; import org.junit.Assert; import org.junit.Test; +import java.util.Optional; + public class ExtensionUnitTest { private Extension extension = new Extension(); @@ -16,8 +18,9 @@ public class ExtensionUnitTest { @Test public void getExtension_whenStringHandle_thenExtensionIsTrue() { String expectedExtension = "java"; - String actualExtension = extension.getExtensionByStringHandling("Demo.java"); - Assert.assertEquals(expectedExtension, actualExtension); + Optional actualExtension = extension.getExtensionByStringHandling("Demo.java"); + Assert.assertTrue(actualExtension.isPresent()); + actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext)); } @Test diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index 87f532c3f3..7f4491117b 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -9,6 +9,13 @@ deltaspike A starter Java EE 7 webapp which uses DeltaSpike http://wildfly.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + Apache License, Version 2.0 @@ -16,12 +23,12 @@ http://www.apache.org/licenses/LICENSE-2.0.html - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + + redhat-repository-techpreview + https://maven.repository.redhat.com/techpreview/all/ + + @@ -47,6 +54,13 @@ pom import + + org.apache.deltaspike.distribution + distributions-bom + ${deltaspike.version} + pom + import + @@ -160,14 +174,12 @@ org.apache.deltaspike.modules deltaspike-data-module-api - ${deltaspike.version} compile org.apache.deltaspike.modules deltaspike-data-module-impl - ${deltaspike.version} runtime @@ -184,6 +196,71 @@ querydsl-jpa ${querydsl.version} + + + org.apache.deltaspike.modules + deltaspike-test-control-module-api + test + + + + org.apache.deltaspike.modules + deltaspike-test-control-module-impl + test + + + + org.apache.deltaspike.cdictrl + deltaspike-cdictrl-weld + test + + + + org.jboss.weld.se + weld-se-core + ${weld.version} + test + + + + org.hibernate + hibernate-core + provided + + + + org.jboss + jandex + 1.2.5.Final-redhat-1 + + + + com.h2database + h2 + 1.4.197 + test + + + + org.hibernate + hibernate-entitymanager + provided + + + + + junit + junit + test + + + + + org.apache.commons + commons-lang3 + 3.5 + + @@ -226,28 +303,6 @@ - - - - default - - true - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - true - - - - - - UTF-8 3.7.4 - 1.7.2 + 1.8.2 1.0.2.Final - 8.2.2.Final + 8.2.1.Final + 2.1.2.Final 2.6 1.1.3 + 1.8 + 1.8 diff --git a/deltaspike/src/main/java/baeldung/controller/MemberController.java b/deltaspike/src/main/java/baeldung/controller/MemberController.java index 7a9e9800f4..eba36355b7 100644 --- a/deltaspike/src/main/java/baeldung/controller/MemberController.java +++ b/deltaspike/src/main/java/baeldung/controller/MemberController.java @@ -16,6 +16,9 @@ */ package baeldung.controller; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; + import javax.annotation.PostConstruct; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; @@ -24,9 +27,6 @@ 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: @@ -34,11 +34,9 @@ import baeldung.service.MemberRegistration; @Model public class MemberController { - @Inject - private FacesContext facesContext; + @Inject private FacesContext facesContext; - @Inject - private MemberRegistration memberRegistration; + @Inject private MemberRegistration memberRegistration; @Produces @Named diff --git a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java index 9189dbba74..6c2387012d 100644 --- a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java @@ -1,29 +1,18 @@ 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; +import javax.persistence.PersistenceContext; -@ApplicationScoped public class EntityManagerProducer { - @PersistenceUnit(unitName = "primary") - private EntityManagerFactory entityManagerFactory; - @Produces - @Default + @PersistenceContext(unitName = "primary") private EntityManager entityManager; + @RequestScoped + @Produces public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - 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 index c1f5fda31d..989bcea917 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java +++ b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java @@ -16,6 +16,8 @@ */ package baeldung.data; +import baeldung.model.Member; + import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; @@ -25,13 +27,10 @@ import javax.inject.Inject; import javax.inject.Named; import java.util.List; -import baeldung.model.Member; - @RequestScoped public class MemberListProducer { - @Inject - private MemberRepository memberRepository; + @Inject private MemberRepository memberRepository; private List members; diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java index 220388bcf0..e9c7e52f9c 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -18,7 +18,10 @@ package baeldung.data; import baeldung.model.Member; import baeldung.model.QMember; -import org.apache.deltaspike.data.api.*; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.EntityManagerConfig; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; import java.util.List; @@ -35,6 +38,9 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() { final QMember member = QMember.member; - return jpaQuery().from(member).orderBy(member.email.asc()).list(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 index 8cb00958ab..4bb8a629de 100644 --- a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java +++ b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java @@ -8,8 +8,7 @@ import javax.inject.Inject; public class QueryDslRepositoryExtension implements QueryDslSupport, DelegateQueryHandler { - @Inject - private QueryInvocationContext context; + @Inject private QueryInvocationContext context; @Override public JPAQuery jpaQuery() { diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java index 41d30d9018..606def4f30 100644 --- a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java @@ -2,29 +2,20 @@ 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; +import javax.persistence.PersistenceContext; @ApplicationScoped public class SecondaryEntityManagerProducer { - @PersistenceUnit(unitName = "secondary") - private EntityManagerFactory entityManagerFactory; + + @PersistenceContext(unitName = "secondary") private EntityManager entityManager; @Produces - @Default @RequestScoped @SecondaryPersistenceUnit public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - 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/SimpleUserRepository.java b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java new file mode 100644 index 0000000000..9ea6115f11 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java @@ -0,0 +1,45 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.FirstResult; +import org.apache.deltaspike.data.api.MaxResults; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository(forEntity = User.class) +public abstract class SimpleUserRepository { + public abstract Collection findAll(); + + public abstract Collection findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size); + + public abstract Collection findTop2OrderByFirstNameAsc(); + + public abstract Collection findFirst2OrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAscLastNameDesc(); + + public abstract User findById(Long id); + + public abstract Collection findByFirstName(String firstName); + + public abstract User findAnyByLastName(String lastName); + + public abstract Collection findAnyByFirstName(String firstName); + + public abstract Collection findByFirstNameAndLastName(String firstName, String lastName); + + public abstract Collection findByFirstNameOrLastName(String firstName, String lastName); + + public abstract Collection findByAddress_city(String city); + + public abstract int count(); + + public abstract void remove(User user); +} diff --git a/deltaspike/src/main/java/baeldung/data/UserRepository.java b/deltaspike/src/main/java/baeldung/data/UserRepository.java new file mode 100644 index 0000000000..688e46f5fc --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/UserRepository.java @@ -0,0 +1,31 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository +public abstract class UserRepository extends AbstractEntityRepository { + + public List findByFirstName(String firstName) { + return typedQuery("select u from User u where u.firstName = ?1") + .setParameter(1, firstName) + .getResultList(); + } + + public abstract List findByLastName(String lastName); + + @Query("select u from User u where u.firstName = ?1") + public abstract Collection findUsersWithFirstName(String firstName); + + @Query(value = "select * from User where firstName = ?1", isNative = true) + public abstract Collection findUsersWithFirstNameNative(String firstName); + +} diff --git a/deltaspike/src/main/java/baeldung/model/Address.java b/deltaspike/src/main/java/baeldung/model/Address.java new file mode 100644 index 0000000000..ef0d461b9c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/Address.java @@ -0,0 +1,51 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +/** + * Created by adam. + */ +@Entity +public class Address { + + @Id + @GeneratedValue + private Long id; + private String street; + private String city; + private String postCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } +} diff --git a/deltaspike/src/main/java/baeldung/model/Member.java b/deltaspike/src/main/java/baeldung/model/Member.java index e178dcf63a..d9b9b5caf1 100644 --- a/deltaspike/src/main/java/baeldung/model/Member.java +++ b/deltaspike/src/main/java/baeldung/model/Member.java @@ -16,22 +16,16 @@ */ package baeldung.model; -import java.io.Serializable; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotEmpty; -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.persistence.*; 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; +import java.io.Serializable; @SuppressWarnings("serial") @Entity diff --git a/deltaspike/src/main/java/baeldung/model/User.java b/deltaspike/src/main/java/baeldung/model/User.java new file mode 100644 index 0000000000..5560ea0e7c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/User.java @@ -0,0 +1,52 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +/** + * Created by adam. + */ +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + private String firstName; + private String lastName; + @OneToOne private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/deltaspike/src/main/resources/META-INF/beans.xml b/deltaspike/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..f462814752 --- /dev/null +++ b/deltaspike/src/main/resources/META-INF/beans.xml @@ -0,0 +1,5 @@ + + diff --git a/deltaspike/src/test/java/baeldung/ValidatorProducer.java b/deltaspike/src/test/java/baeldung/ValidatorProducer.java new file mode 100644 index 0000000000..6b895f771e --- /dev/null +++ b/deltaspike/src/test/java/baeldung/ValidatorProducer.java @@ -0,0 +1,21 @@ +package baeldung; + +import javax.enterprise.inject.Produces; +import javax.validation.Validation; +import javax.validation.Validator; + +/** + * Created by adam. + */ +public class ValidatorProducer { + + @Produces + public Validator createValidator() { + return Validation + .byDefaultProvider() + .configure() + .buildValidatorFactory() + .getValidator(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java new file mode 100644 index 0000000000..139760d7fc --- /dev/null +++ b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java @@ -0,0 +1,23 @@ +package baeldung.data; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.Specializes; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +/** + * Created by adam. + */ +public class TestEntityManagerProducer extends EntityManagerProducer { + + @ApplicationScoped + @Produces + @Specializes + public EntityManager create() { + return Persistence + .createEntityManagerFactory("pu-test") + .createEntityManager(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java index 2b6cfe2b02..6db09abaae 100644 --- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java @@ -16,19 +16,12 @@ */ 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.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; @@ -37,24 +30,39 @@ import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.runner.RunWith; +import javax.inject.Inject; +import java.io.File; +import java.util.logging.Logger; + +import static org.junit.Assert.assertNotNull; + @RunWith(Arquillian.class) public class MemberRegistrationIntegrationTest { @Deployment public static Archive createTestArchive() { - File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); + 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); + 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/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 MemberRegistration memberRegistration; - @Inject - Logger log; + @Inject Logger log; @Test public void testRegister() throws Exception { diff --git a/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java new file mode 100644 index 0000000000..2065338c77 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java @@ -0,0 +1,133 @@ +package baeldung.test; + +import baeldung.data.SimpleUserRepository; +import baeldung.model.User; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class SimpleUserRepositoryUnitTest { + + @Inject private EntityManager entityManager; + + @Inject private SimpleUserRepository simpleUserRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(simpleUserRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindAnyByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findAnyByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenCountByFirstNameShouldReturnSizeTwo() { + assertThat(simpleUserRepository.count(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenRemoveByFirstNameShouldReturnSizeTwo() { + simpleUserRepository.remove(entityManager.merge(simpleUserRepository.findById(1L))); + assertThat(entityManager.find(User.class, 1L), nullValue()); + } + + @Test + public void givenOneUserWithSpecifiedFirstNameAndLastNameWhenFindByFirstNameAndLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByFirstNameAndLastName("Adam", "LastName1") + .size(), equalTo(1)); + assertThat(simpleUserRepository + .findByFirstNameAndLastName("David", "LastName2") + .size(), equalTo(1)); + } + + @Test + public void givenOneUserWithSpecifiedLastNameWhenFindAnyByLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository.findAnyByLastName("LastName1"), notNullValue()); + } + + @Test + public void givenOneUserWithSpecifiedAddressCityWhenFindByCityShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByAddress_city("London") + .size(), equalTo(1)); + } + + @Test + public void givenUsersWithSpecifiedFirstOrLastNameWhenFindByFirstNameOrLastNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstNameOrLastName("David", "LastName1") + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAsc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAscLastNameDesc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindTop2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findTop2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindFirst2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findFirst2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenPagesWithSizeTwoWhenFindAllOrderByFirstNameAscShouldReturnTwoPages() { + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(0, 2) + .size(), equalTo(2)); + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(2, 4) + .size(), equalTo(2)); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java new file mode 100644 index 0000000000..bd07bf2730 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java @@ -0,0 +1,55 @@ +package baeldung.test; + +import baeldung.data.UserRepository; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class UserRepositoryUnitTest { + + @Inject private UserRepository userRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(userRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameNativeShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstNameNative("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedLastNameWhenFindByLastNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByLastName("LastName3") + .size(), equalTo(2)); + } +} diff --git a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties index a861ad729a..787e58ade0 100644 --- a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties +++ b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties @@ -1 +1,3 @@ globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy +org.apache.deltaspike.ProjectStage=UnitTest +deltaspike.testcontrol.stop_container=false \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/beans.xml b/deltaspike/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000000..346b484f2f --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/beans.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/test-persistence.xml b/deltaspike/src/test/resources/META-INF/persistence.xml similarity index 53% rename from deltaspike/src/test/resources/META-INF/test-persistence.xml rename to deltaspike/src/test/resources/META-INF/persistence.xml index bc9fbcbeef..ee69855138 100644 --- a/deltaspike/src/test/resources/META-INF/test-persistence.xml +++ b/deltaspike/src/test/resources/META-INF/persistence.xml @@ -11,6 +11,7 @@ + java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS @@ -18,4 +19,23 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + + baeldung.model.User + baeldung.model.Address + + + + + + + + + + + + + diff --git a/deltaspike/src/test/resources/arquillian.xml b/deltaspike/src/test/resources/arquillian.xml index 14f9e53bbd..7f02023089 100644 --- a/deltaspike/src/test/resources/arquillian.xml +++ b/deltaspike/src/test/resources/arquillian.xml @@ -28,12 +28,4 @@ - - - - - target\wildfly-run\wildfly-10.0.0.Final - - - diff --git a/deltaspike/src/test/resources/import.sql b/deltaspike/src/test/resources/import.sql new file mode 100644 index 0000000000..f6e06ecee4 --- /dev/null +++ b/deltaspike/src/test/resources/import.sql @@ -0,0 +1,6 @@ +INSERT INTO ADDRESS(ID, STREET, CITY, POSTCODE) VALUES (1, 'Oxford', 'London', 'N121'); + +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (1, 'Adam', 'LastName1', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (2, 'David', 'LastName2', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (3, 'Adam', 'LastName3', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (4, 'Peter', 'LastName3', 1); \ No newline at end of file diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF index 254272e1c0..e3c07ab38a 100644 --- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF +++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF @@ -1,3 +1,2 @@ Manifest-Version: 1.0 Class-Path: - diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile new file mode 100644 index 0000000000..211e8927a3 --- /dev/null +++ b/guest/spring-boot-app/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml new file mode 100644 index 0000000000..7e03ddc827 --- /dev/null +++ b/guest/spring-boot-app/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/Application/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/guest/spring-boot-app/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml index ba57bbd5c5..c02eef7ef3 100644 --- a/guest/spring-boot-app/pom.xml +++ b/guest/spring-boot-app/pom.xml @@ -51,6 +51,22 @@ WebContent + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.stackify.Application + ${project.basedir}/docker + + + + + @@ -58,4 +74,4 @@ 8.0.43 - \ No newline at end of file + diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index cf944804db..0000000000 --- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index 94bd63e068..0000000000 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md index 598f2b4913..afba239919 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -11,4 +11,5 @@ - [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) - [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index e8fdabebbc..23d7d2e201 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,5 +1,7 @@ package com.baeldung.hibernate; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; @@ -70,6 +72,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java new file mode 100644 index 0000000000..1af3e3e21b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; + +@Entity +public class OptimisticLockingCourse { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinTable(name = "optimistic_student_course") + private OptimisticLockingStudent student; + + public OptimisticLockingCourse(Long id, String name) { + this.id = id; + this.name = name; + } + + public OptimisticLockingCourse() { + } + + 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 OptimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(OptimisticLockingStudent student) { + this.student = student; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java new file mode 100644 index 0000000000..b79212ae8d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class OptimisticLockingStudent { + + @Id + private Long id; + + private String name; + + private String lastName; + @Version + private Integer version; + + @OneToMany(mappedBy = "student") + private List courses; + + public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { + this.id = id; + this.name = name; + this.lastName = lastName; + this.courses = courses; + } + + public OptimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..68b51764e4 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -0,0 +1,134 @@ +package com.baeldung.hibernate.optimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.OptimisticLockException; +import java.io.IOException; +import java.util.Arrays; + +public class OptimisticLockingIntegrationTest { + + @Before + public void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); + OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); + course.setStudent(student); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @After + public void clean() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); + OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); + entityManager.remove(course); + entityManager.remove(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } +} diff --git a/java-ee-8-security-api/README.md b/java-ee-8-security-api/README.md new file mode 100644 index 0000000000..1735419236 --- /dev/null +++ b/java-ee-8-security-api/README.md @@ -0,0 +1,3 @@ +### Relevant articles + + - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) diff --git a/javax-servlets/README.md b/javax-servlets/README.md index de8a8e4498..55ca1116aa 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -4,3 +4,4 @@ - [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session) - [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet) - [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file) +- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response) diff --git a/json-path/src/main/resources/online_store.json b/json-path/src/main/resources/online_store.json new file mode 100644 index 0000000000..c0ddf274d8 --- /dev/null +++ b/json-path/src/main/resources/online_store.json @@ -0,0 +1,23 @@ +{ + "items":{ + "book":[ + { + "author":"Arthur Conan Doyle", + "title":"Sherlock Holmes", + "price":8.99 + }, + { + "author":"J. R. R. Tolkien", + "title":"The Lord of the Rings", + "isbn":"0-395-19395-8", + "price":22.99 + } + ], + "bicycle":{ + "color":"red", + "price":19.95 + } + }, + "url":"mystore.com", + "owner":"baeldung" +} \ No newline at end of file diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java new file mode 100644 index 0000000000..3408629a6d --- /dev/null +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jsonpath.introduction; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Map; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jayway.jsonpath.JsonPath; + +import net.minidev.json.JSONArray; + +public class JsonPathUnitTest { + + private static String json; + private static File jsonFile = new File("src/main/resources/online_store.json"); + + private static String readFile(File file, Charset charset) throws IOException { + return new String(Files.readAllBytes(file.toPath()), charset); + } + + @BeforeClass + public static void init() throws IOException { + json = readFile(jsonFile, StandardCharsets.UTF_8); + } + + @Test + public void shouldMatchCountOfObjects() { + Map objectMap = JsonPath.read(json, "$"); + assertEquals(3, objectMap.keySet() + .size()); + } + + @Test + public void shouldMatchCountOfArrays() { + JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]"); + assertEquals(2, jsonArray.size()); + } + +} diff --git a/libraries/pom.xml b/libraries/pom.xml index 4f90d63d93..663b9e68bb 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -709,6 +709,20 @@ xchart ${xchart-version} + + + commons-net + commons-net + ${commons-net.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + @@ -923,6 +937,8 @@ 2.5.11 3.6.1 3.5.2 + 3.6 + 2.7.1 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java new file mode 100644 index 0000000000..209bed35f0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.apache.commons.net.PrintCommandListener; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +class FtpClient { + + private final String server; + private final int port; + private final String user; + private final String password; + private FTPClient ftp; + + FtpClient(String server, int port, String user, String password) { + this.server = server; + this.port = port; + this.user = user; + this.password = password; + } + + void open() throws IOException { + ftp = new FTPClient(); + + ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); + + ftp.connect(server, port); + int reply = ftp.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + ftp.disconnect(); + throw new IOException("Exception in connecting to FTP Server"); + } + + ftp.login(user, password); + } + + void close() throws IOException { + ftp.disconnect(); + } + + Collection listFiles(String path) throws IOException { + FTPFile[] files = ftp.listFiles(path); + + return Arrays.stream(files) + .map(FTPFile::getName) + .collect(Collectors.toList()); + } + + void putFileToPath(File file, String path) throws IOException { + ftp.storeFile(path, new FileInputStream(file)); + } + + void downloadFile(String source, String destination) throws IOException { + FileOutputStream out = new FileOutputStream(destination); + ftp.retrieveFile(source, out); + } +} diff --git a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java index fd713606cf..685890c6d7 100644 --- a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java +++ b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java @@ -14,7 +14,7 @@ public class UserController { public static Handler fetchById = ctx -> { int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id"))); UserDao dao = UserDao.instance(); - User user = dao.getUserById(id); + User user = dao.getUserById(id).get(); if (user == null) { ctx.html("Not Found"); } else { diff --git a/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java b/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java new file mode 100644 index 0000000000..e07422a9c6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; + +import org.apache.commons.lang3.time.DateUtils; +import org.joda.time.DateTime; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class StringToDateUnitTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(2018, 05, 05); + + LocalDate date = LocalDate.parse("2018-05-05"); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDateTime() { + LocalDateTime expectedLocalDateTime = LocalDateTime.of(2018, 05, 05, 11, 50, 55); + + LocalDateTime dateTime = LocalDateTime.parse("2018-05-05T11:50:55"); + + assertThat(dateTime).isEqualTo(expectedLocalDateTime); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetDateTimeParseException() { + thrown.expect(DateTimeParseException.class); + thrown.expectMessage("Text '2018-05-05' could not be parsed at index 10"); + + LocalDateTime.parse("2018-05-05"); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectZonedDateTime() { + LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30); + ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris")); + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]"); + + assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime); + } + + @Test + public void givenDateString_whenConvertedToDateUsingFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1959, 7, 9); + + String dateInString = "19590709"; + LocalDate date = LocalDate.parse(dateInString, DateTimeFormatter.BASIC_ISO_DATE); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDateUsingCustomFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1980, 05, 05); + + String dateInString = "Mon, 05 May 1980"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH); + LocalDate dateTime = LocalDate.parse(dateInString, formatter); + + assertThat(dateTime).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDate() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + String dateInString = "7-Jun-2013"; + Date date = formatter.parse(dateInString); + + assertDateIsCorrect(date); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetParseException() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + thrown.expect(ParseException.class); + thrown.expectMessage("Unparseable date: \"07/06/2013\""); + + String dateInString = "07/06/2013"; + formatter.parse(dateInString); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectJodaDateTime() { + org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"); + + String dateInString = "07/06/2013 10:11:59"; + DateTime dateTime = DateTime.parse(dateInString, formatter); + + assertEquals("Day of Month should be 7: ", 7, dateTime.getDayOfMonth()); + assertEquals("Month should be: ", 6, dateTime.getMonthOfYear()); + assertEquals("Year should be: ", 2013, dateTime.getYear()); + + assertEquals("Hour of day should be: ", 10, dateTime.getHourOfDay()); + assertEquals("Minutes of hour should be: ", 11, dateTime.getMinuteOfHour()); + assertEquals("Seconds of minute should be: ", 59, dateTime.getSecondOfMinute()); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDateTime() throws ParseException { + String dateInString = "07/06-2013"; + Date date = DateUtils.parseDate(dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" }); + + assertDateIsCorrect(date); + } + + private void assertDateIsCorrect(Date date) { + Calendar calendar = new GregorianCalendar(Locale.ENGLISH); + calendar.setTime(date); + + assertEquals("Day of Month should be 7: ", 7, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals("Month should be: ", 5, calendar.get(Calendar.MONTH)); + assertEquals("Year should be: ", 2013, calendar.get(Calendar.YEAR)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java new file mode 100644 index 0000000000..43da69f96d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + private FtpClient ftpClient; + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + + ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); + ftpClient.open(); + } + + @After + public void teardown() throws IOException { + ftpClient.close(); + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException { + Collection files = ftpClient.listFiles(""); + + assertThat(files).contains("foobar.txt"); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt"); + + assertThat(new File("downloaded_buz.txt")).exists(); + new File("downloaded_buz.txt").delete(); // cleanup + } + + @Test + public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException { + File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI()); + + ftpClient.putFileToPath(file, "/buz.txt"); + + assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java new file mode 100644 index 0000000000..ef6809b02d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JdkFtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + } + + @After + public void teardown() throws IOException { + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort()); + + URLConnection urlConnection = new URL(ftpUrl).openConnection(); + InputStream inputStream = urlConnection.getInputStream(); + Files.copy(inputStream, new File("downloaded_buz.txt").toPath()); + inputStream.close(); + + assertThat(new File("downloaded_buz.txt")).exists(); + + new File("downloaded_buz.txt").delete(); // cleanup + } + +} diff --git a/spring-boot-ctx-fluent/src/main/resources/application.properties b/libraries/src/test/resources/ftp/baz.txt similarity index 100% rename from spring-boot-ctx-fluent/src/main/resources/application.properties rename to libraries/src/test/resources/ftp/baz.txt diff --git a/msf4j/README.md b/msf4j/README.md index 19e611832c..7c66b8dc5f 100644 --- a/msf4j/README.md +++ b/msf4j/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/spring-boot-war-tomcat-deploy) +- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/msf4j) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index fb80f4bd6a..77ead0b317 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -8,4 +8,4 @@ - [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) - +- [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) diff --git a/performance-tests/README.md b/performance-tests/README.md new file mode 100644 index 0000000000..5af735b708 --- /dev/null +++ b/performance-tests/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks) diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java index fe770aef24..e781f1fca1 100644 --- a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java +++ b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java @@ -151,8 +151,8 @@ public class MappingFrameworksPerformance { @Benchmark @Group("simpleTest") - public Order dozerMapperSimpleBenchmark() { - return DOZER_CONVERTER.convert(sourceOrder); + public DestinationCode dozerMapperSimpleBenchmark() { + return DOZER_CONVERTER.convert(sourceCode); } @Benchmark diff --git a/pom.xml b/pom.xml index d42c3ac617..8c87983870 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ guava-modules/guava-21 guice disruptor - handling-spring-static-resources + spring-static-resources hazelcast hbase @@ -183,7 +183,6 @@ spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java - spring-mvc-tiles spring-mvc-velocity spring-mvc-webflow spring-mvc-xml @@ -262,7 +261,9 @@ java-spi performance-tests twilio - java-ee-8-security-api + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index 400e343263..f94bd0b0c1 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,12 +4,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) -- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 9998dbf751..df96d933ba 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -17,3 +17,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index c509622fca..808d9ef585 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -39,7 +39,6 @@ org.springframework.retry spring-retry - ${springretry.version} org.springframework.shell @@ -55,11 +54,11 @@ org.hibernate hibernate-core - ${hibernate.version} org.javassist javassist + ${javassist.version} mysql @@ -74,6 +73,7 @@ org.hibernate hibernate-validator + ${hibernate.version} @@ -112,7 +112,6 @@ org.assertj assertj-core - ${assertj.version} test @@ -139,17 +138,14 @@ org.ehcache ehcache - ${ehcache.version} org.apache.logging.log4j log4j-api - ${log4j.version} org.apache.logging.log4j log4j-core - ${log4j.version} @@ -187,6 +183,7 @@ org.apache.maven.plugins maven-war-plugin + 3.2.2 false @@ -197,22 +194,23 @@ org.baeldung.sample.App - 4.3.4.RELEASE - 4.2.0.RELEASE - 1.1.5.RELEASE + 5.0.6.RELEASE + 5.0.6.RELEASE + 1.2.2.RELEASE 1.2.0.RELEASE 5.2.5.Final - 19.0 - 3.1.3 - 3.4 + 25.1-jre + 3.5.2 + 3.6 3.6.1 - 6.4.0 + 6.6.0 2.8.2 + 3.22.0-GA diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java index 4df1e2e73b..318dc5ea65 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java @@ -4,9 +4,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { +public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer +{ - @Override + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { //If this is not the only class declaring a root context, we return null because it would clash //with other classes, as there can only be a single root context. @@ -17,19 +19,19 @@ public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDi return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); normalWebAppContext.register(NormalWebAppConfig.class); return normalWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/api/*" }; } - @Override + //@Override protected String getServletName() { return "normal-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java index 0d2674d4f3..b685d2fa83 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java @@ -4,9 +4,10 @@ import org.springframework.web.context.AbstractContextLoaderInitializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -public class AnnotationsBasedApplicationInitializer extends AbstractContextLoaderInitializer { - - @Override +public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer +{ + //uncomment to run the multiple contexts example + // @Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootApplicationConfig.class); diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java index 09e0742394..15a2631cbb 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java @@ -12,9 +12,10 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class ApplicationInitializer implements WebApplicationInitializer { - - @Override +public class ApplicationInitializer //implements WebApplicationInitializer +{ + //uncomment to run the multiple contexts example + //@Override public void onStartup(ServletContext servletContext) throws ServletException { //Here, we can define a root context and register servlets, among other things. //However, since we've later defined other classes to do the same and they would clash, diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java index c250cedc49..3da3d3beb1 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java @@ -5,14 +5,14 @@ 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.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) -public class NormalWebAppConfig extends WebMvcConfigurerAdapter { +public class NormalWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java index 89ce0153f5..d74d4a6c63 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java @@ -4,27 +4,29 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class SecureAnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { - - @Override +public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer +{ + + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); secureWebAppContext.register(SecureWebAppConfig.class); return secureWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/s/api/*" }; } - @Override + //@Override protected String getServletName() { return "secure-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java index f499a4ceba..acc1e3092b 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java @@ -5,14 +5,14 @@ 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.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) -public class SecureWebAppConfig extends WebMvcConfigurerAdapter { +public class SecureWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index fbe3dfb398..8b58c51eb3 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -3,14 +3,12 @@ package com.baeldung.contexts.normal; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.contexts.services.ApplicationContextUtilService; import com.baeldung.contexts.services.GreeterService; @Controller diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index 3dc4db53c0..85305e057f 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -4,29 +4,27 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class StudentControllerConfig implements WebApplicationInitializer { +public class StudentControllerConfig //implements WebApplicationInitializer +{ - @Override + //uncomment to run the student controller example + //@Override public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); root.register(WebConfig.class); - root.setServletContext(sc); + sc.addListener(new ContextLoaderListener(root)); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); - - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - DispatcherServlet dv = new DispatcherServlet(webApplicationContext); - + DispatcherServlet dv = new DispatcherServlet(root); + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); appServlet.setLoadOnStartup(1); appServlet.addMapping("/test/*"); diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java index 251a1affa1..a17210f3b8 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -6,13 +6,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" }) -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java index 21b67933ef..0d753dc447 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java @@ -8,11 +8,11 @@ import java.util.concurrent.TimeUnit; 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.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @ComponentScan("org.baeldung.core") -public class CoreConfig extends WebMvcConfigurerAdapter { +public class CoreConfig implements WebMvcConfigurer { public CoreConfig() { super(); diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java index a857783c60..9f4b73f609 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java @@ -6,13 +6,16 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class MainWebAppInitializer implements WebApplicationInitializer { +public class MainWebAppInitializer implements WebApplicationInitializer +{ /** * Register and configure all Servlet container components necessary to power the web application. @@ -26,14 +29,11 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("org.baeldung.spring.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); + sc.addListener(new ContextLoaderListener(root)); - // Handles requests into the application - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(webApplicationContext)); + DispatcherServlet dv = new DispatcherServlet(root); + + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv); appServlet.setLoadOnStartup(1); final Set mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java index f87e400fce..e550733c47 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java @@ -5,13 +5,13 @@ 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.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,8 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java index d57151e259..ffe88596fa 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java @@ -11,8 +11,8 @@ 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.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index a9bc298db3..fb34725508 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -38,7 +38,7 @@ public class ScopesConfig { } @Bean - @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS) public HelloMessageGenerator globalSessionMessage() { return new HelloMessageGenerator(); } diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web-old.xml similarity index 100% rename from spring-all/src/main/webapp/WEB-INF/web.xml rename to spring-all/src/main/webapp/WEB-INF/web-old.xml diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java index 97ae651473..347dd399e2 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java @@ -6,13 +6,13 @@ 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.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan @EnableWebMvc -public class AttributeAnnotationConfiguration extends WebMvcConfigurerAdapter { +public class AttributeAnnotationConfiguration implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml index 5e308a0134..6d767f9ef7 100644 --- a/spring-boot-ctx-fluent/pom.xml +++ b/spring-boot-ctx-fluent/pom.xml @@ -3,25 +3,26 @@ 4.0.0 com.baeldung - ctxexample + spring-boot-ctx-fluent 0.0.1-SNAPSHOT jar - ctxexample - http://maven.apache.org + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - UTF-8 - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - org.springframework.boot spring-boot-starter-web + + + UTF-8 + + diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/App.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/App.java deleted file mode 100644 index da552a264b..0000000000 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/App.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; - -import com.baeldung.rest.RestConfig; -import com.baeldung.services.ServiceConfig; -import com.baeldung.web.WebConfig; - -@SpringBootApplication -public class App { - public static void main(String[] args) { - new SpringApplicationBuilder().parent(ServiceConfig.class) - .web(WebApplicationType.NONE) - .child(WebConfig.class) - .web(WebApplicationType.SERVLET) - .sibling(RestConfig.class) - .web(WebApplicationType.SERVLET) - .run(args); - } -} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/WebConfig.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java similarity index 71% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/web/WebConfig.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java index 0b0a9a18f6..0bacc5e8fe 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/WebConfig.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java @@ -1,4 +1,4 @@ -package com.baeldung.web; +package com.baeldung.ctx1; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; @@ -6,16 +6,17 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import com.baeldung.services.IHomeService; +import com.baeldung.parent.IHomeService; @Configuration -@ComponentScan("com.baeldung.web") +@ComponentScan("com.baeldung.ctx1") +@PropertySource("classpath:ctx1.properties") @EnableAutoConfiguration -@PropertySource("classpath:web-app.properties") -public class WebConfig { +public class Ctx1Config { @Bean public IHomeService homeService() { return new GreetingService(); } + } diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/HomeController.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java similarity index 80% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/web/HomeController.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java index 622470107d..9c7667db35 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/HomeController.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java @@ -1,14 +1,14 @@ -package com.baeldung.web; +package com.baeldung.ctx1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.baeldung.services.IHomeService; +import com.baeldung.parent.IHomeService; @Controller -public class HomeController { +public class Ctx1Controller { @Autowired IHomeService homeService; diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/GreetingService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java similarity index 74% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/web/GreetingService.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java index 1782b35489..a0f1f16288 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/web/GreetingService.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java @@ -1,8 +1,8 @@ -package com.baeldung.web; +package com.baeldung.ctx1; import org.springframework.stereotype.Service; -import com.baeldung.services.IHomeService; +import com.baeldung.parent.IHomeService; @Service public class GreetingService implements IHomeService { diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/RestConfig.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java similarity index 68% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/RestConfig.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java index 77b78d01b6..fc08b741f3 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/RestConfig.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java @@ -1,4 +1,4 @@ -package com.baeldung.rest; +package com.baeldung.ctx2; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @@ -6,9 +6,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration -@ComponentScan("com.baeldung.rest") +@ComponentScan("com.baeldung.ctx2") @EnableAutoConfiguration -@PropertySource("classpath:rest-app.properties") -public class RestConfig { +@PropertySource("classpath:ctx2.properties") +public class Ctx2Config { } diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/GreetingController.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java similarity index 79% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/GreetingController.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java index 563a374dd1..850fd8021c 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/rest/GreetingController.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java @@ -1,13 +1,13 @@ -package com.baeldung.rest; +package com.baeldung.ctx2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.services.IHomeService; +import com.baeldung.parent.IHomeService; @RestController -public class GreetingController { +public class Ctx2Controller { @Autowired IHomeService homeService; diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java new file mode 100644 index 0000000000..609751bc0f --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java @@ -0,0 +1,19 @@ +package com.baeldung.parent; + +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; + +import com.baeldung.ctx1.Ctx1Config; +import com.baeldung.ctx2.Ctx2Config; + +public class App { + public static void main(String[] args) { + new SpringApplicationBuilder().parent(ParentConfig.class) + .web(WebApplicationType.NONE) + .child(Ctx1Config.class) + .web(WebApplicationType.SERVLET) + .sibling(Ctx2Config.class) + .web(WebApplicationType.SERVLET) + .run(args); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/HomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java similarity index 85% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/services/HomeService.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java index c1cbe027ee..0d23e26cce 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/HomeService.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java @@ -1,4 +1,4 @@ -package com.baeldung.services; +package com.baeldung.parent; import org.springframework.stereotype.Service; diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/IHomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java similarity index 66% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/services/IHomeService.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java index 0386e13c0b..264e49861a 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/IHomeService.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java @@ -1,4 +1,4 @@ -package com.baeldung.services; +package com.baeldung.parent; public interface IHomeService { diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/ServiceConfig.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java similarity index 57% rename from spring-boot-ctx-fluent/src/main/java/com/baeldung/services/ServiceConfig.java rename to spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java index 6f98bb0457..484d020cc0 100644 --- a/spring-boot-ctx-fluent/src/main/java/com/baeldung/services/ServiceConfig.java +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java @@ -1,8 +1,8 @@ -package com.baeldung.services; +package com.baeldung.parent; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan("com.baeldung.services") -public class ServiceConfig {} +@ComponentScan("com.baeldung.parent") +public class ParentConfig {} diff --git a/spring-boot-ctx-fluent/src/main/resources/rest-app.properties b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties similarity index 83% rename from spring-boot-ctx-fluent/src/main/resources/rest-app.properties rename to spring-boot-ctx-fluent/src/main/resources/ctx1.properties index dc5a463238..2b618d4177 100644 --- a/spring-boot-ctx-fluent/src/main/resources/rest-app.properties +++ b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties @@ -1,5 +1,5 @@ server.port=8081 -server.servlet.context-path=/rest +server.servlet.context-path=/ctx1 #logging.level=debug spring.application.admin.enabled=false spring.application.admin.jmx-name=org.springframework.boot:type=AdminRest,name=SpringRestApplication \ No newline at end of file diff --git a/spring-boot-ctx-fluent/src/main/resources/web-app.properties b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties similarity index 72% rename from spring-boot-ctx-fluent/src/main/resources/web-app.properties rename to spring-boot-ctx-fluent/src/main/resources/ctx2.properties index 2b81875901..f3599e17e0 100644 --- a/spring-boot-ctx-fluent/src/main/resources/web-app.properties +++ b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties @@ -1,3 +1,5 @@ -server.port=8080 +server.port=8082 +server.servlet.context-path=/ctx2 + spring.application.admin.enabled=false spring.application.admin.jmx-name=org.springframework.boot:type=WebAdmin,name=SpringWebApplication \ No newline at end of file diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index 02c4c100aa..7eca307924 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -1,3 +1,10 @@ -### Relevant articles +### Relevant Articles: - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index b34fef8e6f..dce826dbb5 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -138,7 +138,6 @@ com.baeldung.webjar.WebjarsdemoApplication - ${project.basedir}/docker diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java new file mode 100644 index 0000000000..aa794182de --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.bootcustomfilters; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter; + +@Configuration +public class FilterConfig { + + // uncomment this and comment the @Component in the filter class definition to register only for a url pattern + // @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + + registrationBean.setFilter(new RequestResponseLoggingFilter()); + + registrationBean.addUrlPatterns("/users/*"); + + return registrationBean; + + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java new file mode 100644 index 0000000000..7cce34a06c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class ShutdownHookApplication { + + public static void main(String args[]) { + SpringApplication.run(ShutdownHookApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java new file mode 100644 index 0000000000..e85b9395d3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import javax.annotation.PreDestroy; + +import org.springframework.stereotype.Component; + +@Component +public class Bean1 { + + @PreDestroy + public void destroy() { + System.out.println("Shutdown triggered using @PreDestroy."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java new file mode 100644 index 0000000000..e85d12e791 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.stereotype.Component; + +@Component +public class Bean2 implements DisposableBean { + + @Override + public void destroy() throws Exception { + System.out.println("Shutdown triggered using DisposableBean."); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java new file mode 100644 index 0000000000..bed1d50ee7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java @@ -0,0 +1,8 @@ +package com.baeldung.shutdownhooks.beans; + +public class Bean3 { + + public void destroy() { + System.out.println("Shutdown triggered using bean destroy method."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java new file mode 100644 index 0000000000..07d729cb83 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java @@ -0,0 +1,18 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class ExampleServletContextListener implements ServletContextListener { + + @Override + public void contextDestroyed(ServletContextEvent event) { + System.out.println("Shutdown triggered using ServletContextListener."); + } + + @Override + public void contextInitialized(ServletContextEvent event) { + // Triggers when context initializes + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java new file mode 100644 index 0000000000..2d0712e19b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextListener; + +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.shutdownhooks.beans.Bean3; + +@Configuration +public class ShutdownHookConfiguration { + + @Bean(destroyMethod = "destroy") + public Bean3 initializeBean3() { + return new Bean3(); + } + + @Bean + ServletListenerRegistrationBean servletListener() { + ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean<>(); + srb.setListener(new ExampleServletContextListener()); + return srb; + } +} diff --git a/spring-core/README.md b/spring-core/README.md index cec85534f5..3684c7f6e9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -15,3 +15,4 @@ - [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) - [@Lookup Annotation in Spring](http://www.baeldung.com/spring-lookup) - [BeanNameAware and BeanFactoryAware Interfaces in Spring](http://www.baeldung.com/spring-bean-name-factory-aware) +- [Spring – Injecting Collections](http://www.baeldung.com/spring-injecting-collections) diff --git a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java similarity index 96% rename from spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java rename to spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java index b54ac16125..11d9daf3bf 100644 --- a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java +++ b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.dependson.shared.File; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfig.class) -public class FileProcessorTest { +public class FileProcessorIntegrationTest { @Autowired ApplicationContext context; diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java new file mode 100644 index 0000000000..38e8304f0f --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.resource; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.ResourceUtils; + +/** + * Test class illustrating various methods of accessing a file from the classpath using Resource. + * @author tritty + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +public class SpringResourceIntegrationTest { + /** + * Resource loader instance for lazily loading resources. + */ + @Autowired + private ResourceLoader resourceLoader; + + @Autowired + private ApplicationContext appContext; + + /** + * Injecting resource + */ + @Value("classpath:data/employees.dat") + private Resource resourceFile; + + /** + * Data in data/employee.dat + */ + private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee"; + + @Test + public void whenResourceLoader_thenReadSuccessful() throws IOException { + final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenApplicationContext_thenReadSuccessful() throws IOException { + final Resource resource = appContext.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenAutowired_thenReadSuccessful() throws IOException { + final String employees = new String(Files.readAllBytes(resourceFile.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceUtils_thenReadSuccessful() throws IOException { + final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(employeeFile.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceAsStream_thenReadSuccessful() throws IOException { + final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { + final String employees = reader.lines() + .collect(Collectors.joining("\n")); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + } + + @Test + public void whenResourceAsFile_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("data/employees.dat").getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } +} diff --git a/spring-core/src/test/resources/data/employees.dat b/spring-core/src/test/resources/data/employees.dat new file mode 100644 index 0000000000..9c28fdf82f --- /dev/null +++ b/spring-core/src/test/resources/data/employees.dat @@ -0,0 +1 @@ +Joe Employee,Jan Employee,James T. Employee \ No newline at end of file diff --git a/spring-data-rest-querydsl/README.md b/spring-data-rest-querydsl/README.md new file mode 100644 index 0000000000..03b5fee06a --- /dev/null +++ b/spring-data-rest-querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [REST Query Language Over Multiple Tables with Querydsl Web Support](http://www.baeldung.com/rest-querydsl-multiple-tables) diff --git a/spring-mockito/README.md b/spring-mockito/README.md index 3ced7161fa..969954c15e 100644 --- a/spring-mockito/README.md +++ b/spring-mockito/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring) +- [Mockito ArgumentMatchers](http://www.baeldung.com/mockito-argument-matchers) diff --git a/spring-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index 450b10433c..f0f7e35a98 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) +- [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java index 770e86ad68..c72d8fe70d 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java @@ -4,7 +4,7 @@ import java.util.List; public interface BookService { - List findAll(); + List findAll(); - void saveAll(List books); + void saveAll(List books); } diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java index 8e5654143a..a25418815b 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java @@ -5,25 +5,25 @@ import java.util.List; public class BooksCreationDto { - private List books; + private List books; - public BooksCreationDto() { - this.books = new ArrayList<>(); - } + public BooksCreationDto() { + this.books = new ArrayList<>(); + } - public BooksCreationDto(List books) { - this.books = books; - } + public BooksCreationDto(List books) { + this.books = books; + } - public List getBooks() { - return books; - } + public List getBooks() { + return books; + } - public void setBooks(List books) { - this.books = books; - } + public void setBooks(List books) { + this.books = books; + } - public void addBook(Book book) { - this.books.add(book); - } + public void addBook(Book book) { + this.books.add(book); + } } diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java index ffba2cea2c..00e1a0393e 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java @@ -16,14 +16,14 @@ public class Config implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("index"); + registry.addViewController("/") + .setViewName("index"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); } @Bean public ITemplateResolver templateResolver() { - ClassLoaderTemplateResolver resolver - = new ClassLoaderTemplateResolver(); + ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("templates/books/"); resolver.setSuffix(".html"); resolver.setTemplateMode(TemplateMode.HTML); diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java index 56ca41c51f..b35522a3ee 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java @@ -12,16 +12,16 @@ import java.util.stream.Collectors; @Service public class InMemoryBookService implements BookService { - static Map booksDB = new HashMap<>(); + static Map booksDB = new HashMap<>(); - @Override - public List findAll() { - return new ArrayList(booksDB.values()); - } + @Override + public List findAll() { + return new ArrayList<>(booksDB.values()); + } - @Override - public void saveAll(List books) { - long nextId = getNextId(); + @Override + public void saveAll(List books) { + long nextId = getNextId(); for (Book book : books) { if (book.getId() == 0) { book.setId(nextId++); @@ -29,14 +29,14 @@ public class InMemoryBookService implements BookService { } Map bookMap = books.stream() - .collect(Collectors.toMap( - Book::getId, Function.identity())); + .collect(Collectors.toMap(Book::getId, Function.identity())); - booksDB.putAll(bookMap); - } + booksDB.putAll(bookMap); + } - private Long getNextId(){ - return booksDB.keySet().stream() + private Long getNextId() { + return booksDB.keySet() + .stream() .mapToLong(value -> value) .max() .orElse(0) + 1; diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java index af8608704b..261954fcff 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java @@ -5,9 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -@SpringBootApplication( - exclude = {SecurityAutoConfiguration.class, - DataSourceAutoConfiguration.class}) +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class }) public class ListBindingApplication { public static void main(String[] args) { diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java index 2e177c7bbf..1ed44778c6 100644 --- a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java @@ -15,45 +15,47 @@ import java.util.List; @RequestMapping("/books") public class MultipleBooksController { - @Autowired - private BookService bookService; + @Autowired + private BookService bookService; - @GetMapping(value = "/all") - public String showAll(Model model) { - model.addAttribute("books", bookService.findAll()); + @GetMapping(value = "/all") + public String showAll(Model model) { + model.addAttribute("books", bookService.findAll()); - return "allBooks"; - } + return "allBooks"; + } - @GetMapping(value = "/create") - public String showCreateForm(Model model) { - BooksCreationDto booksForm = new BooksCreationDto(); + @GetMapping(value = "/create") + public String showCreateForm(Model model) { + BooksCreationDto booksForm = new BooksCreationDto(); - for (int i = 1; i <= 3; i++) { - booksForm.addBook(new Book()); - } + for (int i = 1; i <= 3; i++) { + booksForm.addBook(new Book()); + } - model.addAttribute("form", booksForm); + model.addAttribute("form", booksForm); - return "createBooksForm"; - } + return "createBooksForm"; + } - @GetMapping(value = "/edit") - public String showEditForm(Model model) { - List books = new ArrayList<>(); - bookService.findAll().iterator().forEachRemaining(books::add); + @GetMapping(value = "/edit") + public String showEditForm(Model model) { + List books = new ArrayList<>(); + bookService.findAll() + .iterator() + .forEachRemaining(books::add); - model.addAttribute("form", new BooksCreationDto(books)); + model.addAttribute("form", new BooksCreationDto(books)); - return "editBooksForm"; - } + return "editBooksForm"; + } - @PostMapping(value = "/save") - public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { - bookService.saveAll(form.getBooks()); + @PostMapping(value = "/save") + public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { + bookService.saveAll(form.getBooks()); - model.addAttribute("books", bookService.findAll()); + model.addAttribute("books", bookService.findAll()); - return "redirect:/books/all"; - } + return "redirect:/books/all"; + } } diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 877439145d..b97b961e60 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,3 +29,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index bc81a89bec..f1c2b0b9f5 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -7,10 +7,10 @@ spring-mvc-java - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -49,33 +49,26 @@ com.fasterxml.jackson.core jackson-databind - ${jackson.version} javax.servlet javax.servlet-api - ${javax.servlet-api.version} - provided javax.servlet jstl - ${jstl.version} - runtime org.aspectj aspectjrt - ${aspectj.version} org.aspectj aspectjweaver - ${aspectj.version} @@ -87,7 +80,6 @@ net.sourceforge.htmlunit htmlunit - ${net.sourceforge.htmlunit} commons-logging @@ -111,7 +103,6 @@ com.jayway.jsonpath json-path - ${jsonpath.version} test @@ -128,11 +119,6 @@ - - javax.validation - validation-api - 1.1.0.Final - org.hibernate hibernate-validator @@ -170,13 +156,11 @@ maven-resources-plugin - ${maven-resources-plugin.version} org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -266,18 +250,14 @@ - - 2.1.5.RELEASE - 2.9.4 + 3.0.9.RELEASE 5.2.5.Final 5.1.40 - 5.4.1.Final - 3.1.0 - 1.2 + 6.0.10.Final 19.0 diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java new file mode 100644 index 0000000000..a29a6252f2 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java @@ -0,0 +1,62 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.time.Year; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/customResponse") +public class CustomResponseController { + + @GetMapping("/hello") + public ResponseEntity hello() { + return new ResponseEntity<>("Hello World!", HttpStatus.OK); + } + + @GetMapping("/age") + public ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) { + if (isInFuture(yearOfBirth)) { + return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); + } + + private int calculateAge(int yearOfBirth) { + return currentYear() - yearOfBirth; + } + + private boolean isInFuture(int year) { + return currentYear() < year; + } + + private int currentYear() { + return Year.now().getValue(); + } + + @GetMapping("/customHeader") + public ResponseEntity customHeader() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Custom-Header", "foo"); + + return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); + } + + @GetMapping("/manual") + public void manual(HttpServletResponse response) throws IOException { + response.setHeader("Custom-Header", "foo"); + response.setStatus(200); + response.getWriter() + .println("Hello World!"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java index 301caffca9..68d078de78 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java +++ b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java @@ -3,7 +3,7 @@ package com.baeldung.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration diff --git a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java deleted file mode 100644 index 0c6a7c3ae0..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.dialect; - -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.processor.NameProcessor; -import org.thymeleaf.dialect.AbstractDialect; -import org.thymeleaf.processor.IProcessor; - -public class CustomDialect extends AbstractDialect { - - @Override - public String getPrefix() { - return "custom"; - } - - @Override - public Set getProcessors() { - final Set processors = new HashSet(); - processors.add(new NameProcessor()); - return processors; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java deleted file mode 100644 index 9a7857198c..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.processor; - -import org.thymeleaf.Arguments; -import org.thymeleaf.dom.Element; -import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor; - -public class NameProcessor extends AbstractTextChildModifierAttrProcessor { - - public NameProcessor() { - super("name"); - } - - @Override - protected String getText(final Arguments arguements, final Element elements, final String attributeName) { - return "Hello, " + elements.getAttributeValue(attributeName) + "!"; - } - - @Override - public int getPrecedence() { - return 1000; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java index 1b30479685..de47f9f69e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java @@ -1,9 +1,7 @@ package com.baeldung.spring.web.config; -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.dialect.CustomDialect; +import javax.servlet.ServletContext; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,27 +11,28 @@ 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.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.dialect.IDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { +public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { super(); } // API + + @Autowired + private ServletContext ctx; @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/sample.html"); } @@ -59,7 +58,7 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { @Bean @Description("Thymeleaf template resolver serving HTML 5") public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); @@ -71,9 +70,6 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { public SpringTemplateEngine templateEngine() { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); return templateEngine; } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java deleted file mode 100644 index 6e9318602f..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class ControllerClassNameHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public ControllerClassNameHandlerMapping controllerClassNameHandlerMapping() { - ControllerClassNameHandlerMapping controllerClassNameHandlerMapping = new ControllerClassNameHandlerMapping(); - return controllerClassNameHandlerMapping; - } - - @Bean - public WelcomeController welcome() { - return new WelcomeController(); - } - - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java deleted file mode 100644 index b84998470d..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.handlermappings; - -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.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.config.ControllerClassNameHandlerMappingConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingIntegrationTest { - - @Autowired - private WebApplicationContext webAppContext; - private MockMvc mockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); - } - - @Test - public void whenControllerClassNameMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java index 479b02e77f..e734676b98 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java @@ -9,7 +9,6 @@ import org.junit.Test; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; -import com.gargoylesoftware.htmlunit.html.HtmlHeading1; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScrapingLiveTest { @@ -37,7 +36,7 @@ public class HtmlUnitWebScrapingLiveTest { final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0); final HtmlPage postPage = latestPostLink.click(); - final List h1 = (List) postPage.getByXPath("//h1"); + final List h1 = postPage.getByXPath("//h1"); Assert.assertTrue(h1.size() > 0); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 17a68d67a5..5b86b59095 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -1,10 +1,14 @@ package com.baeldung.htmlunit; +import javax.servlet.ServletContext; + +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.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -13,8 +17,11 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.web.controller" }) -public class TestConfig extends WebMvcConfigurerAdapter { +public class TestConfig implements WebMvcConfigurer { + @Autowired + private ServletContext ctx; + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -25,7 +32,7 @@ public class TestConfig extends WebMvcConfigurerAdapter { @Bean public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index 600a448076..3505fb8009 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -4,3 +4,4 @@ - [Template Engines for Spring](http://www.baeldung.com/spring-template-engines) - [Spring 5 and Servlet 4 – The PushBuilder](http://www.baeldung.com/spring-5-push) - [Servlet Redirect vs Forward](http://www.baeldung.com/servlet-redirect-forward) +- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 1464958865..08eab59540 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -88,6 +88,12 @@ spring-jade4j ${jade.version} + + + org.apache.tiles + tiles-jsp + ${apache-tiles.version} + @@ -181,6 +187,7 @@ 5.1.0 20180130 5.0.2.RELEASE + 3.0.8 diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index c4c6791f9a..c28ee02eef 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -14,7 +14,7 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -24,7 +24,7 @@ import java.util.List; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) -public class ApplicationConfiguration extends WebMvcConfigurerAdapter { +public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { @@ -59,7 +59,5 @@ public class ApplicationConfiguration extends WebMvcConfigurerAdapter { converters.add(new StringHttpMessageConverter()); converters.add(new RssChannelHttpMessageConverter()); converters.add(new JsonChannelHttpMessageConverter()); - - super.configureMessageConverters(converters); } } diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java similarity index 86% rename from spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java index d2e90a4f53..de2b7fe68f 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java @@ -1,47 +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/"); - } - -} +package com.baeldung.spring.configuration; + +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.WebMvcConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.spring.controller.tiles") +public class TilesApplicationConfiguration implements WebMvcConfigurer { + + /** + * 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-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index 09030a8347..74094a11c7 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -21,6 +21,8 @@ public class WebInitializer implements WebApplicationInitializer { // ctx.register(JadeTemplateConfiguration.class); // ctx.register(PushConfiguration.class); // ctx.setServletContext(container); + + //ctx.register(TilesApplicationConfiguration.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(ctx)); diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java similarity index 87% rename from spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java index 1a348d1c26..319340b886 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java @@ -1,26 +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"; - } -} +package com.baeldung.spring.controller.tiles; + +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 TilesController { + + @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/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp index 9936957c04..918c52ab45 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Apache Tiles - - -

Tiles with Spring MVC Demo

- +<%@ 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-simple/src/main/webapp/WEB-INF/views/pages/home.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp index b501d4968e..47157a5d2a 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -1,12 +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

- +<%@ 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-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp index 209b1004de..497e04901a 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -1,12 +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

- +<%@ 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-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp similarity index 96% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp index 2370ad4ab1..064f3ee78b 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -1,25 +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" /> - - - - -
- - -
- -
- -
- - +<%@ 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-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp similarity index 95% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp index 3849cc5230..0946549e06 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -1,2 +1,2 @@ - -
copyright © Baeldung
+ +
copyright © Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp index 8a878c857d..4ad29d82e0 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -1,3 +1,3 @@ -
-

Welcome to Spring MVC integration with Apache Tiles

+
+

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-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp index 2c91eace85..17502fd051 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -1,8 +1,8 @@ - + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml index 789fbd809a..648ecb44fe 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-simple/src/main/webapp/static/css/app.css similarity index 100% rename from spring-mvc-tiles/src/main/webapp/static/css/app.css rename to spring-mvc-simple/src/main/webapp/static/css/app.css diff --git a/spring-mvc-tiles/README.md b/spring-mvc-tiles/README.md deleted file mode 100644 index 58991005f5..0000000000 --- a/spring-mvc-tiles/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml deleted file mode 100644 index 007f7c0844..0000000000 --- a/spring-mvc-tiles/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - 4.0.0 - com.baeldung - spring-mvc-tiles - 0.0.1-SNAPSHOT - war - spring-mvc-tiles - Integrating Spring MVC with Apache Tiles - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.apache.tiles - tiles-jsp - ${apache-tiles.version} - - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - javax.servlet - jstl - ${jstl.version} - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - spring-mvc-tiles - false - - - - - spring-mvc-tiles - - - - 3.0.7 - 3.1.0 - 2.3.1 - 1.2 - 2.6 - - - 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 deleted file mode 100644 index 79583dbe83..0000000000 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -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-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java new file mode 100644 index 0000000000..baaa4c4d80 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java @@ -0,0 +1,16 @@ +package org.baeldung.resttemplate.lists; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Sample application used to demonstrate working with Lists and RestTemplate. + */ +@SpringBootApplication +public class EmployeeApplication +{ + public static void main(String[] args) + { + SpringApplication.run(EmployeeApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java new file mode 100644 index 0000000000..729fa3ca3e --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -0,0 +1,100 @@ +package org.baeldung.resttemplate.lists.client; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.List; + +/** + * Application that shows how to use Lists with RestTemplate. + */ +public class EmployeeClient +{ + public static void main(String[] args) + { + EmployeeClient employeeClient = new EmployeeClient(); + + System.out.println("Calling GET using ParameterizedTypeReference"); + employeeClient.getAllEmployeesUsingParameterizedTypeReference(); + + System.out.println("Calling GET using wrapper class"); + employeeClient.getAllEmployeesUsingWrapperClass(); + + System.out.println("Calling POST using normal lists"); + employeeClient.createEmployeesUsingLists(); + + System.out.println("Calling POST using wrapper class"); + employeeClient.createEmployeesUsingWrapperClass(); + } + + public EmployeeClient() + { + + } + + public List getAllEmployeesUsingParameterizedTypeReference() + { + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity> response = + restTemplate.exchange( + "http://localhost:8080/spring-rest/employees/", + HttpMethod.GET, + null, + new ParameterizedTypeReference>(){}); + + List employees = response.getBody(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public List getAllEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + EmployeeList response = + restTemplate.getForObject( + "http://localhost:8080/spring-rest/employees/v2", + EmployeeList.class); + + List employees = response.getEmployees(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public void createEmployeesUsingLists() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/", + newEmployees, + ResponseEntity.class); + } + + public void createEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/v2/", + new EmployeeList(newEmployees), + ResponseEntity.class); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java new file mode 100644 index 0000000000..f051c6a78b --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -0,0 +1,45 @@ +package org.baeldung.resttemplate.lists.controller; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.baeldung.resttemplate.lists.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/employees") +public class EmployeeResource +{ + @Autowired + private EmployeeService employeeService; + + @RequestMapping(method = RequestMethod.GET, path = "/") + public List getEmployees() + { + return employeeService.getAllEmployees(); + } + + @RequestMapping(method = RequestMethod.GET, path = "/v2") + public EmployeeList getEmployeesUsingWrapperClass() + { + List employees = employeeService.getAllEmployees(); + return new EmployeeList(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/") + public void addEmployees(@RequestBody List employees) + { + employeeService.addEmployees(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/v2") + public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper) + { + employeeService.addEmployees(employeeWrapper.getEmployees()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java new file mode 100644 index 0000000000..bd8ebbf969 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java @@ -0,0 +1,40 @@ +package org.baeldung.resttemplate.lists.dto; + +public class Employee { + + public long id; + public String title; + + public Employee() + { + + } + + public Employee(long id, String title) + { + this.id = id; + this.title = title; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() + { + return "Employee #" + id + "[" + title + "]"; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java new file mode 100644 index 0000000000..2bb86ac5b4 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -0,0 +1,29 @@ +package org.baeldung.resttemplate.lists.dto; + +import java.util.ArrayList; +import java.util.List; + +public class EmployeeList +{ + public List employees; + + public EmployeeList() + { + employees = new ArrayList<>(); + } + + public EmployeeList(List employees) + { + this.employees = employees; + } + + public void setEmployees(List employees) + { + this.employees = employees; + } + + public List getEmployees() + { + return employees; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java new file mode 100644 index 0000000000..08196dda77 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java @@ -0,0 +1,24 @@ +package org.baeldung.resttemplate.lists.service; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class EmployeeService +{ + public List getAllEmployees() + { + List employees = new ArrayList<>(); + employees.add(new Employee(1, "Manager")); + employees.add(new Employee(2, "Java Developer")); + return employees; + } + + public void addEmployees(List employees) + { + employees.forEach(e -> System.out.println("Adding new employee " + e)); + } +} diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 52ec1e4ef0..e50304aa1b 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -193,26 +193,26 @@ - 4.2.6.RELEASE + 5.0.6.RELEASE 5.2.5.Final 5.1.40 - 5.3.3.Final + 5.4.1.Final 3.1.0 1.2 19.0 3.5 - 2.9.1 + 2.9.4 4.5.2 4.4.5 - 2.9.0 + 3.0.7 2.6 diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java index 3b97afc22d..db6141d43e 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java @@ -10,14 +10,14 @@ 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.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan("org.baeldung.web.controller") -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -27,8 +27,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/anonymous.html"); registry.addViewController("/login.html"); diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..e9d5bc4f70 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -6,6 +6,8 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource({ "classpath:webSecurityConfig.xml" }) public class SecSecurityConfig { + + public SecSecurityConfig() { super(); diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java index c67a6f667e..99bf345a41 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java @@ -1,5 +1,6 @@ package org.baeldung.web.controller; +import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @@ -18,7 +19,7 @@ import org.springframework.web.bind.annotation.RequestParam; @RequestMapping(value = "/custom") public class LoginController { - @Autowired + @Resource(name="authenticationManager") private AuthenticationManager authManager; public LoginController() { diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index f2ecaba5c8..e79e14abeb 100644 --- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ @@ -24,11 +24,11 @@ - + - - + + diff --git a/handling-spring-static-resources/README.md b/spring-static-resources/README.md similarity index 100% rename from handling-spring-static-resources/README.md rename to spring-static-resources/README.md diff --git a/handling-spring-static-resources/pom.xml b/spring-static-resources/pom.xml similarity index 92% rename from handling-spring-static-resources/pom.xml rename to spring-static-resources/pom.xml index 771b37fb52..a00d03d2a1 100644 --- a/handling-spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -174,7 +174,9 @@ - maven-war-plugin + org.apache.maven.plugins + maven-war-plugin + 3.2.2 @@ -190,20 +192,20 @@ 1.8 - 4.2.6.RELEASE + 5.0.6.RELEASE 1.8.9 2.3.2-b02 - 2.8.5 + 2.9.6 - 5.3.3.Final - 4.0.6 - 2.9.6 + 6.0.10.Final + 4.1.0 + 2.10 1.2 - 3.1.0 + 4.0.1 1 diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java similarity index 97% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java index 4a198cf195..dbc548e028 100644 --- a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java @@ -15,7 +15,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.resource.GzipResourceResolver; @@ -27,7 +27,7 @@ import org.springframework.web.servlet.view.JstlView; @Configuration @ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { @Autowired Environment env; @@ -39,7 +39,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/login.html"); registry.addViewController("/home.html"); diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java diff --git a/handling-spring-static-resources/src/main/resources/application.properties b/spring-static-resources/src/main/resources/application.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/application.properties rename to spring-static-resources/src/main/resources/application.properties diff --git a/handling-spring-static-resources/src/main/resources/logback.xml b/spring-static-resources/src/main/resources/logback.xml similarity index 100% rename from handling-spring-static-resources/src/main/resources/logback.xml rename to spring-static-resources/src/main/resources/logback.xml diff --git a/handling-spring-static-resources/src/main/resources/messages_en.properties b/spring-static-resources/src/main/resources/messages_en.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_en.properties rename to spring-static-resources/src/main/resources/messages_en.properties diff --git a/handling-spring-static-resources/src/main/resources/messages_es_ES.properties b/spring-static-resources/src/main/resources/messages_es_ES.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_es_ES.properties rename to spring-static-resources/src/main/resources/messages_es_ES.properties diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..ea64ad5aea --- /dev/null +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css diff --git a/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..c046aa16a9 --- /dev/null +++ b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml b/spring-static-resources/src/main/webapp/WEB-INF/web.xml similarity index 97% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml rename to spring-static-resources/src/main/webapp/WEB-INF/web.xml index e9d784e940..4bb60e4f2c 100644 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml +++ b/spring-static-resources/src/main/webapp/WEB-INF/web.xml @@ -1,6 +1,6 @@ - diff --git a/handling-spring-static-resources/src/main/webapp/js/bootstrap.css b/spring-static-resources/src/main/webapp/js/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/bootstrap.css rename to spring-static-resources/src/main/webapp/js/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/js/foo.js b/spring-static-resources/src/main/webapp/js/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/foo.js rename to spring-static-resources/src/main/webapp/js/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js b/spring-static-resources/src/main/webapp/js/handlebars-3133af2.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js rename to spring-static-resources/src/main/webapp/js/handlebars-3133af2.js diff --git a/handling-spring-static-resources/src/main/webapp/js/helpers/utils.js b/spring-static-resources/src/main/webapp/js/helpers/utils.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/helpers/utils.js rename to spring-static-resources/src/main/webapp/js/helpers/utils.js diff --git a/handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js b/spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js rename to spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js diff --git a/handling-spring-static-resources/src/main/webapp/js/main.js b/spring-static-resources/src/main/webapp/js/main.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/main.js rename to spring-static-resources/src/main/webapp/js/main.js diff --git a/handling-spring-static-resources/src/main/webapp/js/require.gz b/spring-static-resources/src/main/webapp/js/require.gz similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.gz rename to spring-static-resources/src/main/webapp/js/require.gz diff --git a/handling-spring-static-resources/src/main/webapp/js/require.js b/spring-static-resources/src/main/webapp/js/require.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.js rename to spring-static-resources/src/main/webapp/js/require.js diff --git a/handling-spring-static-resources/src/main/webapp/js/router.js b/spring-static-resources/src/main/webapp/js/router.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/router.js rename to spring-static-resources/src/main/webapp/js/router.js diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/Hello.html b/spring-static-resources/src/main/webapp/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/other-resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/foo.js b/spring-static-resources/src/main/webapp/other-resources/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/foo.js rename to spring-static-resources/src/main/webapp/other-resources/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/resources/bootstrap.css b/spring-static-resources/src/main/webapp/resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/bootstrap.css rename to spring-static-resources/src/main/webapp/resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/resources/myCss.css b/spring-static-resources/src/main/webapp/resources/myCss.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/myCss.css rename to spring-static-resources/src/main/webapp/resources/myCss.css diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html index f3d28d7ef4..34a6dec4da 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html @@ -32,7 +32,9 @@