Merge remote-tracking branch 'origin/master'

This commit is contained in:
Slavisa Baeldung 2016-09-30 14:43:29 +02:00
commit c250fa59f1
59 changed files with 2173 additions and 27 deletions

View File

@ -0,0 +1 @@
Hello World from fileTest.txt!!!

View File

@ -0,0 +1,78 @@
package com.baeldung.file;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import static org.hamcrest.CoreMatchers.containsString;
public class FileOperationsTest {
@Test
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
@Test
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
Class clazz = FileOperationsTest.class;
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
@Test
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
String expectedData = "Baeldung";
URL urlObject = new URL("http://www.baeldung.com/");
URLConnection urlConnection = urlObject.openConnection();
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
@Test
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
String expectedData = "BSD License";
Class clazz = Matchers.class;
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
private String readFromInputStream(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder resultStringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line);
resultStringBuilder.append("\n");
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return resultStringBuilder.toString();
}
}

View File

@ -21,7 +21,7 @@ public class JavaFolderSizeTest {
@Before
public void init() {
final String separator = File.separator;
path = "src" + separator + "test" + separator + "resources";
path = String.format("src%stest%sresources", separator, separator);
}
@Test
@ -79,7 +79,9 @@ public class JavaFolderSizeTest {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum();
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length).sum();
assertEquals(expectedSize, size);
}
@ -101,13 +103,11 @@ public class JavaFolderSizeTest {
long length = 0;
final File[] files = folder.listFiles();
final int count = files.length;
for (int i = 0; i < count; i++) {
if (files[i].isFile()) {
length += files[i].length();
for (File file : files) {
if (file.isFile()) {
length += file.length();
} else {
length += getFolderSize(files[i]);
length += getFolderSize(file);
}
}
return length;

View File

@ -123,6 +123,12 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,27 @@
package com.baeldung.java.regex;
public class Result {
private boolean found = false;
private int count = 0;
public Result() {
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,503 @@
package com.baeldung.java.regex;
import static org.junit.Assert.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class RegexTest {
private static Pattern pattern;
private static Matcher matcher;
@Test
public void givenText_whenSimpleRegexMatches_thenCorrect() {
Result result = runTest("foo", "foo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
Result result = runTest("foo", "foofoo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
Result result = runTest(".", "foo");
assertTrue(result.isFound());
}
@Test
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
Result result = runTest("foo.", "foofoo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenORSet_whenMatchesAny_thenCorrect() {
Result result = runTest("[abc]", "b");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
Result result = runTest("[abc]", "cab");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
Result result = runTest("[bcr]at", "bat cat rat");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenNORSet_whenMatchesNon_thenCorrect() {
Result result = runTest("[^abc]", "g");
assertTrue(result.isFound());
}
@Test
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
Result result = runTest("[^bcr]at", "sat mat eat");
assertTrue(result.isFound());
}
@Test
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 26);
}
@Test
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 28);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
Result result = runTest("[1-3[7-9]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 6);
}
@Test
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
Result result = runTest("[1-6&&[3-9]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 4);
}
@Test
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
Result result = runTest("[0-9&&[^2468]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 5);
}
@Test
public void givenDigits_whenMatches_thenCorrect() {
Result result = runTest("\\d", "123");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenNonDigits_whenMatches_thenCorrect() {
Result result = runTest("\\D", "a6c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenWhiteSpace_whenMatches_thenCorrect() {
Result result = runTest("\\s", "a c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
Result result = runTest("\\S", "a c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenWordCharacter_whenMatches_thenCorrect() {
Result result = runTest("\\w", "hi!");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenNonWordCharacter_whenMatches_thenCorrect() {
Result result = runTest("\\W", "hi!");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a?", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{0,1}", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a*", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{0,}", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a+", "hi");
assertFalse(result.isFound());
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{1,}", "hi");
assertFalse(result.isFound());
}
@Test
public void givenBraceQuantifier_whenMatches_thenCorrect() {
Result result = runTest("a{3}", "aaaaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
Result result = runTest("a{3}", "aa");
assertFalse(result.isFound());
}
@Test
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
Result result = runTest("a{2,3}", "aaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
Result result = runTest("a{2,3}?", "aaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect() {
Result result = runTest("(\\d\\d)", "12");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect2() {
Result result = runTest("(\\d\\d)", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect3() {
Result result = runTest("(\\d\\d)(\\d\\d)", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
Result result = runTest("(\\d\\d)\\1", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
Result result = runTest("(\\d\\d)\\1", "1213");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtBeginning_thenCorrect() {
Result result = runTest("^dog", "dogs are friendly");
assertTrue(result.isFound());
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
Result result = runTest("^dog", "are dogs are friendly?");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtEnd_thenCorrect() {
Result result = runTest("dog$", "Man's best friend is a dog");
assertTrue(result.isFound());
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
Result result = runTest("dog$", "is a dog man's best friend?");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
Result result = runTest("\\bdog\\b", "a dog is friendly");
assertTrue(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
Result result = runTest("\\bdog\\b", "dog is man's best friend");
assertTrue(result.isFound());
}
@Test
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
Result result = runTest("\\bdog\\b", "snoop dogg is a rapper");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
Result result = runTest("\\bdog\\B", "snoop dogg is a rapper");
assertTrue(result.isFound());
}
@Test
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
Result result = runTest("\u00E9", "\u0065\u0301");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
Result result = runTest("dog", "This is a Dog");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
Result result = runTest("(?i)dog", "This is a Dog");
assertTrue(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
assertTrue(result.isFound());
}
@Test
public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
Pattern pattern = Pattern.compile("(.*)");
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text", matcher.group(1));
}
@Test
public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
}
@Test
public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() {
Pattern pattern = Pattern.compile("(?s)(.*)");
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
matcher.find();
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
}
@Test
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
Result result = runTest("(.*)", "text");
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
Result result = runTest("(.*)", "text", Pattern.LITERAL);
assertFalse(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL);
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertFalse(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertTrue(result.isFound());
}
@Test
public void givenMatch_whenGetsIndices_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("This dog is mine");
matcher.find();
assertEquals(5, matcher.start());
assertEquals(8, matcher.end());
}
@Test
public void whenStudyMethodsWork_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are friendly");
assertTrue(matcher.lookingAt());
assertFalse(matcher.matches());
}
@Test
public void whenMatchesStudyMethodWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dog");
assertTrue(matcher.matches());
}
@Test
public void whenReplaceFirstWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceFirst("cat");
assertEquals("cats are domestic animals, dogs are friendly", newStr);
}
@Test
public void whenReplaceAllWorks_thenCorrect() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceAll("cat");
assertEquals("cats are domestic animals, cats are friendly", newStr);
}
public synchronized static Result runTest(String regex, String text) {
pattern = Pattern.compile(regex);
matcher = pattern.matcher(text);
Result result = new Result();
while (matcher.find())
result.setCount(result.getCount() + 1);
if (result.getCount() > 0)
result.setFound(true);
return result;
}
public synchronized static Result runTest(String regex, String text, int flags) {
pattern = Pattern.compile(regex, flags);
matcher = pattern.matcher(text);
Result result = new Result();
while (matcher.find())
result.setCount(result.getCount() + 1);
if (result.getCount() > 0)
result.setFound(true);
return result;
}
}

View File

@ -0,0 +1,90 @@
package org.baeldung.java.md5;
import static org.junit.Assert.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import java.io.File;
import java.io.IOException;
import java.nio.*;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaMD5Test {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
@Test
public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException {
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase();
assertThat(myHash.equals(hash)).isTrue();
}
@Test
public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(filename)));
byte[] digest = md.digest();
String myChecksum = DatatypeConverter
.printHexBinary(digest).toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
@Test
public void givenPassword_whenHashingUsingCommons_thenVerifying() {
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
String md5Hex = DigestUtils
.md5Hex(password).toUpperCase();
assertThat(md5Hex.equals(hash)).isTrue();
}
@Test
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
HashCode hash = com.google.common.io.Files
.hash(new File(filename), Hashing.md5());
String myChecksum = hash.toString()
.toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
}

View File

@ -96,6 +96,7 @@
<module>spring-mvc-java</module>
<module>spring-mvc-no-xml</module>
<module>spring-mvc-xml</module>
<module>spring-mvc-tiles</module>
<module>spring-openid</module>
<module>spring-protobuf</module>
<module>spring-quartz</module>

View File

@ -10,7 +10,7 @@
<module>spring-cloud-config</module>
<module>spring-cloud-eureka</module>
<module>spring-cloud-hystrix</module>
<module>spring-cloud-integration</module>
<module>spring-cloud-bootstrap</module>
</modules>
<packaging>pom</packaging>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-integration</artifactId>
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
@ -17,9 +17,9 @@
<module>resource</module>
</modules>
<artifactId>part-1</artifactId>
<artifactId>spring-cloud-integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
</project>

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>part-1</module>
</modules>
</project>

85
spring-mvc-tiles/pom.xml Normal file
View File

@ -0,0 +1,85 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-mvc-tiles</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-mvc-tiles</name>
<description>Integrating Spring MVC with Apache Tiles</description>
<properties>
<springframework.version>4.3.2.RELEASE</springframework.version>
<apachetiles.version>3.0.5</apachetiles.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Apache Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${apachetiles.version}</version>
</dependency>
<!-- Servlet+JSP+JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>spring-mvc-tiles</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>spring-mvc-tiles</finalName>
</build>
</project>

View File

@ -0,0 +1,47 @@
package com.baeldung.tiles.springmvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.tiles.springmvc")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
/**
* Configure TilesConfigurer.
*/
@Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" });
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
/**
* Configure ViewResolvers to deliver views.
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
TilesViewResolver viewResolver = new TilesViewResolver();
registry.viewResolver(viewResolver);
}
/**
* Configure ResourceHandlers to serve static resources
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.tiles.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class ApplicationController {
@RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
return "home";
}
@RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET)
public String productsPage(ModelMap model) {
return "apachetiles";
}
@RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET)
public String contactUsPage(ModelMap model) {
return "springmvc";
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.tiles.springmvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Apache Tiles</title>
</head>
<body>
<h2>Tiles with Spring MVC Demo</h2>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<h2>Welcome to Apache Tiles integration with Spring MVC</h2>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC</title>
</head>
<body>
<h2>Spring MVC configured to work with Apache Tiles</h2>
</body>
</html>

View File

@ -0,0 +1,25 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><tiles:getAsString name="title" /></title>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
</head>
<body>
<div class="flex-container">
<tiles:insertAttribute name="header" />
<tiles:insertAttribute name="menu" />
<article class="article">
<tiles:insertAttribute name="body" />
</article>
<tiles:insertAttribute name="footer" />
</div>
</body>
</html>

View File

@ -0,0 +1,2 @@
<footer>copyright © Baeldung</footer>

View File

@ -0,0 +1,3 @@
<header>
<h1>Welcome to Spring MVC integration with Apache Tiles</h1>
</header>

View File

@ -0,0 +1,8 @@
<nav class="nav">
<a href="${pageContext.request.contextPath}/"></a>
<ul id="menu">
<li><a href="${pageContext.request.contextPath}/">Home</a></li>
<li><a href="${pageContext.request.contextPath}/springmvc">SpringMVC</a></li>
<li><a href="${pageContext.request.contextPath}/apachetiles">ApacheTiles</a></li>
</ul>
</nav>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<!-- Template Definition -->
<definition name="template-def"
template="/WEB-INF/views/tiles/layouts/defaultLayout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/views/tiles/templates/defaultHeader.jsp" />
<put-attribute name="menu" value="/WEB-INF/views/tiles/templates/defaultMenu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/tiles/templates/defaultFooter.jsp" />
</definition>
<!-- Main Page -->
<definition name="home" extends="template-def">
<put-attribute name="title" value="Welcome" />
<put-attribute name="body" value="/WEB-INF/views/pages/home.jsp" />
</definition>
<!-- Apache Tiles Page -->
<definition name="apachetiles" extends="template-def">
<put-attribute name="title" value="ApacheTiles" />
<put-attribute name="body" value="/WEB-INF/views/pages/apachetiles.jsp" />
</definition>
<!-- Spring MVC Page -->
<definition name="springmvc" extends="template-def">
<put-attribute name="title" value="SpringMVC" />
<put-attribute name="body" value="/WEB-INF/views/pages/springmvc.jsp" />
</definition>
</tiles-definitions>

View File

@ -0,0 +1,36 @@
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
text-align: center;
}
.flex-container > * {
padding: 15px;
-webkit-flex: 1 100%;
flex: 1 100%;
}
.article {
text-align: left;
}
header {background: black;color:white;}
footer {background: #aaa;color:white;}
.nav {background:#eee;}
.nav ul {
list-style-type: none;
padding: 0;
}
.nav ul a {
text-decoration: none;
}
@media all and (min-width: 768px) {
.nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;}
.article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;}
footer {-webkit-order:3;order:3;}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.7.3.201602250914-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
</configs>
<autoconfigs>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>

View File

@ -0,0 +1 @@
spring-userservice is using a in memory derby db. Right click -> run on server to run the project

320
spring-userservice/pom.xml Normal file
View File

@ -0,0 +1,320 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-userservice</groupId>
<artifactId>spring-userservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.5</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbynet</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbytools</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>spring-userservice</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.security.version>4.1.3.RELEASE</org.springframework.security.version>
<org.springframework.version>4.3.2.RELEASE</org.springframework.version>
<javassist.version>3.20.0-GA</javassist.version>
<!-- persistence -->
<hibernate.version>5.2.2.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<spring-data-jpa.version>1.10.2.RELEASE</spring-data-jpa.version>
<h2.version>1.4.192</h2.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<!-- <maven-war-plugin.version>2.6</maven-war-plugin.version> -->
</properties>
</project>

View File

@ -0,0 +1,42 @@
package org.baeldung.custom.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "org.baeldung.security" })
public class MvcConfig extends WebMvcConfigurerAdapter {
public MvcConfig() {
super();
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/");
registry.addViewController("/index");
registry.addViewController("/login");
registry.addViewController("/register");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@ -0,0 +1,89 @@
package org.baeldung.custom.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.baeldung.user.dao.MyUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-derby.properties" })
public class PersistenceDerbyJPAConfig {
@Autowired
private Environment env;
public PersistenceDerbyJPAConfig() {
super();
}
// beans
@Bean
public LocalContainerEntityManagerFactoryBean myEmf() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
@Bean
public MyUserDAO myUserDAO() {
final MyUserDAO myUserDAO = new MyUserDAO();
return myUserDAO;
}
}

View File

@ -0,0 +1,75 @@
package org.baeldung.custom.config;
import org.baeldung.security.MyUserDetailsService;
import org.baeldung.user.service.MyUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@Profile("!https")
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
public SecSecurityConfig() {
super();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.authenticationProvider(authenticationProvider());
// @formatter:on
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/*").permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/",true)
.failureUrl("/login?error=true")
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.logoutSuccessUrl("/");
// @formatter:on
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService());
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(11);
}
@Bean
public MyUserDetailsService myUserDetailsService() {
return new MyUserDetailsService();
}
@Bean
public MyUserService myUserService() {
return new MyUserService();
}
}

View File

@ -0,0 +1,50 @@
package org.baeldung.persistence.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(schema = "spring_custom_user_service")
public class MyUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
public MyUser() {
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
}

View File

@ -0,0 +1,37 @@
package org.baeldung.security;
import java.util.ArrayList;
import java.util.Collection;
import org.baeldung.persistence.model.MyUser;
import org.baeldung.user.dao.MyUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
MyUserDAO myUserDAO;
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
final MyUser user = myUserDAO.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + username);
}
else {
final Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(user.getUsername(), user.getPassword(), authorities);
}
}
}

View File

@ -0,0 +1,52 @@
package org.baeldung.security;
import javax.annotation.Resource;
import org.baeldung.user.service.MyUserService;
import org.baeldung.web.MyUserDto;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
@Resource
MyUserService myUserService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUserAccount(final MyUserDto accountDto, final Model model) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
model.addAttribute("name", auth.getName());
try {
myUserService.registerNewUserAccount(accountDto);
model.addAttribute("message", "Registration successful");
return "index";
}
catch(final Exception exc){
model.addAttribute("message", "Registration failed");
return "index";
}
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getHomepage(final Model model) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
model.addAttribute("name", auth.getName());
return "index";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String getRegister() {
return "register";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String getLogin() {
return "login";
}
}

View File

@ -0,0 +1,46 @@
package org.baeldung.user.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.baeldung.persistence.model.MyUser;
import org.springframework.stereotype.Repository;
@Repository
public class MyUserDAO {
@PersistenceContext
private EntityManager entityManager;
public MyUser findByUsername(final String username) {
final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class);
query.setParameter("username", username);
final List<MyUser> result = query.getResultList();
if (result != null && result.size() > 0) {
return result.get(0);
} else
return null;
}
public MyUser save(final MyUser user) {
entityManager.persist(user);
return user;
}
public void removeUserByUsername(String username) {
final Query query = entityManager.createQuery("delete from MyUser where username=:username");
query.setParameter("username", username);
query.executeUpdate();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(final EntityManager entityManager) {
this.entityManager = entityManager;
}
}

View File

@ -0,0 +1,49 @@
package org.baeldung.user.service;
import org.baeldung.persistence.model.MyUser;
import org.baeldung.user.dao.MyUserDAO;
import org.baeldung.web.MyUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class MyUserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
MyUserDAO myUserDAO;
public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception {
if (usernameExists(accountDto.getUsername())) {
throw new Exception("There is an account with that username: " + accountDto.getUsername());
}
final MyUser user = new MyUser();
user.setUsername(accountDto.getUsername());
user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
return myUserDAO.save(user);
}
public MyUser getUserByUsername(final String username) {
final MyUser user = myUserDAO.findByUsername(username);
return user;
}
public void removeUserByUsername(String username){
myUserDAO.removeUserByUsername(username);
}
private boolean usernameExists(final String username) {
final MyUser user = myUserDAO.findByUsername(username);
if (user != null) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,29 @@
package org.baeldung.web;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class MyUserDto {
@NotNull
@Size(min = 1)
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
}

View File

@ -0,0 +1,12 @@
# jdbc.X
jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver
jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true
jdbc.user=tutorialuser
jdbc.pass=tutorialpass
# hibernate.X
hibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

View File

@ -0,0 +1,88 @@
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<context:annotation-config></context:annotation-config>
<security:http auto-config="true">
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/login*" access="permitAll" />
<security:intercept-url pattern="/logout*" access="permitAll" />
<security:intercept-url pattern="/register*" access="permitAll" />
<security:csrf disabled="true"/>
<security:form-login login-page='/login' login-processing-url="/login" default-target-url="/" authentication-failure-url="/login?error=true"
always-use-default-target="true"/>
<security:logout logout-url="/logout" delete-cookies="JSESSIONID" logout-success-url="/"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="myUserDetailsService" >
<security:password-encoder ref="passwordEncoder"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<bean id="myUserDetailsService" class="org.baeldung.security.MyUserDetailsService" />
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<constructor-arg value="11"/>
</bean>
<context:component-scan base-package="org.baeldung.security"></context:component-scan>
<context:component-scan base-package="org.baeldung.user"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:property-placeholder location="classpath:persistence-derby.properties"/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="org.baeldung.persistence.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> <property name="generateDdl" value="${jpa.generateDdl}" /> <property name="databasePlatform"
value="${persistence.dialect}" /> </bean> -->
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven/>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

View File

@ -0,0 +1,35 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome!</title>
</head>
<body>
<c:url value="/register" var="registerUrl" />
<c:url value="/login" var="loginUrl"/>
<c:url value="/logout" var="logoutUrl"/>
<a href="${registerUrl }">Register</a>
<br /><br/>
<sec:authorize access="!isAuthenticated()">
<a href="${loginUrl }">Login</a>
</sec:authorize>
<br><br>
${message }
<br><br>
<sec:authorize access="isAuthenticated()">
Hello, ${name }!
<br>
<br>
<a href="${logoutUrl }">Logout</a>
</sec:authorize>
</body>
</html>

View File

@ -0,0 +1,29 @@
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head></head>
<body>
<h1>Login</h1>
<form name='f' action="login" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
<c:if test="${param.error }">Username or password invalid! </c:if>
</body>
</html>

View File

@ -0,0 +1,23 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome!</title>
</head>
<body>
<c:url value="/register" var="registerUrl" />
Register here:<br><br>
<form action="${registerUrl }" method="POST">
Username: <input type="text" name="username"/><br>
Password: <input type="password" name="password"/><br>
<input type="submit" value="Register"/>
</form>
</body>
</html>

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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/web-app_3_1.xsd"
version="3.1">
<display-name>Spring MVC Application</display-name>
<!--
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.custom.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
-->
<!-- Spring child -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1,85 @@
package org.baeldung.userservice;
import org.baeldung.custom.config.MvcConfig;
import org.baeldung.custom.config.PersistenceDerbyJPAConfig;
import org.baeldung.custom.config.SecSecurityConfig;
import org.baeldung.user.service.MyUserService;
import org.baeldung.web.MyUserDto;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class })
@WebAppConfiguration
public class CustomUserDetailsServiceTest {
private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest");
public static final String USERNAME = "user";
public static final String PASSWORD = "pass";
public static final String USERNAME2 = "user2";
@Autowired
MyUserService myUserService;
@Autowired
AuthenticationProvider authenticationProvider;
@Test
public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() {
try {
MyUserDto userDTO = new MyUserDto();
userDTO.setUsername(USERNAME);
userDTO.setPassword(PASSWORD);
myUserService.registerNewUserAccount(userDTO);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD);
Authentication authentication = authenticationProvider.authenticate(auth);
assertEquals(authentication.getName(), USERNAME);
} catch (Exception exc) {
LOG.log(Level.SEVERE, "Error creating account");
} finally {
myUserService.removeUserByUsername(USERNAME);
}
}
@Test (expected = BadCredentialsException.class)
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
try {
MyUserDto userDTO = new MyUserDto();
userDTO.setUsername(USERNAME);
userDTO.setPassword(PASSWORD);
try {
myUserService.registerNewUserAccount(userDTO);
}
catch (Exception exc) {
LOG.log(Level.SEVERE, "Error creating account");
}
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
Authentication authentication = authenticationProvider.authenticate(auth);
}
finally {
myUserService.removeUserByUsername(USERNAME);
}
}
}