Merge branch 'masterEugen'
This commit is contained in:
commit
39916c3905
|
@ -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)
|
||||
|
|
|
@ -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<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.linkedlist;
|
||||
package com.baeldung.algorithms.middleelementlookup;
|
||||
|
||||
public class Node {
|
||||
private Node next;
|
|
@ -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 {
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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.
|
||||
}
|
||||
}
|
|
@ -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.
|
||||
}
|
||||
}
|
|
@ -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()");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherPublic {
|
||||
public AnotherPublic() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
}
|
||||
}
|
|
@ -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.
|
||||
}
|
||||
}
|
|
@ -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.
|
||||
}
|
||||
}
|
|
@ -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<String> getExtensionByStringHandling(String filename) {
|
||||
return Optional.ofNullable(filename)
|
||||
.filter(f -> f.contains("."))
|
||||
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
|
||||
}
|
||||
|
||||
public String getExtensionByGuava(String filename) {
|
||||
|
|
|
@ -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<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
||||
Assert.assertTrue(actualExtension.isPresent());
|
||||
actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -9,6 +9,13 @@
|
|||
<name>deltaspike</name>
|
||||
<description>A starter Java EE 7 webapp which uses DeltaSpike</description>
|
||||
<url>http://wildfly.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<licenses>
|
||||
<license>
|
||||
<name>Apache License, Version 2.0</name>
|
||||
|
@ -16,12 +23,12 @@
|
|||
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
|
||||
</license>
|
||||
</licenses>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>redhat-repository-techpreview</id>
|
||||
<url>https://maven.repository.redhat.com/techpreview/all/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
@ -47,6 +54,13 @@
|
|||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.distribution</groupId>
|
||||
<artifactId>distributions-bom</artifactId>
|
||||
<version>${deltaspike.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
|
@ -160,14 +174,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.deltaspike.modules</groupId>
|
||||
<artifactId>deltaspike-data-module-api</artifactId>
|
||||
<version>${deltaspike.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.modules</groupId>
|
||||
<artifactId>deltaspike-data-module-impl</artifactId>
|
||||
<version>${deltaspike.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
|
@ -184,6 +196,71 @@
|
|||
<artifactId>querydsl-jpa</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.modules</groupId>
|
||||
<artifactId>deltaspike-test-control-module-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.modules</groupId>
|
||||
<artifactId>deltaspike-test-control-module-impl</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.cdictrl</groupId>
|
||||
<artifactId>deltaspike-cdictrl-weld</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>${weld.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss</groupId>
|
||||
<artifactId>jandex</artifactId>
|
||||
<version>1.2.5.Final-redhat-1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Needed for running tests (you may also use TestNG) -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Others -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.5</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -226,28 +303,6 @@
|
|||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<!-- The default profile skips all tests, though you can tune it to run
|
||||
just unit tests based on a custom pattern -->
|
||||
<!-- Seperate profiles are provided for running all tests, including Arquillian
|
||||
tests that execute in the specified container -->
|
||||
<id>default</id>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
|
||||
<!-- An optional Arquillian testing profile that executes tests in your
|
||||
|
@ -273,15 +328,18 @@
|
|||
resources, i.e. build is platform dependent! -->
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<querydsl.version>3.7.4</querydsl.version>
|
||||
<deltaspike.version>1.7.2</deltaspike.version>
|
||||
<deltaspike.version>1.8.2</deltaspike.version>
|
||||
<!-- JBoss dependency versions -->
|
||||
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
|
||||
<!-- Define the version of the JBoss BOMs we want to import to specify
|
||||
tested stacks. -->
|
||||
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
|
||||
<jboss.bom.version>8.2.1.Final</jboss.bom.version>
|
||||
<weld.version>2.1.2.Final</weld.version>
|
||||
<!-- other plugin versions -->
|
||||
<war.plugin.version>2.6</war.plugin.version>
|
||||
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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<Member> members;
|
||||
|
||||
|
|
|
@ -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<Member,
|
|||
|
||||
public List<Member> 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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,8 +8,7 @@ import javax.inject.Inject;
|
|||
|
||||
public class QueryDslRepositoryExtension<E> implements QueryDslSupport, DelegateQueryHandler {
|
||||
|
||||
@Inject
|
||||
private QueryInvocationContext context;
|
||||
@Inject private QueryInvocationContext context;
|
||||
|
||||
@Override
|
||||
public JPAQuery jpaQuery() {
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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<User> findAll();
|
||||
|
||||
public abstract Collection<User> findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size);
|
||||
|
||||
public abstract Collection<User> findTop2OrderByFirstNameAsc();
|
||||
|
||||
public abstract Collection<User> findFirst2OrderByFirstNameAsc();
|
||||
|
||||
public abstract List<User> findAllOrderByFirstNameAsc();
|
||||
|
||||
public abstract List<User> findAllOrderByFirstNameAscLastNameDesc();
|
||||
|
||||
public abstract User findById(Long id);
|
||||
|
||||
public abstract Collection<User> findByFirstName(String firstName);
|
||||
|
||||
public abstract User findAnyByLastName(String lastName);
|
||||
|
||||
public abstract Collection<User> findAnyByFirstName(String firstName);
|
||||
|
||||
public abstract Collection<User> findByFirstNameAndLastName(String firstName, String lastName);
|
||||
|
||||
public abstract Collection<User> findByFirstNameOrLastName(String firstName, String lastName);
|
||||
|
||||
public abstract Collection<User> findByAddress_city(String city);
|
||||
|
||||
public abstract int count();
|
||||
|
||||
public abstract void remove(User user);
|
||||
}
|
|
@ -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<User, Long> {
|
||||
|
||||
public List<User> findByFirstName(String firstName) {
|
||||
return typedQuery("select u from User u where u.firstName = ?1")
|
||||
.setParameter(1, firstName)
|
||||
.getResultList();
|
||||
}
|
||||
|
||||
public abstract List<User> findByLastName(String lastName);
|
||||
|
||||
@Query("select u from User u where u.firstName = ?1")
|
||||
public abstract Collection<User> findUsersWithFirstName(String firstName);
|
||||
|
||||
@Query(value = "select * from User where firstName = ?1", isNative = true)
|
||||
public abstract Collection<User> findUsersWithFirstNameNative(String firstName);
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="
|
||||
http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
|
||||
</beans>
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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 {
|
||||
|
|
|
@ -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<User> users = simpleUserRepository.findAllOrderByFirstNameAsc();
|
||||
assertThat(users
|
||||
.get(0)
|
||||
.getFirstName(), equalTo("Adam"));
|
||||
assertThat(users
|
||||
.get(3)
|
||||
.getFirstName(), equalTo("Peter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() {
|
||||
List<User> 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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -0,0 +1,18 @@
|
|||
<!--<?xml version="1.0" encoding="UTF-8"?>-->
|
||||
<!--<!– JBoss, Home of Professional Open Source Copyright 2013, Red Hat, Inc. -->
|
||||
<!--and/or its affiliates, and individual contributors by the @authors tag. See -->
|
||||
<!--the copyright.txt in the distribution for a full listing of individual contributors. -->
|
||||
<!--Licensed under the Apache License, Version 2.0 (the "License"); you may not -->
|
||||
<!--use this file except in compliance with the License. You may obtain a copy -->
|
||||
<!--of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required -->
|
||||
<!--by applicable law or agreed to in writing, software distributed under the -->
|
||||
<!--License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS -->
|
||||
<!--OF ANY KIND, either express or implied. See the License for the specific -->
|
||||
<!--language governing permissions and limitations under the License. –>-->
|
||||
<!--<!– Marker file indicating CDI should be enabled –>-->
|
||||
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="
|
||||
http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
|
||||
|
||||
</beans>
|
|
@ -11,6 +11,7 @@
|
|||
<property name="hibernate.show_sql" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="secondary">
|
||||
<jta-data-source>java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS</jta-data-source>
|
||||
<properties>
|
||||
|
@ -18,4 +19,23 @@
|
|||
<property name="hibernate.show_sql" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="pu-test" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<!-- add classes -->
|
||||
<class>baeldung.model.User</class>
|
||||
<class>baeldung.model.Address</class>
|
||||
|
||||
<properties>
|
||||
<!-- Configuring JDBC properties -->
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
|
||||
<!-- Hibernate properties -->
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
|
||||
<property name="hibernate.format_sql" value="false"/>
|
||||
<property name="hibernate.show_sql" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
|
@ -28,12 +28,4 @@
|
|||
<!-- Force the use of the Servlet 3.0 protocol with all containers, as it is the most mature -->
|
||||
<defaultProtocol type="Servlet 3.0" />
|
||||
|
||||
<!-- Example configuration for a remote WildFly instance -->
|
||||
<container qualifier="jboss" default="true">
|
||||
<!-- By default, arquillian will use the JBOSS_HOME environment variable. Alternatively, the configuration below can be uncommented. -->
|
||||
<configuration>
|
||||
<property name="jbossHome">target\wildfly-run\wildfly-10.0.0.Final</property>
|
||||
</configuration>
|
||||
</container>
|
||||
|
||||
</arquillian>
|
||||
|
|
|
@ -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);
|
|
@ -1,3 +1,2 @@
|
|||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
||||
|
|
|
@ -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"]
|
|
@ -0,0 +1,15 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<include resource="org/springframework/boot/logging/logback/base.xml"/>
|
||||
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>/var/log/Application/application.log</file>
|
||||
<append>true</append>
|
||||
<encoder>
|
||||
<pattern>%-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,4 @@
|
|||
#!/bin/sh
|
||||
|
||||
java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war
|
||||
|
|
@ -51,6 +51,22 @@
|
|||
<warSourceDirectory>WebContent</warSourceDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<mainClass>com.stackify.Application</mainClass>
|
||||
<outputDirectory>${project.basedir}/docker</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -58,4 +74,4 @@
|
|||
<tomcat.version>8.0.43</tomcat.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -1,40 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"
|
||||
>
|
||||
<http use-expressions="true">
|
||||
<intercept-url pattern="/login*" access="permitAll"/>
|
||||
<intercept-url pattern="/logout*" access="permitAll"/>
|
||||
<intercept-url pattern="/home*" access="permitAll"/>
|
||||
<intercept-url pattern="/files/**" access="permitAll"/>
|
||||
<intercept-url pattern="/resources/**" access="permitAll"/>
|
||||
<intercept-url pattern="/js/**" access="permitAll"/>
|
||||
<intercept-url pattern="/other-files/**" access="permitAll"/>
|
||||
<intercept-url pattern="/invalidSession*" access="isAnonymous()"/>
|
||||
<intercept-url pattern="/**" access="isAuthenticated()"/>
|
||||
|
||||
<form-login login-page='/login.html' authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler"
|
||||
default-target-url="home.html"/>
|
||||
<session-management invalid-session-url="/invalidSession.html" session-fixation-protection="none"/>
|
||||
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" delete-cookies="JSESSIONID"/>
|
||||
|
||||
</http>
|
||||
|
||||
<!-- for XML static resource confguration- comment out for java based config -->
|
||||
<!-- -<mvc:resources mapping="/resources/**" location="/resources/" /> -->
|
||||
|
||||
<beans:bean id="myAuthenticationSuccessHandler" class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
|
||||
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
</beans:beans>
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
|
||||
|
||||
</beans>
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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<OptimisticLockingCourse> courses;
|
||||
|
||||
public OptimisticLockingStudent(Long id, String name, String lastName, List<OptimisticLockingCourse> 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<OptimisticLockingCourse> getCourses() {
|
||||
return courses;
|
||||
}
|
||||
|
||||
public void setCourses(List<OptimisticLockingCourse> courses) {
|
||||
this.courses = courses;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
|
|
@ -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)
|
||||
|
|
|
@ -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"
|
||||
}
|
|
@ -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<String, String> objectMap = JsonPath.read(json, "$");
|
||||
assertEquals(3, objectMap.keySet()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldMatchCountOfArrays() {
|
||||
JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
|
||||
assertEquals(2, jsonArray.size());
|
||||
}
|
||||
|
||||
}
|
|
@ -709,6 +709,20 @@
|
|||
<artifactId>xchart</artifactId>
|
||||
<version>${xchart-version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-net</groupId>
|
||||
<artifactId>commons-net</artifactId>
|
||||
<version>${commons-net.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockftpserver</groupId>
|
||||
<artifactId>MockFtpServer</artifactId>
|
||||
<version>${mockftpserver.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
@ -923,6 +937,8 @@
|
|||
<typesafe-akka.version>2.5.11</typesafe-akka.version>
|
||||
<common-math3-version>3.6.1</common-math3-version>
|
||||
<xchart-version>3.5.2</xchart-version>
|
||||
<commons-net.version>3.6</commons-net.version>
|
||||
<mockftpserver.version>2.7.1</mockftpserver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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<String> 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);
|
||||
}
|
||||
}
|
|
@ -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 {
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
||||
}
|
||||
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks)
|
|
@ -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
|
||||
|
|
7
pom.xml
7
pom.xml
|
@ -60,7 +60,7 @@
|
|||
<module>guava-modules/guava-21</module>
|
||||
<module>guice</module>
|
||||
<module>disruptor</module>
|
||||
<module>handling-spring-static-resources</module>
|
||||
<module>spring-static-resources</module>
|
||||
<module>hazelcast</module>
|
||||
<module>hbase</module>
|
||||
<!--<module>hibernate5</module> -->
|
||||
|
@ -183,7 +183,6 @@
|
|||
<module>spring-mvc-forms-jsp</module>
|
||||
<module>spring-mvc-forms-thymeleaf</module>
|
||||
<module>spring-mvc-java</module>
|
||||
<module>spring-mvc-tiles</module>
|
||||
<module>spring-mvc-velocity</module>
|
||||
<module>spring-mvc-webflow</module>
|
||||
<module>spring-mvc-xml</module>
|
||||
|
@ -262,7 +261,9 @@
|
|||
<module>java-spi</module>
|
||||
<module>performance-tests</module>
|
||||
<module>twilio</module>
|
||||
<module>java-ee-8-security-api</module>
|
||||
<module>spring-boot-ctx-fluent</module>
|
||||
<module>java-ee-8-security-api</module>
|
||||
<module>spring-webflux-amqp</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -8,10 +8,10 @@
|
|||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-1</relativePath>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -39,7 +39,6 @@
|
|||
<dependency>
|
||||
<groupId>org.springframework.retry</groupId>
|
||||
<artifactId>spring-retry</artifactId>
|
||||
<version>${springretry.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.shell</groupId>
|
||||
|
@ -55,11 +54,11 @@
|
|||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
<artifactId>javassist</artifactId>
|
||||
<version>${javassist.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
|
@ -74,6 +73,7 @@
|
|||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
|
@ -112,7 +112,6 @@
|
|||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -139,17 +138,14 @@
|
|||
<dependency>
|
||||
<groupId>org.ehcache</groupId>
|
||||
<artifactId>ehcache</artifactId>
|
||||
<version>${ehcache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -187,6 +183,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.2.2</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
|
@ -197,22 +194,23 @@
|
|||
<properties>
|
||||
<start-class>org.baeldung.sample.App</start-class>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
|
||||
<springretry.version>1.1.5.RELEASE</springretry.version>
|
||||
<org.springframework.version>5.0.6.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>5.0.6.RELEASE</org.springframework.security.version>
|
||||
<springretry.version>1.2.2.RELEASE</springretry.version>
|
||||
<org.springframework.shell.version>1.2.0.RELEASE</org.springframework.shell.version>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>5.2.5.Final</hibernate.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<ehcache.version>3.1.3</ehcache.version>
|
||||
<easymock.version>3.4</easymock.version>
|
||||
<guava.version>25.1-jre</guava.version>
|
||||
<ehcache.version>3.5.2</ehcache.version>
|
||||
<easymock.version>3.6</easymock.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<jasperreports.version>6.4.0</jasperreports.version>
|
||||
<jasperreports.version>6.6.0</jasperreports.version>
|
||||
|
||||
<log4j.version>2.8.2</log4j.version>
|
||||
<javassist.version>3.22.0-GA</javassist.version>
|
||||
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -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";
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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";
|
||||
}
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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/*");
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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<String> mappingConflicts = appServlet.addMapping("/");
|
||||
if (!mappingConflicts.isEmpty()) {
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -3,25 +3,26 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>ctxexample</artifactId>
|
||||
<artifactId>spring-boot-ctx-fluent</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>ctxexample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.RELEASE</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
|
@ -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 {
|
|
@ -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 {
|
||||
|
||||
}
|
|
@ -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;
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.services;
|
||||
package com.baeldung.parent;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.services;
|
||||
package com.baeldung.parent;
|
||||
|
||||
public interface IHomeService {
|
||||
|
|
@ -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 {}
|
|
@ -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
|
|
@ -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
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue